如果是,按钮不起作用

时间:2016-05-14 13:58:02

标签: python python-2.7 tkinter

尝试更改按钮文本。如果按钮具有LBS,则单击该按钮应将其更改为KGS。如果按钮具有KGS,则单击该按钮应将其更改为LBS。

按钮什么都不做,但代码对我来说似乎是正确的。

from Tkinter import *

myGui=Tk()
myGui.geometry("200x100")
myGui.title("basicGUI")
myGui.configure(bg="gray")

def toggle():
    text = "LBS"
    if text == LBS:
        tglBtn.config(text = KGS)
    else:
        tglBtn.config(text = LBS)

LBS = StringVar
tglBtn = Button(text="LBS",
                textvariable=LBS,
                command=toggle)
tglBtn.pack()

mainloop()

2 个答案:

答案 0 :(得分:1)

除非添加括号:StringVar,否则不会创建LBS = StringVar()对象。该名称也具有误导性,因为StringVar将是" LBS"或" KGS"。 StringVar的重点是,只要StringVar更改其值,按钮的文本就会自动更新。

from Tkinter import *

myGui=Tk()
myGui.geometry("200x100")
myGui.title("basicGUI")
myGui.configure(bg="gray")

def toggle():
    if buttonText.get() == "LBS":
        buttonText.set("KGS")
    else:
        buttonText.set("LBS")

buttonText = StringVar()
buttonText.set("LBS")      # you can't do StringVar("LBS")
tglBtn = Button(textvariable=buttonText,
                command=toggle)
tglBtn.pack()

mainloop()

答案 1 :(得分:0)

在您的第text == LBS行中,您正在比较stringtext)和变量实例(LBS,即StringVar)。要么比较textLBS.get(),要么直接直接比较字符串,如下例所示。

from Tkinter import *

myGui=Tk()
myGui.geometry("200x100")
myGui.title("basicGUI")
myGui.configure(bg="gray")

def toggle():
    text = tglBtn.cget("text")
    if text == "LBS":
        tglBtn.config(text = "KGS")
    else:
        tglBtn.config(text = "LBS")

tglBtn = Button(text="LBS", command=toggle)
tglBtn.pack()

mainloop()