我只是想Radiobutton使用tkinter. 每次用戶選擇具有該名稱的任何內容時,我都想更改/替換“選擇您的澆頭” Label(myLabel)。因此,我面臨的錯誤是,即使我使用的是全域.RadiobuttonRadiobuttonLabel
from tkinter import *
root = Tk()
Toppings = [
["Pepperoni", "Pepperoni"],
["Cheese", "Cheese"],
["Mushroom", "Mushroom"],
["Onion", "Onion"]
]
pizza = StringVar()
pizza.set("Select your toppings")
for topping, value in Toppings:
Radiobutton(root, text = topping, variable = pizza, value = value). pack(anchor = W)
myLabel = Label(root, text = pizza.get())
myLabel.pack()
def clicked(value):
global myLabel
myLabel.grid_forget()
myLabel = Label(root, text = value)
myLabel.pack()
myButton = Button(root, text="CLick me!", command = lambda: clicked(pizza.get()))
myButton.pack()
root.mainloop()

uj5u.com熱心網友回復:
使用.config配置特定部件的選項(而無需使用global在這種情況下,反正)(和為什么覆寫它沒有作業的解釋是,因為你需要從洗掉它Tcl通過呼叫.destroy如果你想這樣做的,但這是不必要的):
def clicked(value):
myLabel.config(text=value)
另外,我建議遵循 PEP 8,=如果在關鍵字引數中使用它,則周圍沒有空格,變數名也應該在snake_case. 并且*在匯入模塊時不要使用,只匯入你需要的。
進一步改進:
from tkinter import Tk, Label, Radiobutton, StringVar
toppings = [
"Pepperoni",
"Cheese",
"Mushroom",
"Onion"
]
root = Tk()
topping_var = StringVar(value='Select your topping')
for topping in toppings:
Radiobutton(root, text=topping, variable=topping_var, value=topping).pack(anchor='w')
myLabel = Label(root, textvariable=topping_var)
myLabel.pack()
root.mainloop()
您不需要使用按鈕,只需將變數設定為textvariableforLabel就可以了
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/345020.html
上一篇:如何使影像永久顯示在樹視圖中?
