簡體   English   中英

如何通過Tkinter中的按鈕傳遞參數

[英]How to pass an argument through a button in tkinter

我正在嘗試為學校項目使用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

您需要在調用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條件不會執行任何操作,因為它們不是由按下按鈕觸發的。

這樣做的另一種方法是為按下按鈕定義特定的功能。 如果您打算在按鈕按下時發生其他事情,那么這可能會有所幫助。

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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM