使用 Tkinter 和 Python。已經為要放置的按鈕創建了一個視窗。我希望出現四個按鈕,并且我希望能夠單擊四個按鈕中的一個,并且能夠設定選擇變數 =“whatever I clicked”,以便以后可以使用此變數呼叫 API。當我運行程式并單擊“常識”按鈕并列印選擇時,它確實正確列印了“常識”,但是當我嘗試回傳此選擇變數時它只是不起作用而且我不知道為什么。
def select1():
selection = "General Knowledge"
print(selection)
def select2():
selection = "Science"
def select3():
selection = "Entertainment"
def select4():
selection = "Miscellaneous"
button1 = tk.Button(text = "General Knowledge", command = select1)
button1.place(x=100, y=100)
button2 = tk.Button(text = "Science", command = select2)
button2.place(x=100, y=140)
button3 = tk.Button(text = "Entertainment", command = select3)
button3.place(x=100, y=180)
button4 = tk.Button(text = "Miscellaneous", command = select4)
button4.place(x=100, y=220)
uj5u.com熱心網友回復:
有幾種方法可以實作您的目標。
一種方法是撰寫一個函式,該函式將一個值分配給您的變數。這樣,您可以擁有任意數量的按鈕,并且只有一個功能。
如果您使用的是函式,則不是必須將變數傳遞給函式或讓函式知道它在全域命名空間中。
import tkinter as tk
root = tk.Tk()
selection = ''
def assign_value(value):
global selection
selection = value
lbl["text"] = value
print(selection)
lbl = tk.Label(root, text='Selection Goes Here')
lbl.grid(row=0, column=0)
tk.Button(text="General Knowledge", command=lambda: assign_value("General Knowledge")).grid(row=1, column=0)
tk.Button(text="Science", command=lambda: assign_value("Science")).grid(row=2, column=0)
tk.Button(text="Entertainment", command=lambda: assign_value("Entertainment")).grid(row=3, column=0)
tk.Button(text="Miscellaneous", command=lambda: assign_value("Miscellaneous")).grid(row=4, column=0)
root.mainloop()
或者您可以直接從按鈕分配值。
import tkinter as tk
root = tk.Tk()
selection = tk.StringVar()
selection.set('Selection Goes Here')
lbl = tk.Label(root, textvariable=selection)
lbl.grid(row=0, column=0)
tk.Button(text="General Knowledge", command=lambda: selection.set("General Knowledge")).grid(row=1, column=0)
tk.Button(text="Science", command=lambda: selection.set("Science")).grid(row=2, column=0)
tk.Button(text="Entertainment", command=lambda: selection.set("Entertainment")).grid(row=3, column=0)
tk.Button(text="Miscellaneous", command=lambda: selection.set("Miscellaneous")).grid(row=4, column=0)
root.mainloop()
我敢肯定,如果我花更多的時間在這上面,我可以想出別的辦法,但這個想法基本上是以更干燥(不要重復自己)的方式撰寫你的代碼,并確保你將值分配給全域變數命名空間,否則它將無法按您的預期作業。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/519337.html
