例子1,代码为:
from tkinter import *
import ctypes
whnd = ctypes.windll.kernel32.GetConsoleWindow()
if whnd != 0:
ctypes.windll.user32.ShowWindow(whnd, 0)
ctypes.windll.kernel32.CloseHandle(whnd)
def msgshow():
label.config(text='好久不见', bg='lightyellow', fg='blue')
root = Tk()
root.title('hello')
label = Label(root)
btn1 = Button(root, text='你好', width=15, command=msgshow) # 调用msgshow函数
btn2 = Button(root, text='再见', width=15, command=root.destroy) # 关闭窗口
label.pack()
btn1.pack(side=LEFT)
btn2.pack(side=LEFT)
root.mainloop()
结果为:
点击‘你好’后:
点击‘再见’后窗口会直接关闭
例子2,代码为:
from tkinter import *
counter = 0
def run_counter(digit):
def counting():
global counter
counter += 1
digit.config(text=str(counter))
digit.after(1000, counting)
counting()
root = Tk()
root.title('计时器')
digit = Label(root, bg='yellow', fg='blue', height=3, width=10, font='Helvetic 20 bold')
digit.pack()
run_counter(digit)
Button(root, text='结束', width=15, command=root.destroy).pack(pady=10)
root.mainloop()
运行结果为: