gpt4 book ai didi

python - Tkinter OptionMenu 已禁用但可扩展

转载 作者:太空宇宙 更新时间:2023-11-04 09:31:01 24 4
gpt4 key购买 nike

是否有写保护 tkinter OptionMenu 同时保留检查可用选项的可能性的解决方案?

背景:我有一个 tkinter OptionMenu,其中包含用户可以“快速加载”到应用程序中的一系列文件。但是,用户可能没有加载新文件的权限。

我现在通过将 OptionMenu 置于 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()

/image/0Dxmj.png

为了更好地理解 Menu() 是如何在 OptionMenu 类中定义的,可以 check the source code of OptionMenu() class . (来自 3959 行)

关于python - Tkinter OptionMenu 已禁用但可扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55741962/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com