我正在尝试用python3.7为一个学校项目编写一个basic程序,当按下一个按钮时,它会打印一个文本字符串。有人知道我做错了什么吗?你知道吗
我尝试过使用lambda函数,但它给了我一个错误消息。你知道吗
#This is what I have tried:
import tkinter
window = tkinter.Tk()
button1 = tkinter.Button(window, text = "Press Me1", command= lambda: action("1"))
button2 = tkinter.Button(window, text = "Press Me2", command= lambda: action("2"))
button1.pack()
button2.pack()
window.mainloop()
if button1 == "1":
print("Button 1 was pressed.")
elif button2 == "2":
print("Button 2 was pressed.")
I'm expecting that, when you press one of the buttons, it prints the specified statement.
#However, I get the following error message:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\liamd\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
File "C:\Users\liamd\Documents\!!!!MY STUFF!!!!\Python\Bankaccount Assessment - Simplified - And Again.py", line 4, in <lambda>
button1 = tkinter.Button(window, text = "Press Me1", command= lambda: action("1"))
NameError: name 'action' is not defined
在调用
action
函数之前,您需要为它提供一个实现,例如:所以您的代码如下所示:
或者,也可以将所有
action
调用替换为print()
调用:if
条件不会起任何作用,因为它们不是由按下按钮触发的。你知道吗另一种方法是定义按下按钮时的特定功能。如果你计划有其他事情发生在按下按钮,然后这可能是有帮助的。你知道吗
相关问题 更多 >
编程相关推荐