我正在创建三个“消息窗口小部件”,但它们似乎根据内部的内容调整宽度和高度,是否可以防止这样的事情?
from tkinter import *
root = Tk()
root.configure(background = 'Yellow')
root.geometry('500x400')
a = '{}'.format('The Elepthan is Big')
b = '{}'.format('The Bird')
c = '{}'.format('The Lion is big and ferocious, kills any animal')
msg = Message(root, text = a, width=300, justify='left')
msg.config(bg='lightgreen',relief=RIDGE, font=('times', 9), pady=-2, borderwidth=3)
msg.pack()
msg = Message(root, text = b, width=300, justify='left')
msg.config(bg='lightgreen',relief=RIDGE, font=('times', 9), pady=-2, borderwidth=3)
msg.pack()
msg = Message(root, text = c, width=300, justify='left')
msg.config(bg='lightgreen',relief=RIDGE, font=('times', 9), pady=-2, borderwidth=3)
msg.pack()
root.mainloop()
答案 0 :(得分:3)
更新:
您可以在此处选择一些选项,但根据您的评论widgets resize according to their content, I want them all with same width
,我将使用pack()
几何管理器提供最符合您需求的示例。
for pack至少最简单的选择是pack(fill = BOTH)
最快捷的方式就是使用框架。框架将调整为最大的文本,并且在所有消息窗口小部件上使用pack(fill = BOTH)
会将较小的窗口扩展为框架的大小,该框架也是最大窗口小部件的大小。
from tkinter import *
root = Tk()
root.configure(background = 'Yellow')
root.geometry('500x400')
a = '{}'.format('The Elepthan is Big')
b = '{}'.format('The Bird')
c = '{}'.format('The Lion is big and ferocious, kills any animal')
frame = Frame(root)
frame.pack()
msg = Message(frame, text = a, width=300, justify='left')
msg.config(bg='lightgreen',relief=RIDGE, font=('times', 9), pady=-2, borderwidth=3)
msg.pack(fill=BOTH)
msg = Message(frame, text = b, width=300, justify='left')
msg.config(bg='lightgreen',relief=RIDGE, font=('times', 9), pady=-2, borderwidth=3)
msg.pack(fill=BOTH)
msg = Message(frame, text = c, width=300, justify='left')
msg.config(bg='lightgreen',relief=RIDGE, font=('times', 9), pady=-2, borderwidth=3)
msg.pack(fill=BOTH)
root.mainloop()
答案 1 :(得分:2)
您可以通过查找最长邮件的宽度,然后使用Message
窗口小部件padx
选项将所有邮件的长度置于该长度值中来实现。这是一个例子:
from tkinter import *
import tkinter.font as tkFont
root = Tk()
root.configure(background='Yellow')
root.geometry('500x400')
a = 'The Elepthan is Big'
b = 'The Bird'
c = 'The Lion is big and ferocious, kills any animal'
messages = a, b, c
msgfont = tkFont.Font(family='times', size=9)
maxwidth = max(msgfont.measure(text) for text in messages) # get pixel width of longest one
for text in messages:
msg = Message(root, text=text, width=maxwidth, justify='left')
padx = (maxwidth-msgfont.measure(text)) // 2 # padding needed to center text
msg.config(bg='lightgreen', relief=RIDGE, font=msgfont, padx=padx, pady=-2, borderwidth=3)
msg.pack()
root.mainloop()
结果: