+-
我是 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
最佳答案
这里有一些问题:
>每当动态创建窗口小部件时,都需要将对它们的引用存储在集合中,以便以后可以访问它们.
> Tkinter小部件的网格方法始终返回None.因此,您需要将对网格的任何调用放在自己的线路上.
>每当将按钮的命令选项分配给需要自变量的函数时,都必须使用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()
点击查看更多相关文章
转载注明原文:python-在Tkinter中单击后禁用按钮 - 乐贴网