tkinter的set()与get()

 

 下面用set()实现,这里用了一个标记记录点击的状态,不管内容是什么点了就变

 1 from tkinter import *
 2 
 3 def btn_hit():
 4     global msg_on
 5     if msg_on == False:
 6         msg_on=True
 7         x.set("I like tkinter")
 8     else:
 9         msg_on = False
10         x.set("")
11 
12 root = Tk()
13 root.title("tkinter的set()")
14 
15 msg_on =False
16 x = StringVar()
17 
18 lab = Label(root,textvariable=x,fg="blue",bg="lightyellow",font ="Verdana 16 bold",width=25,height=2)
19 lab.pack()
20 
21 btn = Button(root,text="点我",command= btn_hit)
22 btn.pack()
23 
24 root.mainloop()

 下面用get先获取到内容,在判断,与上面的区别在于,上面没有获得内容直接变,下面对内容进行了判断

from tkinter import *

def btn_hit():
    if x.get() == "":
        x.set("I like tkinter")
    else:
        x.set("")

root = Tk()
root.title("tkinter的get()")

x = StringVar()

lab = Label(root,textvariable=x,fg="blue",bg="lightyellow",font ="Verdana 16 bold",width=25,height=2)
lab.pack()

btn = Button(root,text="点我",command= btn_hit)
btn.pack()

root.mainloop()