python button.cget(属性)

问题在注释里


import tkinter as tk


def on_off():
    global button
    state = button.cget("text")#这里的property为什么要用引号?如果直接button.cget(text)会报错,这是什么原因?
    if state == "ON":
        state = "OFF"
    else:
        state = "ON"
    button.config(text=state)


window = tk.Tk()
button = tk.Button(window, text="OFF", command=on_off)
button.place(x=50, y=100, width=100)
window.mainloop()

```

state = button.cget("text")这里用引号是字符串形式的属性名
如果直接button.cget(text), text就成了变量名了,你没有定义text变量就报错了
你定义一个text变量就可以不加引号

text = "text"
state = button.cget(text)

button.cget("text")
这里的"text"是一个字符串啊

您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!
PS:问答VIP年卡 【限时加赠:IT技术图书免费领】,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632文章:使用Python中的Button组件制作按钮 中也许有你想要的答案,请看下吧
你还可以看下python参考手册中的 python-特殊属性