Ser*_*rra 4 python tkinter button
我是 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)
Run Code Online (Sandbox Code Playgroud)
我想要做的是一旦我点击它们就禁用它们。我试过
def appear(x):
nButton.config(state="disabled")
return lambda: results.insert(END, x)
Run Code Online (Sandbox Code Playgroud)
但它给了我以下错误:
NameError:未定义全局名称“nButton”
小智 5
这里有几个问题:
每当您动态创建小部件时,您都需要将它们的引用存储在一个集合中,以便您以后可以访问它们。
gridTkinter 小部件的方法总是返回None. 因此,您需要将任何呼叫grid置于他们自己的线路上。
每当您将按钮的command选项分配给需要参数的函数时,您必须使用 alambda或此类来“隐藏”该函数的调用,直到单击该按钮。有关更多信息,请参阅/sf/answers/1438982471/。
以下是解决所有这些问题的示例脚本:
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()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
22081 次 |
| 最近记录: |