如何使OptionMenu保持相同的宽度?
我有一个创建 OptionMenu
小部件的代码片段。
...
options = ('White', 'Grey', 'Black', 'Red', 'Orange',
'Yellow', 'Green', 'Blue', 'Cyan', 'Purple')
var = StringVar()
optionmenu = OptionMenu(par, var, *options)
optionmenu.grid(column=column, row=row)
...
我遇到的一个问题是每次选择一个新选项时,小部件的宽度都会发生变化。我相信这是由于小部件中的文本改变了宽度。如何使小部件保持一致的宽度?
I have a snippet which creates an OptionMenu
widget.
...
options = ('White', 'Grey', 'Black', 'Red', 'Orange',
'Yellow', 'Green', 'Blue', 'Cyan', 'Purple')
var = StringVar()
optionmenu = OptionMenu(par, var, *options)
optionmenu.grid(column=column, row=row)
...
One problem I've encountered is every time a new option is selected, the width of the widget changes. I believe this is due to the text within the widget changing widths. How do I make the widget hold a consistent width?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
据我所知,您可以使用
optionmenu.config(width=)
,如下所示:To the best of my knowledge, you can use
optionmenu.config(width=<YOUR_WIDTH>)
as follows:当您使用
grid
命令将小部件放置在其父级中时,让小部件填充其单元格(尝试sticky="ew"
)When you use the
grid
command to place the widget in its parent, have the widget fill its cell (trysticky="ew"
)我和12年前的OP一模一样——将下拉菜单放在一个框架中,却发现没有解决方案可以将它们设置为水平扩展并填充该框架。因此,每当选择不同长度的选项时,它们总是会调整大小(并重新居中)。 Sticky='' 没有任何效果。 width='' 有效,但现在您设置的是仅针对一种分辨率进行优化的固定宽度。
当然,糟糕的解决方案是使用等宽字体并在下拉列表中所有选项的末尾添加空格。我只是不明白为什么没有真正的解决方案。结果,这些下拉菜单看起来绝对很糟糕。
I'm in the exact same boat as the OP was 12 years ago - placing dropdowns in a frame, only to discover that no solution exists for setting them to expand horizontally and fill that frame. As a result they're always resizing (and re-centering) any time a different-length option is selected. sticky='' has no effect whatsoever. width='' works, but now you're setting a fixed width that is only optimized for one resolution.
Of course the terrible solution is to use a monospace font and add spaces to the end of all the options in the dropdown. I just don't understand how there can be no real solution for this. These dropdowns look absolutely atrocious as a result.
这可以通过
“不是最佳”来完成,因为您必须猜测列的像素宽度,但它可以工作。
我发现这里有一些链接对于得出这个答案很有用。
https://www.pythontutorial.net/tkinter/tkinter-grid/
< a href="https://stackoverflow.com/questions/52844549/set-minimum-width-of-column-in-grid">设置网格中列的最小宽度
https://tkdocs.com/tutorial/grid.html
This can be done with
Not optimal as you have to guess the pixel width of the colume, but it works.
Here are some links, I found to be useful in coming up with this answer.
https://www.pythontutorial.net/tkinter/tkinter-grid/
Set minimum width of column in grid
https://tkdocs.com/tutorial/grid.html