[英]Tkinter OptionMenu disabled but expandable
Is there any solution of write-protecting a tkinter
OptionMenu
while retaining the possibility to inspect the available Options? 是否有任何解决方案写保护tkinter
OptionMenu
同时保留检查可用选项的可能性?
Background: I have a tkinter OptionMenu
containing a selection of files that the user can "quick-load" into the application. 背景:我有一个OptionMenu
其中包含OptionMenu
用户“快速加载”到应用程序中的文件选择。 However it might be that the user does not have permission to load new files. 但是,可能是用户无权加载新文件。
I now indicate this by putting the OptionMenu
in disabled
state. 现在,我通过将OptionMenu
置于disabled
状态来表明这一点。 But then the dropdown cannot be expanded anymore; 但是,下拉列表无法再扩展。 meaning that the user cannot look at the available files. 表示用户无法查看可用文件。
You can disable each entry of the menu instead of disabling the optionmenu totally using menu.entryconfigure(<index>, state='disabled')
. 您可以禁用菜单的每个条目,而不是使用menu.entryconfigure(<index>, state='disabled')
完全禁用选项菜单。 The menu of an optionmenu is stored in the 'menu' property: 选项菜单的菜单存储在'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')
So you can view all the items in the menu but they are not clickable. 因此,您可以查看菜单中的所有项目,但无法单击。
Yes, it is possible to disable the menu and still be able to open it just to see the list. 是的,可以禁用菜单,但仍然可以打开菜单以查看列表。 The menu used in OptionMenu
is tkinter Menu()
and you can access it. OptionMenu
使用的菜单是OptionMenu
Menu()
,您可以访问它。
Example: 例:
Op = OptionMenu(root, var, 'First', 'Second', 'Third')
Op.pack()
# Op_Menu is the Menu() class used for OptionMenu
Op_Menu = Op['menu']
Then you can do anything with the Op
menu same as Menu()
然后,您可以使用与Menu()
相同的Op
菜单执行任何Op
We can use menu.entryconfig(index, options)
to configure state = 'disabled' / 'normal'
as per the user. 我们可以根据用户使用menu.entryconfig(index, options)
来配置state = 'disabled' / 'normal'
。
Example: 例:
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()
For better understanding on how the Menu()
is defined inside OptionMenu
class can check the source code of OptionMenu()
class . 为了更好地理解OptionMenu
类中如何定义Menu()
可以检查OptionMenu()
类的源代码 。 (from line 3959 ) (从3959行开始)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.