【问题标题】:How to change Tkinter Button state from disabled to normal?如何将 Tkinter 按钮状态从禁用更改为正常?
【发布时间】:2013-04-09 10:19:57
【问题描述】:

当某些事件发生时,我需要将Button 的状态从DISABLED 更改为NORMAL

这是我的 Button 的当前状态,当前处于禁用状态:

  self.x = Button(self.dialog, text="Download",
                state=DISABLED, command=self.download).pack(side=LEFT)

 self.x(state=NORMAL)  # this does not seem to work

任何人都可以帮助我如何做到这一点?

【问题讨论】:

    标签: python button tkinter state


    【解决方案1】:

    您只需将按钮self.xstate 设置为normal

    self.x['state'] = 'normal'
    

    self.x.config(state="normal")
    

    此代码将进入将导致启用按钮的事件的回调中。


    另外,正确的代码应该是:

    self.x = Button(self.dialog, text="Download", state=DISABLED, command=self.download)
    self.x.pack(side=LEFT)
    

    Button(...).pack() 中的方法pack 返回None,您将其分配给self.x。您实际上想将Button(...) 的返回值分配给self.x,然后在下一行中使用self.x.pack()

    【讨论】:

    • 应该补充一点,这段代码将进入触发按钮启用的事件的回调中。
    • 我试过得到错误:self.x['state'] = 'enabled' : 'NoneType' object does not support item assignment
    • self.y=Button(self.dialog, text="Check URL",state=NORMAL,command=self.callback).pack(side=RIGHT) def callback(self): self. x['state'] = 'enabled' 我添加了这两行...似乎仍然不起作用..
    • @scandalous 不要将 Button().pack() 分配给 self.x。这是没有意义的。 pack() 函数返回无
    • 感谢盛工作 :) 顺便说一句,我使用的是 python 2.7,所以 self.x['state'] = 'active' 只是提醒其他可能遇到同样情况的人
    【解决方案2】:

    我认为更改小部件选项的一种快速方法是使用configure 方法。

    在你的情况下,它看起来像这样:

    self.x.configure(state=NORMAL)
    

    【讨论】:

      【解决方案3】:

      这对我有用。我不确定为什么语法不同,但是尝试激活、非活动、停用、禁用等的每种组合都非常令人沮丧。在小写大写的引号中,在括号中的括号中的引号中等等。好吧,这里是出于某种原因,对我来说获胜的组合.. 与其他人不同?

      import tkinter
      
      class App(object):
          def __init__(self):
              self.tree = None
              self._setup_widgets()
      
          def _setup_widgets(self):
              butts = tkinter.Button(text = "add line", state="disabled")
              butts.grid()
      
      def main():  
          root = tkinter.Tk()
          app = App()
          root.mainloop()
      
      if __name__ == "__main__":
          main()
      

      【讨论】:

      • 你的不一样,因为你没有从 tkinter 导入常量,from tkinter import * 这将导入 DISABLED 和其他常量,否则 tkinter.DISABLED 将工作相同。
      猜你喜欢
      • 1970-01-01
      • 2021-03-20
      • 2018-08-05
      • 1970-01-01
      • 1970-01-01
      • 2019-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多