[英]Checking if Tkinter Widget (OptionMenu) is disabled
我觉得自己已经在网络上搜寻了一个永恒的事物,对我的问题做了一千次的表述,我觉得这很简单。
我想知道是否有一种方法可以检查Tkinter Widget是否处于活动状态(未显示为灰色/禁用状态)。 我有一组开始禁用的OptionMenu,并且在单击复选框时被配置为state=ACTIVE
,以便用户可以选择要使用的OptionMenu。
当我尝试“提交” OptionMenus中的字段时,我只想要那些ACTIVE
。 我已经尝试过if OptionMenu.state == ACTIVE
但是我得到一个错误,即OptionMenu没有属性状态,即使我之前进行了配置。
这是我的代码示例:
from tkinter import *
class Application(Frame):
# Initializing the window and the required variables
def __init__(self, master=None):
Frame.__init__(self, master)
self.checkbox_in_use = BooleanVar(self, False)
self.checkbox = Checkbutton(self, text="check",
var=self.checkbox_in_use,
command=self.check_change
self.checkbox.grid(row=0, column=1, sticky='W')
self.menu = OptionMenu(title_setting,
"Menu",
"Menu",
["Menu1", "Menu2"])
self.menu.grid(row=1, column=1)
self.menu.config(state=DISABLED)
submit = Button(self, text="submit",
command=self.submit_function)
submit.grid(row=2, column=0)
self.master = master
self.init_window()
# Initialize the window
def init_window(self):
self.master.title("Example")
self.pack(fill=BOTH, expand=1)
def check_change(self):
if self.checkbox_in_use.get():
self.menu.config(state=ACTIVE)
else:
self.menu.config(state=DISABLED)
def submit_function(self):
# This is the part I want to do something with.
if self.menu.state == ACTIVE:
print("You are good to go! Do the stuff.")
root = Tk()
root.geometry("400x300")
app = Application(root)
root.mainloop()
感谢您的所有回复。
您只需要cget()
。 self.menu.cget('state')
可以解决问题。
就是说,我想指出您代码中的其他内容。
您的Application
类开头已经有一个__init__
,所以为什么使用:
# Initialize the window
def init_window(self):
self.master.title("Example")
self.pack(fill=BOTH, expand=1)
您实际上不应该从框架类内部打包框架,而应该在调用类时打包。 打包也不会在这里工作,它将引发错误。 改为执行以下操作: app = Application(root).grid()
。
看一下下面重新格式化的示例(使用cget()
)。
from tkinter import *
class Application(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.master.title("Example")
self.checkbox_in_use = BooleanVar(self, False)
self.checkbox = Checkbutton(self, text="check", var=self.checkbox_in_use, command=self.check_change)
self.checkbox.grid(row=0, column=1, sticky='W')
self.menu = OptionMenu(master,"Menu","Menu",["Menu1", "Menu2"])
self.menu.grid(row=1, column=1)
self.menu.config(state=DISABLED)
Button(self, text="submit", command=self.submit_function).grid(row=2, column=0)
def check_change(self):
if self.checkbox_in_use.get():
self.menu.config(state=ACTIVE)
else:
self.menu.config(state=DISABLED)
def submit_function(self):
print(self.menu.cget('state'))
root = Tk()
root.geometry("400x300")
app = Application(root).grid()
root.mainloop()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.