如何用python?GUI(tkinter)寫一個(gè)鬧鈴小程序(思路詳解)
事情的起因是幫助一個(gè)朋友寫一個(gè)程序,來(lái)控制他們單位的鈴聲,平時(shí)竟然是手動(dòng)打鈴(闊怕)
事情的第一步:理清思路。需要用到python的幾個(gè)知識(shí):1、tkinter一些函數(shù)控件,2、控件和函數(shù)之間的聯(lián)系(主用TreeView控件),3、讀寫數(shù)據(jù)入txt文檔(高級(jí)版可換為數(shù)據(jù)庫(kù)),4、數(shù)據(jù)的類的封裝。
需要其他方面的知識(shí):1、簡(jiǎn)單設(shè)計(jì)界面布局,2、確保程序易于使用的不反人類細(xì)節(jié)。
考慮清楚后,那么我開始學(xué)習(xí)一下相關(guān)知識(shí)。
(1)python中作為面向?qū)ο蟮囊环葑?,Class(類)和Instance(實(shí)例)的兩個(gè)概念必須要清楚,
class Student(object):
pass
class后面緊接著是類名,Student,緊接著是(object),表示該類是從哪個(gè)類繼承下來(lái)的,如果沒(méi)有合適的繼承類,就使用object類,這是所有類最終都會(huì)繼承的類。
class Student(object):
def __init__(self, name, score):
self.name = name
self.score = score
注意到__init__方法的第一個(gè)參數(shù)永遠(yuǎn)是self,表示創(chuàng)建的實(shí)例本身,因此,在__init__方法內(nèi)部,就可以把各種屬性綁定到self,因?yàn)閟elf就指向創(chuàng)建的實(shí)例本身。
有了__init__方法,在創(chuàng)建實(shí)例的時(shí)候,就不能傳入空的參數(shù)了,必須傳入與__init__方法匹配的參數(shù),但self不需要傳,Python解釋器自己會(huì)把實(shí)例變量傳進(jìn)去:
eg: Tom = Student('Bart Simpson', 59)
要定義一個(gè)方法,除了第一個(gè)參數(shù)是self外,其他和普通函數(shù)一樣。要調(diào)用一個(gè)方法,只需要在實(shí)例變量上直接調(diào)用,除了self不用傳遞,其他參數(shù)正常傳入。
PS:看了網(wǎng)上幾個(gè)教程,有的class類出現(xiàn)不同的寫法:
class App: class App(): class App(Frame):
需要特別說(shuō)明的是,不帶()與帶()效果一樣,而Class A(B):是繼承關(guān)系,A繼承了B。
(2)tkinter中ttk中的Treeview控件,
ttk.Treeview(self.frame_center, show="headings", height=18, columns=("a", "b", "c", "d", "e"))
show="heading"表示第一行是隱藏的,show="tree"表示顯示第一行。
其實(shí)項(xiàng)目沒(méi)什么難度,貼上源代碼:
# 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 # 用于兩個(gè)button狀態(tài)切換
self.run01=1 # 用于 啟動(dòng)和停止 狀態(tài)切換,1為啟動(dòng)
self.datatxt = "日常模式_保存配置.txt" #用于 儲(chǔ)存生成txt文件
def creatThings(self):
self.myStr01 = tkinter.StringVar() #如果想讓該變量成為整個(gè)Class的全局變量,則必須加self
self.myStr01.set('正在運(yùn)行')
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="當(dāng)前狀態(tài)",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="啟動(dòng)",variable=self.myStr01,value='啟動(dòng)',command=self.Change_SelectionA)
# 其中variable=self.myStr01, value='啟動(dòng)'的意思就是,當(dāng)我們鼠標(biāo)選中了其中一個(gè)選項(xiàng),把value的值'啟動(dòng)'放到變量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="保存當(dāng)前配置",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=["序號(hào)","時(shí)間","事件","鈴聲"]
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時(shí)不顯示
tree.column('2', width=150, anchor='center')
tree.column('3', width=350, anchor='center')
tree.heading('0', text='序號(hào)')
tree.heading('1', text='時(shí)間')
tree.heading('2', text='事件')
tree.heading('3', text='鈴聲')
self.data = {"item0": ["1", "06:20", "起床", "起床號(hào).mp3"],"item1": ["2", "06:30", "早操", "早操號(hào).mp3"]}
tree.insert('', 'end', values=self.data["item0"])
tree.insert('', 'end', values=self.data["item1"]) #這里,使用字典不適合,無(wú)序
self.newdata = {"num01": ["", "", "", ""]}
tree.pack() #這一行是必須的
tree.bind('<ButtonRelease-1>', self.Tree_Selection)
print("階段執(zhí)行檢測(cè)")
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)
#各種點(diǎn)擊函數(shù)集合:
def Change_SelectionA(self): #用于點(diǎn)選框變更
self.label_st2.config(text=self.myStr01.get())
self.run01=1
def Change_SelectionB(self): # 用于點(diǎn)選框變更
self.label_st2.config(text=self.myStr01.get())
self.run01=0
def WriteToTree(self): #未完成
#清空newdata中原始數(shù)據(jù)
for item in self.tree.get_children():
self.tree.delete(item)
f2=open(os.getcwd()+r"\\"+self.datatxt,'r') #讀數(shù)據(jù)文件datatxt
cont2=f2.readlines()
#self.newdata = {"num01": ["", "", "", ""]} #當(dāng)然上面這個(gè)不行
self.newdata = cont2
for i in range(len(self.newdata)):
'''
for j in range(len(cont2[0])): # 取數(shù)組中一個(gè)元素的最大長(zhǎng)度
self.newdata[i][j].replace('\'','')
'''
a=self.newdata[i]
b=a.replace('\'','') # b是字符串
c=b.split(',') # c變?yōu)榱藬?shù)組
self.tree.insert('',i,values=c)
#self.tree.update() 該行好像沒(méi)起什么作用
# self.tree.insert('','end',values=["1", "06:20", "起床", "起床號(hào)2.mp3"])
def New_Building(self):
self.tree.insert('','end',values=["1", "06:20", "起床", "起床號(hào)2.mp3"])
def Tree_Selection(self,event): #這里的event和前面的self是同一個(gè)東東, 如果單一參數(shù)的話會(huì)報(bào)錯(cuò)
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',''))
# 官方手冊(cè)解釋 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): # 寫入數(shù)據(jù)
#問(wèn)題是如何輸出當(dāng)前表格數(shù)的最大行數(shù),以后再說(shuō)
try: item_text = tree.item(
"I00"+str(i+1), "values") #這是針對(duì)列表寫的
file01.write(str(item_text).replace("(", "").replace(")", "") + '\n') #這是針對(duì)列表寫的
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): # 寫入數(shù)據(jù)
#問(wèn)題是如何輸出當(dāng)前表格數(shù)的最大行數(shù),以后再說(shuō)
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()
#導(dǎo)入日常模式—數(shù)據(jù)
pass
def buttonB2_Func(self):
self.num01 = 1
self.buttonB2['bg']='#71C671'
self.buttonA1['bg'] = '#D1EEEE'
print("效果生成 =1")
self.datatxt = "休息模式_保存配置.txt"
self.WriteToTree()
# 導(dǎo)入休息模式—數(shù)據(jù)
pass
def Test(self):
print("純測(cè)試")
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("鬧鈴監(jiān)測(cè)正在運(yùn)行中...") a = i.split(
',')
#print(a[1]) # 時(shí)間 06:20
#print(a[3]) # 鈴聲 起床號(hào).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("時(shí)間到!")
#playsound(r'C:\Users\Jesse Eisenberg\PycharmProjects\Zidonghua\ZidonghuaExcel\一個(gè)鬧鈴.mp3')
#playsound(a4)
#playsound(currentDir + '\\' + a[3])
#采用playsound會(huì)報(bào)線程錯(cuò)誤
a4='C:\\Users\\Jesse Eisenberg\\PycharmProjects\\Zidonghua\\ZidonghuaExcel\\一個(gè)鬧鈴.wav'
winsound.PlaySound(a4, winsound.SND_FILENAME) time.sleep(
56)
else:
#time.sleep(0.5)
continue
def mainpro(): windows = tkinter.Tk() windows.title(
"打鈴系統(tǒng)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")
#開始之后,鬧鈴檢測(cè)程序自動(dòng)啟動(dòng),點(diǎn)擊“停止”圓框選項(xiàng)后,鬧鈴檢測(cè)程序停止,在按“啟動(dòng)”圓框選項(xiàng),程序并未啟動(dòng)
到此這篇關(guān)于如何用python?GUI(tkinter)寫一個(gè)鬧鈴小程序(思路詳解)的文章就介紹到這了,更多相關(guān)python?鬧鈴小程序內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
結(jié)合Python工具使用TfidfVectorizer進(jìn)行文本特征提取方式
在自然語(yǔ)言處理中,TF-IDF是一種重要的特征提取方法,本文介紹了如何使用Python的sklearn庫(kù)中的TfidfVectorizer進(jìn)行文本特征提取,首先,需要安裝sklearn庫(kù),TfidfVectorizer能將文本文檔集合轉(zhuǎn)換為TF-IDF特征矩陣2024-10-10
Python 3.8正式發(fā)布,來(lái)嘗鮮這些新特性吧
今天 Python3.8 發(fā)布啦,它是 Python2 終結(jié)前最后一個(gè)大版本,我們一起看看這個(gè)版本都添加了那些新功能和特性2019-10-10
Python中的fileinput模塊的簡(jiǎn)單實(shí)用示例
這篇文章主要介紹了Python中的fileinput模塊實(shí)用示例,文中的示例是使用其來(lái)便利硬盤分區(qū)下的文本文件并打印其中行的長(zhǎng)度,需要的朋友可以參考下2015-07-07
Pandas實(shí)現(xiàn)在線文件和剪貼板數(shù)據(jù)讀取詳解
這篇文章主要為大家介紹的是Pandas兩種少用的讀取文件方式:讀取在線文件的數(shù)據(jù)和讀取剪貼板的數(shù)據(jù),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2022-06-06
python3.x 生成3維隨機(jī)數(shù)組實(shí)例
今天小編就為大家分享一篇python3.x 生成3維隨機(jī)數(shù)組實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-11-11
Python使用itchat模塊實(shí)現(xiàn)群聊轉(zhuǎn)發(fā),自動(dòng)回復(fù)功能示例
這篇文章主要介紹了Python使用itchat模塊實(shí)現(xiàn)群聊轉(zhuǎn)發(fā),自動(dòng)回復(fù)功能,結(jié)合實(shí)例形式分析了Python基于itchat模塊針對(duì)微信信息的發(fā)送、回復(fù)等相關(guān)操作技巧,需要的朋友可以參考下2019-08-08

