我最近在看了一本Python tkinter从入门到精通,看了四章了,前面四章主要就是讲部件的共同属性,控件的布局,窗口的属性设置,于是利用这些做了个简单的程序,其中info文件,except文件,圣诞老人.ico文件,我都没有上传,如果想要的话,私聊我,加我CSND好友,我发送给你,代码如下
from tkinter import *
import time,traceback,re
win = Tk() # 新建一个窗口
sh = win.winfo_screenheight() # 获取屏幕的高
sw = win.winfo_screenwidth() # 获取屏幕的宽
winh = int(sh / 4) # 设置窗口的高
winw = int(sw / 3.5) # 设置窗口的宽
x = int((sh - winh) / 2) # 设置窗口的位置
y = int((sw - winw) / 2) # 设置窗口的位置
win.geometry(f"{winw}x{winh}+{x}+{y}") # 设置窗口的大小和位置
win.iconbitmap("圣诞老人.ico") # 设置窗口图标
var1 = StringVar() # 定义三个变量
var2 = StringVar()
var3 = StringVar()
# 从文件中读取信息,在将每一行信息转化成一个列表
with open("info.txt","r") as f:
words=f.readlines()
num1word,num2word,num3word=words[0],words[1],words[2]
word1=num1word.replace("\n","").split(",")
word2=num2word.replace("\n","").split(",")
word3=num3word.replace("\n","").split(",")
# 创建三个函数
def num1():
# 判断列表的值数量是否为空,为空就销毁窗口,不为空就将值设置为标签的值,再删除这个值
try:
if len(word1) == 0:
win.destroy()
else:
cycle(word1,var1)
except:
write_except()
def write_except():
#将当前日期时间和异常信息写入except.txt文件中,在打印当前时间和异常信息
with open("except.txt", "r+") as f:
now=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
f.write(now+str( traceback.print_exc())+"\n")
print(now+traceback.format_exc())
def cycle(lists,V):
#循环输出每个元素信息,到对应的标签Label的文本变量中textvariable
for i in lists:
V.set(i)
lists.pop(0)
break
def num2():
# 判断列表的值数量是否为空,为空就销毁窗口,不为空就将值设置为标签的值,再删除这个值
try:
if len(word2) == 0:
pass
else:
cycle(word2,var2)
except:
write_except()
def num3():
# 判断列表的值数量是否为空,为空就销毁窗口,不为空就将值设置为标签的值,再删除这个值
try:
if len(word3) == 0:
pass
else:
cycle(word3,var3)
except:
write_except()
# 函数直接调用其他三个函数
def sum():
num1(), num2(), num3()
Label(win, textvariable=var1, font="微软雅黑 20 italic", fg="pink", bg="yellow").place(relx=0, rely=0, relwidth=0.35,
relheight=1) # 创建第一个标签
Label(win, textvariable=var2, font="微软雅黑 20 italic", fg="pink", bg="yellow").place(relx=0.35, rely=0, relwidth=0.2,
relheight=1) # 创建第二个标签
Label(win, textvariable=var3, font="微软雅黑 20 italic", fg="pink", bg="yellow").place(relx=0.55, rely=0, relwidth=0.33,
relheight=1) # 创建第三个标签
Button(win, command=sum, font="微软雅黑 20 italic", fg="pink", bg="yellow", relief="ridge", text="start") \
.place(relx=0.88, rely=0, relwidth=0.12, relheight=1) # 创建一个按钮,绑定sum函数
mainloop()
|