在Tkin中单击后禁用按钮

2024-09-29 02:23:29 发布

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

我是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: global name 'nButton' is not defined


Tags: lambdain应用程序forindexreturntkinterdef
2条回答

这对我现在正在做的工作很有帮助

from math import floor



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

这里有几个问题:

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

  2. Tkinter小部件的grid方法总是返回None。所以,您需要在他们自己的线路上给grid打任何电话。

  3. 无论何时将按钮的command选项分配给需要参数的函数,都必须使用^{}或类似的选项来“隐藏”该函数的调用,直到单击按钮。有关详细信息,请参见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()

相关问题 更多 >