【问题标题】:Cannot modify global Label in Tkinter python无法在 Tkinter python 中修改全局标签
【发布时间】:2021-11-01 09:17:08
【问题描述】:

我只是想用tkinter 制作一个Radiobutton GUI。每次用户使用 Radiobutton 名称选择任何 Radiobutton 时,我都想在其中更改/替换“选择您的浇头”Label (myLabel)。因此,我面临的错误不是替换该标签,而是在下方创建一个新标签,即使我使用的是全局 Label

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

【问题讨论】:

    标签: python tkinter tkinter-label


    【解决方案1】:

    使用.config 配置特定的小部件选项(在这种情况下无论如何都不需要使用global)(以及为什么覆盖它不起作用的解释是因为您需要从@987654323 中删除它@ 调用.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()
    

    您不需要使用按钮,只需将变量设置为textvariableLabel 就可以了

    【讨论】:

      猜你喜欢
      • 2019-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-01
      相关资源
      最近更新 更多