[英]How to stop Tkinter Message widget from resizing?
我正在创建三个“消息小部件”,但它们似乎根据内部的内容调整宽度和高度,是否可以防止这样的事情?
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()
更新:
你有几个选项,但根据你的评论widgets resize according to their content, I want them all with same width
我将使用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()
您可以通过查找最长消息的宽度,然后使用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()
结果:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.