【问题标题】:Tkinter button disable not workingTkinter 按钮禁用不起作用
【发布时间】:2015-06-18 22:23:28
【问题描述】:

我是 Python 新手,甚至是 GUI 编程新手。

我有一个按钮和两个旋转框,我想在单击开始按钮后禁用它们。 我用谷歌搜索了 5 种不同的方法来禁用 Tkinter 按钮,但似乎都没有。从理论上讲,旋转框应该以同样的方式被禁用,但我只是没有任何运气。 对整个 GUI 感到非常沮丧。

self.gps_comself.arduino_com 是两个旋转框

如您所见,我尝试使用update() 作为按钮,但它不起作用。我已经看到在所有大写字母、首字母大写字母和引号的不同变体中使用 disabled 的代码变体。当前的语法不会从 Spyder 发出警告/错误。

我认为找到这个问题的答案很容易,但我已经研究了几个小时了。

def OnButtonClickStart(self):
    self.labelVariable.set( self.entryVariable.get())
    self.entry.focus_set()
    self.entry.selection_range(0, Tkinter.END)
    self.button_start.config(state = 'DISABLED')
    self.button_start.update()
    self.gps_com.config(state = 'DISABLED')
    self.arduino_com.config(state = 'DISABLED')

【问题讨论】:

  • 您确定 Spyder 发行版支持您尝试使用的功能吗?
  • 如果你还没有尝试过,请尝试Tkinter.DISABLED"disabled"(全部小写带引号[单双不重要])。
  • 您是否 100% 确定该回调已实际执行?尝试在其中添加一些print 声明。此外,该按钮是否触发了任何可能阻塞 UI 的长时间运行的操作?
  • 我注释掉了除 GUI 内容之外的所有其他代码。我正在确保正如你所建议的那样它没有在某个地方被阻止。当前的代码迭代只是带有几个按钮和两个旋转框的 GUI 窗口,我试图通过单击“开始”按钮来禁用它们。

标签: python tkinter


【解决方案1】:

试试这段代码,看看文本更新和按钮是否按预期禁用/重新启用:

import tkinter as tk

class Window():

    def __init__(self, root):

        self.frame = tk.Frame(root)
        self.frame.grid()

        self.i = 0
        self.labelVar = tk.StringVar()
        self.labelVar.set("This is the first text: %d" %self.i) 

        self.label = tk.Label(self.frame, text = self.labelVar.get(), textvariable = self.labelVar)
        self.label.grid(column = 0, row = 0)

        self.button = tk.Button(self.frame, text = "Update", command = self.updateLabel)
        self.button.grid(column = 1, row = 0)

        self.enableButton = tk.Button(self.frame, text = "Enable Update Button", state = 'disabled', command = self.enable)
        self.enableButton.grid(column = 2, row = 0)

    def updateLabel(self):

        self.i += 1
        self.labelVar.set("This is the new text: %d" %self.i)
        self.button.config(state = 'disabled')
        self.enableButton.config(state = 'active')

    def enable(self):

        self.button.config(state = 'active')
        self.enableButton.config(state = 'disabled')

root = tk.Tk()
window = Window(root)
root.mainloop()

如果这比您更有效 a) 使用错误的关键字('disabled',全小写,在 Python 2.5/3.4 中(我昨晚测试了 3.4))或 b) 您尝试调用的函数不是按照 tobias_k 的建议正确执行。

【讨论】:

  • 定期在函数中放置print 语句是一个有用的提示。我可能会在您尝试更改按钮状态之前和之后建议一个。
  • 您的代码运行良好。必须是未执行的回调。将向它添加一些调试打印,看看出了什么问题。
  • 至少对于 Python 3,导入的情况不正确。如果您认为这是错误的,请将其重新设置。一旦我更新了那行代码,你的代码就帮了我。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-05-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多