在 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, 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:未定义全局名称“nButton”

原文由 Serra 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.4k
2 个回答

这里有几个问题:

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

  2. Tkinter 小部件的 grid 方法总是返回 None 。因此,您需要 grid 的任何调用放在他们自己的线路上。

  3. 每当您将按钮的 command 选项分配给需要参数的函数时,您必须使用 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()

原文由 user2555451 发布,翻译遵循 CC BY-SA 3.0 许可协议

如果你想在点击后禁用一个按钮,你可以创建一个函数,你将在其中执行所需的操作,但在开始时你应该使用一个命令来禁用按钮,以便在函数运行时禁用按钮。如果你愿意,你可以从这段代码中得到一点帮助:-

 from tkinter import *
root = Tk()

def disable_button():
    button_1['state'] = DISABLED
    print("this is how you disable a buuton after a click")
button_1 = Button(root,text = "Disable this button",command=disable_button)
button_1.pack()
root.mainloop()

我希望你的问题已经解决

谢谢

原文由 Empire of programmers 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题