我想要一个按钮,该按钮仅在满足某些条件后才执行命令。
这是我们的按钮:
import tkinter as tk
from matplotlib import *
from tkinter import ttk, messagebox, filedialog
class Hauptmenu(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
ttk.Button(self, text='Button', command=self.doSomething).grid(row=7,column=4, sticky="w")
clickability_criterion=False
因此,我希望在将标准设置为True后,按钮才能起作用。
有什么优雅的方法可以做到这一点吗?
答案 0 :(得分:4)
定义按钮时有一个state
字段,您可以将其设置为ENABLED
或DISABLED
。您可以在启动时将按钮定义为DISABLED
,
import tkinter as tk
from matplotlib import *
from tkinter import ttk, messagebox, filedialog
tk = tk.Tk()
myButton = ttk.Button(tk, text='Button', command=self.doSomething, state = 'disabled')
myButton.grid(row=7,column=4, sticky="w")
满足某些条件后,您可以将状态更改为NORMAL
:
myButton['state'] = 'normal'
这应该可以解决问题。
编辑:关于运行时更新,我将在您的类中定义一个方法来为您更新状态,诸如此类:
class Hauptmenu:
def __init__(self, parent):
self.myParent = parent
self.myContainer = tk.Frame(parent)
self.myContainer.pack()
self.button = tk.Button(self.myContainer)
self.button.configure(text="Button", command=self.doSomething, state = 'disabled')
self.button.pack()
def doSomething(self):
print('This button has been pressed')
def changeButtonState(self, state):
self.button['state'] = state
root = tk.Tk()
c = Hauptmenu(root)
c.changeButtonState('normal')
tk.mainloop()
答案 1 :(得分:2)
您可以这样创建一个禁用按钮:
ttk.Button(self, text='Button', state = ttk.DISABLED, command=self.doSomething).grid(row=7,column=4, sticky="w")
然后像这样启用它:
variable_inwhich_button_is_saved.configure(state=ttk.ENABLED)