tkinter的button实例

这个博客展示了如何使用Python的Tkinter库创建GUI应用,并结合ctypes库隐藏命令行窗口。第一个例子中,点击'你好'按钮显示'好久不见',而'再见'按钮关闭窗口。第二个例子是一个计数器应用,每秒自动增加计数,直到点击'结束'按钮关闭窗口。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

例子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()

运行结果为:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值