Tkinter选项菜单禁用但可扩展

2024-06-16 15:04:07 发布

您现在位置:Python中文网/ 问答频道 /正文

在保留检查可用选项的可能性的同时,是否有写保护tkinterOptionMenu的解决方案?你知道吗

背景:我有一个tkinterOptionMenu,其中包含用户可以“快速加载”到应用程序中的文件选择。但是,用户可能没有加载新文件的权限。你知道吗

我现在通过将OptionMenu置于disabled状态来表示这一点。但是下拉列表不能再扩展了;这意味着用户不能查看可用的文件。你知道吗


Tags: 文件用户应用程序权限列表状态选项解决方案
2条回答

您可以禁用菜单的每个条目,而不是完全使用menu.entryconfigure(<index>, state='disabled')禁用optionmenu。 optionmenu的菜单存储在“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中使用的菜单是tkinter Menu(),您可以访问它。你知道吗

示例:

Op = OptionMenu(root, var, 'First', 'Second', 'Third')
Op.pack()

# Op_Menu is the Menu() class used for OptionMenu
Op_Menu = Op['menu']

然后您可以使用Op菜单执行与Menu()相同的操作


在你的情况下,如何禁用?你知道吗

我们可以根据用户使用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

为了更好地理解Menu()是如何在OptionMenu类中定义的,可以check the source code of ^{} class(从第3959行开始)

相关问题 更多 >