脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - 如何用python GUI(tkinter)写一个闹铃小程序(思路详解)

如何用python GUI(tkinter)写一个闹铃小程序(思路详解)

2022-03-13 13:50西子伯格 Python

这篇文章主要介绍了用python GUI(tkinter)写一个闹铃小程序思路详解,涉及到tkinter一些函数控件,数据的类的封装,本文通过实例代码给大家介绍的非常详细,需要的朋友可以参考下

事情的起因是帮助一个朋友写一个程序,来控制他们单位的铃声,平时竟然是手动打铃(阔怕)

事情的第一步:理清思路。需要用到python的几个知识:1、tkinter一些函数控件,2、控件和函数之间的联系(主用TreeView控件),3、读写数据入txt文档(高级版可换为数据库),4、数据的类的封装。

需要其他方面的知识:1、简单设计界面布局,2、确保程序易于使用的不反人类细节。

考虑清楚后,那么我开始学习一下相关知识。

(1)python中作为面向对象的一份子,Class(类)和Instance(实例)的两个概念必须要清楚,

?
1
2
class Student(object):
    pass

class后面紧接着是类名,Student,紧接着是(object),表示该类是从哪个类继承下来的,如果没有合适的继承类,就使用object类,这是所有类最终都会继承的类。

?
1
2
3
4
class Student(object):
    def __init__(self, name, score):
        self.name = name
        self.score = score

注意到__init__方法的第一个参数永远是self,表示创建的实例本身,因此,在__init__方法内部,就可以把各种属性绑定到self,因为self就指向创建的实例本身。
有了__init__方法,在创建实例的时候,就不能传入空的参数了,必须传入与__init__方法匹配的参数,但self不需要传,Python解释器自己会把实例变量传进去:
eg:  Tom = Student('Bart Simpson', 59)
要定义一个方法,除了第一个参数是self外,其他和普通函数一样。要调用一个方法,只需要在实例变量上直接调用,除了self不用传递,其他参数正常传入。
PS:看了网上几个教程,有的class类出现不同的写法:
class App:   class App():   class App(Frame):
需要特别说明的是,不带()与带()效果一样,而Class A(B):是继承关系,A继承了B。
(2)tkinter中ttk中的Treeview控件,

?
1
ttk.Treeview(self.frame_center, show="headings", height=18, columns=("a", "b", "c", "d", "e"))

show="heading"表示第一行是隐藏的,show="tree"表示显示第一行。

其实项目没什么难度,贴上源代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
# coding=utf-8
import tkinter
from tkinter import ttk
import os,sys
import time
from playsound import playsound
import threading
import winsound
class Application():
    def __init__(self,master):
        self.master=master  #master就是Tk(),也就是windows
        self.num01=0  # 用于两个button状态切换
        self.run01=1    # 用于 启动和停止 状态切换,1为启动
        self.datatxt = "日常模式_保存配置.txt"    #用于 储存生成txt文件
    def creatThings(self):
        self.myStr01 = tkinter.StringVar()     #如果想让该变量成为整个Class的全局变量,则必须加self
        self.myStr01.set('正在运行')
        self.myVar01 = tkinter.IntVar()
        self.buttonA1=tkinter.Button(self.master,text="日常",bg='#D1EEEE',width=20,command=self.buttonA1_Func)
        self.buttonB2=tkinter.Button(self.master,text="特殊",bg='#D1EEEE',width=20,command=self.buttonB2_Func)
        self.buttonA1.pack()
        self.buttonB2.pack()
        self.label_status=tkinter.Label(self.master,text="当前状态",background="#ffffe0",width=20)
        self.label_status.pack()
        self.label_st2=tkinter.Label(self.master,bg='green', fg='yellow', font=('Arial', 12), width=10, textvariable=self.myStr01)
        self.label_st2.pack()
        self.radioButtonA1=tkinter.Radiobutton(self.master,text="启动",variable=self.myStr01,value='启动',command=self.Change_SelectionA)
        # 其中variable=self.myStr01, value='启动'的意思就是,当我们鼠标选中了其中一个选项,把value的值'启动'放到变量self.myStr01中,然后赋值给variable
        self.radioButtonB2 = tkinter.Radiobutton(self.master, text="停止",variable=self.myStr01,value='停止',command=self.Change_SelectionB)
        self.radioButtonA1.pack()
        self.radioButtonB2.pack()
        self.buttonC3 = tkinter.Button(self.master, text="保存当前配置",width=15,height=2,command=self.Set2Txt)#
        self.buttonC3.pack()
        self.buttonD4 = tkinter.Button(self.master, text="新建事件",width=15,height=2,command=self.New_Building)
        self.buttonD4.pack()
    def creatTree(self):
        treecol=["序号","时间","事件","铃声"]
        global tree
        tree=self.tree=ttk.Treeview(self.master,columns=treecol, height=10, show="headings")
        tree.column('0', width=50, anchor='center'# 指定第一列的宽度和名称, 如果show = "headings", 这一列就被隐藏。
        tree.column('1', width=150, anchor='center')    #表示列,headings时不显示
        tree.column('2', width=150, anchor='center')
        tree.column('3', width=350, anchor='center')
        tree.heading('0', text='序号')
        tree.heading('1', text='时间')
        tree.heading('2', text='事件')
        tree.heading('3', text='铃声')
        self.data = {"item0": ["1", "06:20", "起床", "起床号.mp3"],"item1": ["2", "06:30", "早操", "早操号.mp3"]}
        tree.insert('', 'end', values=self.data["item0"])
        tree.insert('', 'end', values=self.data["item1"])   #这里,使用字典不适合,无序
        self.newdata = {"num01": ["", "", "", ""]}
        tree.pack()     #这一行是必须的
        tree.bind('<ButtonRelease-1>', self.Tree_Selection)
        print("阶段执行检测")
    def Gui_arrange(self):
        self.buttonA1.place(x=100, y=20)
        self.buttonB2.place(x=300, y=20)
        self.tree.place(x=50,y=100)
        self.label_status.place(x=950,y=80)
        self.label_st2.place(x=980,y=105)
        self.radioButtonA1.place(x=950,y=150)
        self.radioButtonB2.place(x=1050, y=150)
        self.buttonC3.place(x=1000,y=500)
        self.buttonD4.place(x=600,y=500)
    #各种点击函数集合:
    def Change_SelectionA(self): #用于点选框变更
        self.label_st2.config(text=self.myStr01.get())
        self.run01=1
    def Change_SelectionB(self):  # 用于点选框变更
        self.label_st2.config(text=self.myStr01.get())
        self.run01=0
    def WriteToTree(self):  #未完成
        #清空newdata中原始数据
        for item in self.tree.get_children():
            self.tree.delete(item)
        f2=open(os.getcwd()+r"\\"+self.datatxt,'r')     #读数据文件datatxt
        cont2=f2.readlines()
        #self.newdata = {"num01": ["", "", "", ""]}  #当然上面这个不行
        self.newdata = cont2
        for i in range(len(self.newdata)):
            '''
            for j in range(len(cont2[0])):  # 取数组中一个元素的最大长度
                self.newdata[i][j].replace('\'','')
            '''
            a=self.newdata[i]
            b=a.replace('\'','')    # b是字符串
            c=b.split(',')          # c变为了数组
self.tree.insert('',i,values=c)       
#self.tree.update() 该行好像没起什么作用
# self.tree.insert('','end',values=["1", "06:20", "起床", "起床号2.mp3"])
def New_Building(self):       
self.tree.insert('','end',values=["1", "06:20", "起床", "起床号2.mp3"])   
def Tree_Selection(self,event):  #这里的event和前面的self是同一个东东, 如果单一参数的话会报错
for item2 in tree.selection():           item_text=tree.item(item2
,"values"#item是I001、I002
print(item_text[1:3])          
print(item_text)       
#item1 = tree.selection()[0]
        #print(item1)
        column = tree.identify_column(event.x)  #列column
row=tree.identify_row(event.y)  #行row
print("正确的column是"+column)       
print("the items has been selected = ",tree.selection())        entryedit=tkinter.Text(
self.master,width=40,height=2)        entryedit.place(
x=90,y=60)       
def save_edit():           
print("==== = ", tree.selection())            tree.set(item2
,column=column,value=entryedit.get(0.0,"end").replace('\n',''))           
# 官方手册解释 set the value of given column in given item to the specified value.
            entryedit.destroy()            Obutton.destroy()        Obutton=tkinter.Button(
self.master,text="更 改",bg="gray",width=4,command=save_edit)        Obutton.place(
x=390,y=60)   
def Set2Txt(self):       
print("num01:",self.num01)       
if self.num01==0:            file01=
open(currentDir+'\\日常模式_保存配置.txt','w')           
for i in range(21):  # 写入数据
#问题是如何输出当前表格数的最大行数,以后再说
try:                    item_text = tree.item(
"I00"+str(i+1), "values") #这是针对列表写的
                    file01.write(str(item_text).replace("(", "").replace(")", "") + '\n') #这是针对列表写的
except:                   
#file01.write(str(item_text).replace("(","").replace(")","")+'\n')
pass
            file01.close()       
elif self.num01==1:            file02=
open(currentDir+'\\休息模式_保存配置.txt','w')           
for i in range(21):  # 写入数据
#问题是如何输出当前表格数的最大行数,以后再说
try:                    item_text = tree.item(
"I00"+str(i+1), "values")                    file02.write(
str(item_text).replace("(", "").replace(")", "") + '\n')               
except:                   
pass
            file02.close()   
def buttonA1_Func(self):       
self.num01 = 0
self.buttonA1['bg']='#71C671'
self.buttonB2['bg'] = '#D1EEEE'
print("效果生成 =0")       
self.datatxt="日常模式_保存配置.txt"
self.WriteToTree()       
#导入日常模式—数据
pass
    def buttonB2_Func(self):       
self.num01 = 1
self.buttonB2['bg']='#71C671'
self.buttonA1['bg'] = '#D1EEEE'
print("效果生成 =1")       
self.datatxt = "休息模式_保存配置.txt"
self.WriteToTree()       
# 导入休息模式—数据
pass
    def Test(self):       
print("纯测试")   
def Belling(self):       
self.num01 = 0  #日常模式0 休息模式1
        #currentDir = os.getcwd()
while True & self.run01==1:           
if self.num01 == 0:               
self.datatxt = "日常模式_保存配置.txt"
elif self.num01 == 1:               
self.datatxt = "休息模式_保存配置.txt"
            f1 = open(os.getcwd() + r"\\" + self.datatxt, 'r')            contect = f1.readlines() 
# contect = []
            # print(contect)
            f1.close()            t = time.localtime()            now = time.strftime(
"%H %M", t).split()           
for i in contect:               
print(i)               
print("闹铃监测正在运行中...")                a = i.split(
',')               
#print(a[1])  # 時間 06:20
                #print(a[3])  # 铃声 起床号.mp3
                h = a[1].replace('\'','').replace(' ','').split(':')               
a2=h                a3=a[
3].replace('\'','').replace('\n','').replace(' ','')               
a4=(currentDir+'\\'+a3)               
if h[0] == now[0] and h[1] == now[1]:                   
print("时间到!")                   
#playsound(r'C:\Users\Jesse Eisenberg\PycharmProjects\Zidonghua\ZidonghuaExcel\一个闹铃.mp3')
                    #playsound(a4)
                    #playsound(currentDir + '\\' + a[3])
                    #采用playsound会报线程错误
                    a4='C:\\Users\\Jesse Eisenberg\\PycharmProjects\\Zidonghua\\ZidonghuaExcel\\一个闹铃.wav'
                    winsound.PlaySound(a4, winsound.SND_FILENAME)                    time.sleep(
56)               
else:                   
#time.sleep(0.5)
continue
def mainpro():    windows = tkinter.Tk()    windows.title(
"打铃系统v1.0")    windows.geometry(
'1200x600')    windows.resizable(
0,0#禁止更改窗口大小
    app = Application(windows)    app.creatTree()    app.creatThings()    app.Gui_arrange()    app.Test()   
def looppro():        app.Belling()    threadObj01 = threading.Thread(
target=looppro)    threadObj01.start()    windows.mainloop()    sys.exit()currentDir=os.getcwd()
print("os.getcwd()=%s" % os.getcwd())
if __name__ == '__main__':   
print("game starts")    mainpro()   
print("game ends")
#开始之后,闹铃检测程序自动启动,点击“停止”圆框选项后,闹铃检测程序停止,在按“启动”圆框选项,程序并未启动

到此这篇关于如何用python GUI(tkinter)写一个闹铃小程序(思路详解)的文章就介绍到这了,更多相关python 闹铃小程序内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://www.cnblogs.com/kuhns/p/10091749.html

延伸 · 阅读

精彩推荐