【问题标题】:Enabling a checkbox Tkinter (Python 3.4)启用复选框 Tkinter (Python 3.4)
【发布时间】:2017-11-10 20:26:37
【问题描述】:
我在 Tkinter 中有一个 CheckBox。我希望它始终保持选中状态,但禁用复选框会破坏 GUI 应用程序的外观。我想将其状态保持为“正常”,如果用户尝试取消选中它,则该框保持选中状态,或者在之后立即重新选中。
global ghistory
ghistory = IntVar()
cc = Checkbutton(frame3, text="History", variable=ghistory)
cc.select()
cc.pack()
我该怎么做?
【问题讨论】:
标签:
python
user-interface
checkbox
tkinter
【解决方案1】:
添加一个将变量设置为 True 的函数。一个快速的 lambda 函数就可以解决问题:
cc=tk.Checkbutton(frame3,text="History",variable=ghistory, command=lambda:ghistory.set(1))
或者你可以使用select 命令:
cc=tk.Checkbutton(frame3,text="History",variable=ghistory)
cc['command'] = cc.select
【解决方案2】:
使用 .cget('state') 查看按钮是否被禁用...
self.widget_checkbutton = tk.Checkbutton(self, variable=self.some_variable, command=lambda:self.stay_checked())
def stay_checked(self):
if self.widget_checkbutton.cget('state') == 'disabled':
self.widget_checkbutton.select()
else:
self.widget_checkbutton.deselect()
#this will only let the button be checked if widget is active.
(基本上,如果某些小部件被禁用...您告诉复选框保持不变。否则,如果某些小部件正常,您允许复选框正常工作...选择...取消选择...)