第一个例子:after

用于定时操作

import tkinter as tk
import time class MyApp(tk.Frame):
def __init__(self, msecs=1000):
super().__init__()
self.pack() self.msecs = msecs self.utc_time = tk.Label(self, text='', bg='navy', fg='white')
self.utc_time.pack()
self.cst_time = tk.Label(self, text='', bg='navy', fg='white')
self.cst_time.pack() self.repeater() def repeater(self):
self.utc_time.config(text= 'UTC: ' + time.strftime('%Y/%m/%d %H:%M:%S',time.gmtime()))
self.cst_time.config(text= 'CST: ' + time.strftime('%Y/%m/%d %H:%M:%S',time.localtime())) self.after(self.msecs, self.repeater) if __name__ == '__main__':
MyApp(msecs=1000).mainloop()

效果图:

tkinter 的两个例子-LMLPHP

第二个例子:pack_forget

用于切换窗口部件的显示、隐藏

import tkinter as tk

class MyApp(tk.Frame):
def __init__(self):
super().__init__()
self.pack() # 两个按钮
self.rowframe = tk.Frame(self)
self.rowframe.pack(fill='x')
self.btn2 = tk.Button(self.rowframe, text='按钮2') # , command=self.update
self.btn2.pack(side=tk.RIGHT)
self.btn1 = tk.Button(self.rowframe, text='按钮1')
self.btn1.pack(side=tk.RIGHT) self.btn1.bind('<Button-1>', self.update)
self.btn2.bind('<Button-1>', self.update) # 测试pack_forget
def update(self, event):
#print(dir(event))
if event.widget == self.btn1:
self.btn1.forget()
self.btn2.pack(side=tk.RIGHT)
else:
self.btn2.pack_forget() # 故意的
self.btn1.pack(side=tk.RIGHT) if __name__ == '__main__':
MyApp().mainloop()

效果图:

tkinter 的两个例子-LMLPHP

05-11 11:09