效果
雙擊開始播放,繼續(xù)雙擊可以加速播放
右鍵可以彈出菜單:播放、暫停、退出
左鍵可以拖動窗口
代碼
from tkinter import * import time import tkinter as tk file = "待播放文本.txt" text=" " bgcolor = '#000000' fgcolor = '#FFFFFF' def getText(): global text # 讀 with open(file, "r",encoding='utf-8') as f: # 按字節(jié)讀 text = f.read() #獲取一行 getText() root = Tk() # 窗口設(shè)定為無邊框 root.overrideredirect(True) # 窗口前置 root.wm_attributes("-topmost", 1) # 窗口屬性 透明度設(shè)置 root.attributes("-alpha", 0.8) # 窗口標(biāo)題 # root.title("文本播放器") # 窗口大小 root.geometry("200x35+100+100") # 更新顯示文本 show_str = StringVar(root) # 初始顯示文本 show_str.set("雙擊播放") # 源字符 source_str = text # 播放標(biāo)記 playflag = True # 播放位置 pos = 0 # 滾動 def marquee(widget): #字符寬度 textwidth = 18 # 源字符長度 strlen = len(source_str) # 引用全局變量 global pos # 如果字符長度-播放位置textwidth if strlen - pos textwidth: # 設(shè)定顯示的字符串為源字符串的(播放位置,播放位置+文本寬度)+ 源字符串的(0,10-字符串長度+播放位置) show_str.set(source_str[pos:pos+textwidth] + source_str[0:textwidth - strlen + pos]) else: # 如果大于textwidth,則播放(播放位置,播放位置+文本寬度)的字符 show_str.set(source_str[pos:pos+textwidth]) #播放位置+1 pos += 1 #如果播放位置大于字符串長度 if pos > strlen: #播放位置設(shè)為0 pos = 0 # 引用全局變量 global stopflag # 如果當(dāng)前為播放狀態(tài) if playflag: # 睡眠0.3秒后執(zhí)行滾動函數(shù) widget.after(300, marquee, widget) # 創(chuàng)建標(biāo)簽 show_lb = Label(root, textvariable=show_str,width=300, fg=fgcolor, bg=bgcolor, text=text, font=("Consolas", 10)) # 設(shè)定標(biāo)簽位置 show_lb.place(x=0, y=0, width=200, height=35) def doubleClicktoPlay(event): global playflag # 播放 playflag = True marquee(show_lb) def playStart(): global playflag # 播放 playflag = True marquee(show_lb) def playStop(): global playflag # 暫停播放 playflag = False # 創(chuàng)建彈出式菜單 menu = tk.Menu(root, tearoff=0) # 為菜單添加命令標(biāo)簽 menu.add_command(label="播放", command=playStart) menu.add_command(label="暫停", command=playStop) menu.add_command(label="退出", command=exit) def popUpMenu(event): #在鼠標(biāo)點(diǎn)擊的位置彈出菜單 menu.post(event.x_root, event.y_root) # 為消息事件(按鍵、點(diǎn)擊)綁定函數(shù) root.bind_all("ButtonRelease-3>", popUpMenu) def moveStart(event): global startX, startY #獲取鼠標(biāo)的點(diǎn)擊位置的x、y startX = event.x startY = event.y def move(event): #新坐標(biāo)=鼠標(biāo)點(diǎn)擊坐標(biāo)+窗口坐標(biāo)-初始坐標(biāo) new_x = (event.x) + root.winfo_x() - startX new_y = (event.y) + root.winfo_y() - startY s = "200x35+" + str(new_x) + "+" + str(new_y) # 重新設(shè)置窗口大小及其位置 root.geometry(s) # 為消息事件(按鍵、點(diǎn)擊)綁定函數(shù) root.bind_all("Button-1>", moveStart) root.bind_all("B1-Motion>", move) root.bind_all("Double-Button-1>", doubleClicktoPlay) root.mainloop()
注:
如果文本有換行符,切換不會很流暢
可用此方法刪除換行符
到此這篇關(guān)于Python 文本滾動播放器的文章就介紹到這了,更多相關(guān)Python滾動播放器內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
標(biāo)簽:日照 金華 赤峰 臨汾 貴州 克拉瑪依 雙鴨山 陽泉
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《Python 文本滾動播放器的實(shí)現(xiàn)代碼》,本文關(guān)鍵詞 Python,文本,滾動,播放器,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。