python代码实现计数器功能
import tkinter as tk
# 设置初始计数值
count = 0
def increment_number():
"""每次调用此函数时,将label中的数字增加1"""
global count
count += 1
label.config(text=str(count))
def reset_number():
"""将计数器重置为0"""
global count
count = 0
label.config(text=str(count))
def center_window(root):
"""
调整窗口位置使其居中
"""
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
window_width = 600
window_height = 400
x = (screen_width // 2) - (window_width // 2)
y = (screen_height // 2) - (window_height // 2)
root.geometry(f"{window_width}x{window_height}+{x}+{y}")
# 初始化主窗口
root = tk.Tk()
root.title("计数器")
# 调用函数使窗口居中
center_window(root)
# 创建并配置标签
label = tk.Label(root, text=str(count), font=("Microsoft YaHei", 120))
label.pack(pady=20)
# 创建一个框架来放置两个按钮,并水平居中显示
button_frame = tk.Frame(root)
button_frame.pack(side=tk.BOTTOM, pady=(0, 10)) # 靠近底部并留一些边距
# 创建增加按钮,当点击时触发increment_number函数
increment_button_font = ("Microsoft YaHei", 20) # 设置按钮上的文字字体
increment_button = tk.Button(button_frame, text="增加", font=increment_button_font, command=increment_number)
increment_button.pack(side=tk.LEFT, padx=(10, 10)) # 左右间距
# 创建清零按钮,当点击时触发reset_number函数
reset_button_font = ("Microsoft YaHei", 20) # 设置按钮上的文字字体
reset_button = tk.Button(button_frame, text="清零", font=reset_button_font, command=reset_number)
reset_button.pack(side=tk.RIGHT, padx=(10, 10)) # 左右间距
# 进入消息循环
root.mainloop()
最后修改时间:2024-10-18 10:49:55
「喜欢这篇文章,您的关注和赞赏是给作者最好的鼓励」
关注作者
【版权声明】本文为墨天轮用户原创内容,转载时必须标注文章的来源(墨天轮),文章链接,文章作者等基本信息,否则作者和墨天轮有权追究责任。如果您发现墨天轮中有涉嫌抄袭或者侵权的内容,欢迎发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




