如何通过Tkinter中的按钮传递参数

时间:2019-04-11 19:07:31

标签: python tkinter python-idle

我正在尝试使用Python 3.7编写一个学校项目的基本程序,该项目在按下按钮时会打印一串文本。有人对我做错了什么有想法吗?

我尝试使用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

2 个答案:

答案 0 :(得分:1)

例如,您需要为action函数提供实现,然后再调用它,例如:

def action(message):
    print(message)

因此您的代码应如下所示:

import tkinter

def action(message):
    print(message)

window = tkinter.Tk()
button1 = tkinter.Button(window, text = "Press Me1", command= lambda: action("Button 1 was pressed"))
button2 = tkinter.Button(window, text = "Press Me2", command= lambda: action("Button 2 was pressed"))
button1.pack()
button2.pack()
window.mainloop()

或者,您也可以将所有action呼叫替换为print()呼叫:

button1 = tkinter.Button(window, text = "Press Me1", command= lambda: print("Button 1 was pressed"))
button1 = tkinter.Button(window, text = "Press Me1", command= lambda: print("Button 2 was pressed"))

if条件不会执行任何操作,因为它们不是由按下按钮触发的。

答案 1 :(得分:0)

另一种方法是定义按下按钮时的特定功能。如果您打算在按键时发生其他事情,那么这会有所帮助。

import tkinter

#This is what I added to get the buttons to work.
def on_button_1():
    print('Button 1 was pressed.')
def on_button_2():
    print('Button 2 was pressed.')


window = tkinter.Tk()
#changed these next 2 lines so that each button calls the appropriate function
button1 = tkinter.Button(window, text = "Press Me1", command= on_button_1)
button2 = tkinter.Button(window, text = "Press Me2", command= on_button_2)
button1.pack()
button2.pack()
window.mainloop()