Python 在Tkinter中单击后禁用按钮

Python 在Tkinter中单击后禁用按钮,python,button,tkinter,Python,Button,Tkinter,我是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, wid

我是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)
我要做的是在单击按钮后禁用它们。 我试过了

但它给了我以下错误:

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


这里有几个问题:

  • 无论何时动态创建小部件,都需要在集合中存储对它们的引用,以便以后可以访问它们

  • Tkinter小部件的
    grid
    方法始终返回
    None
    。因此,您需要将对
    grid
    的任何调用放在它们自己的线路上

  • 每当将按钮的
    命令
    选项指定给需要参数的函数时,必须使用或类似的方法“隐藏”该函数的调用,直到单击按钮为止。有关详细信息,请参阅

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

    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()
    

    这对我目前正在进行的一项工作非常有帮助,添加了一个小的修正

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

    这是一个解决方案吗?
    from math import floor
    
    
    
    button.grid(padx=2, pady=2, row=index%3, column=floor(index/3))