[英]Tkinter OptionMenu disabled but expandable
是否有任何解决方案写保护tkinter
OptionMenu
同时保留检查可用选项的可能性?
背景:我有一个OptionMenu
其中包含OptionMenu
用户“快速加载”到应用程序中的文件选择。 但是,可能是用户无权加载新文件。
现在,我通过将OptionMenu
置于disabled
状态来表明这一点。 但是,下拉列表无法再扩展。 表示用户无法查看可用文件。
您可以禁用菜单的每个条目,而不是使用menu.entryconfigure(<index>, state='disabled')
完全禁用选项菜单。 选项菜单的菜单存储在'menu'属性中:
import tkinter as tk
root = tk.Tk()
var = tk.StringVar(root)
opmenu = tk.OptionMenu(root, var, *['item %i' % i for i in range(5)])
opmenu.pack()
menu = opmenu['menu']
for i in range(menu.index('end') + 1):
menu.entryconfigure(i, state='disabled')
因此,您可以查看菜单中的所有项目,但无法单击。
是的,可以禁用菜单,但仍然可以打开菜单以查看列表。 OptionMenu
使用的菜单是OptionMenu
Menu()
,您可以访问它。
例:
Op = OptionMenu(root, var, 'First', 'Second', 'Third')
Op.pack()
# Op_Menu is the Menu() class used for OptionMenu
Op_Menu = Op['menu']
然后,您可以使用与Menu()
相同的Op
菜单执行任何Op
我们可以根据用户使用menu.entryconfig(index, options)
来配置state = 'disabled' / 'normal'
。
例:
import tkinter as tk
root = tk.Tk()
root.geometry('250x250+100+100')
str = tk.StringVar()
str.set('Select')
Op = tk.OptionMenu(root, str, "First", "Second", "Third")
Op.pack()
# This will disable the First and Third entries in the Op
# state = 'disable' / 'normal'
Op['menu'].entryconfig(0, state='disable')
Op['menu'].entryconfig("Third", state='disable')
entries = Op['menu'].index('end') # This will get the total no. of entries.
# If you want to disable all of the entries uncomment below 2 lines.
# for i in range(entries+1):
# Op['menu'].entryconfig(i, state='disable')
root.mainloop()
为了更好地理解OptionMenu
类中如何定义Menu()
可以检查OptionMenu()
类的源代码 。 (从3959行开始)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.