引
有些时候,我们会希望自己的窗口看上去花里胡哨一点,比如弄个会定时刷新文字的标签……
码
# -*- coding: utf-8 -*-
# Environment PyCharm
# File_name whileLoop |User Pfolg
# 2024/7/30 12:42
import time
from tkinter import ttk
import threading
import tkinter as tk
aboutList = ["我是编程路上一个蹒跚学步的婴儿",
"我是Python新手村的村民",
"我是学不进Java的废材",
"我是一个喜欢花里胡哨的普通人",
"这个程序是我用来练习和进步的",
"谢谢你的见证!"]
def authorInfor(frame):
ttk.Label(frame, text="关于作者-Pfolg").place(relx=.02, rely=.02)
def showLabel():
i = 0
while True:
try: # 这里会报错,于是try一下
a = ttk.Label(frame, text=aboutList[i], font=("微软雅黑", 16), width=40)
a.place(relx=.3, rely=.1)
except RuntimeError:
break
if i == len(aboutList) - 1:
i = 0
i += 1
# 三秒刷新一次
time.sleep(3)
# 开辟一个线程使事件循环,建议关闭(注释掉)
threading.Thread(target=showLabel).start()
ttk.Button(
frame, text="Bilibili",
command=None
).place(relx=.2, rely=.5)
ttk.Button(
frame, text="GitHub",
command=None
).place(relx=.3, rely=.6)
ttk.Button(
frame, text="CSDN"
).place(relx=.4, rely=.7)
ttk.Button(
frame, text="作者的个人网站"
).place(relx=.5, rely=.6)
ttk.Button(
frame, text="QQ&微信",
command=None
).place(relx=.6, rely=.5)
window = tk.Tk()
window.title("文字刷新")
screen_w, screen_h = window.winfo_screenwidth(), window.winfo_screenheight()
w, h = int(screen_w / 2), int(screen_h / 2)
window.geometry(f'{w}x{h}+{int(screen_w / 4)}+{int(screen_h / 4)}')
window.resizable(False, False) # 窗口大小不可变化
window.attributes('-alpha', 0.9) # 透明度.9
frame = ttk.Frame(window,width=w,height=h)
frame.pack()
authorInfor(frame)
window.mainloop()
值得注意的是,这里的精髓就是函数里面的那个函数+函数内函数下方的那一行代码:
def showLabel():
i = 0
while True:
try: # 这里会报错,于是try一下
a = ttk.Label(frame, text=aboutList[i], font=("微软雅黑", 16), width=40)
a.place(relx=.3, rely=.1)
except RuntimeError:
break # 这里程序才结束
if i == len(aboutList) - 1:
i = 0
i += 1
# 三秒刷新一次
time.sleep(3)
# 开辟一个线程使事件循环,建议关闭(注释掉)
threading.Thread(target=showLabel).start()
其他的都可不必理会,什么按钮标签etc. 的技术含量 都不如 这个 加了线程的 标签。
尾
哦对了,纯粹是我自己琢磨出来的,有问题很正常,嘿嘿。
如果你有代码所需的第三方库,复制粘贴直接运行——应该没问题,剩下的自己钻研吧。