在Tkinter中单击后禁用按钮 [英] Disabling buttons after click in Tkinter
问题描述
我是Python的新手,我正在尝试使用Tkinter制作一个简单的应用程序.
I'm new to Python and I'm trying to make a simple application using 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)
我要尝试的是单击按钮后将其禁用.我尝试过
What I'm trying to do is disable the buttons once I click them. I tried
def appear(x):
nButton.config(state="disabled")
return lambda: results.insert(END, x)
但这给了我以下错误:
NameError:未定义全局名称'nButton'
NameError: global name 'nButton' is not defined
推荐答案
这里有一些问题:
-
每当动态创建窗口小部件时,都需要将对它们的引用存储在集合中,以便以后可以访问它们.
Whenever you create widgets dynamically, you need to store references to them in a collection so that you can access them later.
Tkinter小部件的 grid
方法始终返回 None
.因此,您需要将对 grid
的所有呼叫放在自己的线路上.
The grid
method of a Tkinter widget always returns None
. So, you need to put any calls to grid
on their own line.
每当将按钮的 command
选项分配给需要参数的函数时,都必须使用 https://stackoverflow.com/a/20556892/2555451 .
Whenever you assign a button's command
option to a function that requires arguments, you must use a lambda
or such to "hide" that call of the function until the button is clicked. For more information, see https://stackoverflow.com/a/20556892/2555451.
以下是解决所有这些问题的示例脚本:
Below is a sample script addressing all of these issues:
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()
这篇关于在Tkinter中单击后禁用按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!