【问题标题】:Disabling buttons after click in Tkinter在 Tkinter 中单击后禁用按钮
【发布时间】:2014-01-03 00:22:37
【问题描述】:

我是 Python 新手,我正在尝试使用 Tkinter 制作一个简单的应用程序。

def appear(x):
    return lambda: results.insert(END, x)

letters=["A", "T", "D", "M", "E", "A", "S", "R", "M"] 

for index in range(9): 
    n=letters[index] 
    nButton = Button(buttons, bg="White", text=n, width=5, height=1,
    command =appear(n), relief=GROOVE).grid(padx=2, pady=2, row=index%3,
    column=index/3)

我想要做的是在单击按钮后禁用它们。 我试过了

def appear(x):
    nButton.config(state="disabled")
    return lambda: results.insert(END, x)

但它给了我以下错误:

NameError:未定义全局名称“nButton”

【问题讨论】:

    标签: python button tkinter


    【解决方案1】:

    这里有几个问题:

    1. 每当您动态创建小部件时,您需要将它们的引用存储在一个集合中,以便您以后可以访问它们。

    2. Tkinter 小部件的grid 方法总是返回None。因此,您需要将任何对grid 的呼叫放在他们自己的线路上。

    3. 每当您将按钮的command 选项分配给需要参数的函数时,您必须使用lambda 或类似的“隐藏”该函数的调用,直到单击按钮。如需更多信息,请参阅https://stackoverflow.com/a/20556892/2555451

    以下是解决所有这些问题的示例脚本:

    from Tkinter import Tk, Button, GROOVE
    
    root = Tk()
    
    def appear(index, letter):
        # This line would be where you insert the letter in the textbox
        print letter
    
        # Disable the button by index
        buttons[index].config(state="disabled")
    
    letters=["A", "T", "D", "M", "E", "A", "S", "R", "M"]
    
    # A collection (list) to hold the references to the buttons created below
    buttons = []
    
    for index in range(9): 
        n=letters[index]
    
        button = Button(root, bg="White", text=n, width=5, height=1, relief=GROOVE,
                        command=lambda index=index, n=n: appear(index, n))
    
        # Add the button to the window
        button.grid(padx=2, pady=2, row=index%3, column=index/3)
    
        # Add a reference to the button to 'buttons'
        buttons.append(button)
    
    root.mainloop()
    

    【讨论】:

      【解决方案2】:

      这对我目前正在进行的工作非常有帮助,可以添加一个小的更正

      from math import floor
      
      
      
      button.grid(padx=2, pady=2, row=index%3, column=floor(index/3))
      

      【讨论】:

      • 这是一个解决方案吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-20
      • 1970-01-01
      • 2014-06-29
      • 2016-10-20
      相关资源
      最近更新 更多