有没有办法触发tkinter中按钮的可点击性?

2024-05-23 17:16:11 发布

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

我想要一个按钮,它只在满足某些条件后执行命令。你知道吗

这是我们的按钮:

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之后,按钮能够正常工作。你知道吗

有什么优雅的方法可以做到这一点吗?你知道吗


Tags: fromimportselfmatplotlibinittkinterasbutton
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)

定义按钮时有一个state字段,可以设置为ENABLEDDISABLED。您可以在启动时将按钮定义为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()

相关问题 更多 >