繁体   English   中英

Tkinter OptionMenu已禁用但可以扩展

[英]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()

https://i.stack.imgur.com/0Dxmj.png

为了更好地理解OptionMenu类中如何定义Menu()可以检查OptionMenu()类的源代码 (从3959行开始)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM