Python 文本滚动播放
生活随笔
收集整理的這篇文章主要介紹了
Python 文本滚动播放
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
效果
雙擊開始播放,繼續(xù)雙擊可以加速播放
右鍵可以彈出菜單:播放、暫停、退出
左鍵可以拖動窗口
代碼
from tkinter import * import timeimport tkinter as tkfile = "待播放文本.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() # 窗口設定為無邊框 root.overrideredirect(True) # 窗口前置 root.wm_attributes("-topmost", 1) # 窗口屬性 透明度設置 root.attributes("-alpha", 0.8) # 窗口標題 # root.title("文本播放器") # 窗口大小 root.geometry("200x35+100+100") # 更新顯示文本 show_str = StringVar(root) # 初始顯示文本 show_str.set("雙擊播放") # 源字符 source_str = text # 播放標記 playflag = True# 播放位置 pos = 0 # 滾動 def marquee(widget):#字符寬度textwidth = 18# 源字符長度strlen = len(source_str)# 引用全局變量global pos# 如果字符長度-播放位置<textwidthif strlen - pos < textwidth:# 設定顯示的字符串為源字符串的(播放位置,播放位置+文本寬度)+ 源字符串的(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])#播放位置+1pos += 1#如果播放位置大于字符串長度if pos > strlen:#播放位置設為0pos = 0# 引用全局變量global stopflag# 如果當前為播放狀態(tài)if playflag:# 睡眠0.3秒后執(zhí)行滾動函數(shù)widget.after(300, marquee, widget)# 創(chuàng)建標簽 show_lb = Label(root, textvariable=show_str,width=300, fg=fgcolor, bg=bgcolor, text=text, font=("Consolas", 10)) # 設定標簽位置 show_lb.place(x=0, y=0, width=200, height=35)def doubleClicktoPlay(event):global playflag# 播放playflag = Truemarquee(show_lb)def playStart():global playflag# 播放playflag = Truemarquee(show_lb)def playStop():global playflag# 暫停播放playflag = False# 創(chuàng)建彈出式菜單 menu = tk.Menu(root, tearoff=0) # 為菜單添加命令標簽 menu.add_command(label="播放", command=playStart) menu.add_command(label="暫停", command=playStop) menu.add_command(label="退出", command=exit)def popUpMenu(event):#在鼠標點擊的位置彈出菜單menu.post(event.x_root, event.y_root)# 為消息事件(按鍵、點擊)綁定函數(shù) root.bind_all("<ButtonRelease-3>", popUpMenu) def moveStart(event):global startX, startY#獲取鼠標的點擊位置的x、ystartX = event.xstartY = event.ydef move(event):#新坐標=鼠標點擊坐標+窗口坐標-初始坐標new_x = (event.x) + root.winfo_x() - startXnew_y = (event.y) + root.winfo_y() - startYs = "200x35+" + str(new_x) + "+" + str(new_y)# 重新設置窗口大小及其位置root.geometry(s)# 為消息事件(按鍵、點擊)綁定函數(shù) root.bind_all("<Button-1>", moveStart) root.bind_all("<B1-Motion>", move) root.bind_all("<Double-Button-1>", doubleClicktoPlay) root.mainloop()注:
如果文本有換行符,切換不會很流暢
可用此方法刪除換行符
更新
新增了設定文本、全屏模式、調節(jié)大小、保存位置、恢復位置的功能
import time import tkinter as tk from tkinter import *file = "playtext.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() # 窗口設定為無邊框 root.overrideredirect(True) # 窗口前置 root.wm_attributes("-topmost", 1) # 窗口屬性 透明度設置 root.attributes("-alpha", 0.8)# 窗口大小,字體 w,h,fs=200,35,10#得到屏幕寬度 sw = root.winfo_screenwidth() #得到屏幕高度 sh = root.winfo_screenheight()def Center(root,w,h):# 居中偏移量# 需要取整dx = int((sw-w) / 2)dy = int((sh-h) / 2)return str(w) + "x" + str(h) +"+"+str(dx)+"+"+str(dy)# 窗口大小 root.geometry(Center(root,w,h)) # 更新顯示文本 show_str = StringVar(root) # 初始顯示文本 show_str.set("雙擊播放") # 源字符 source_str = text #字符寬度 textwidth = 20 det=textwidth-len(source_str) if len(source_str) - textwidth < 0:print(" "*int(det/2)+source_str+" "*int(det/2))source_str=" "*int(det/2)+source_str+" "*int(det/2)# 播放標記 playflag = Truedef replay():global source_str,pos# 從頭播放pos=0# 重新獲取文字getText()source_str = textplayStop()playStart()# 播放位置 pos = 0 # 滾動 def marquee(widget):global source_str# 源字符長度strlen = len(source_str)det=textwidth-len(source_str)if len(source_str) - textwidth < 0:source_str=" "*int(det/2)+source_str+" "*int(det/2)strlen = len(source_str)# 引用全局變量global pos# 如果字符長度-播放位置<textwidthif strlen - pos < textwidth:# 設定顯示的字符串為源字符串的(播放位置,播放位置+文本寬度)+ 源字符串的(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])#播放位置+1pos += 1#如果播放位置大于字符串長度if pos > strlen:#播放位置設為0pos = 0#重新播放replay()# 引用全局變量global playflag# 如果當前為播放狀態(tài)if playflag:# 睡眠0.3秒后執(zhí)行滾動函數(shù)widget.after(300, marquee, widget)# 創(chuàng)建標簽 showlabel = Label(root, textvariable=show_str,width=200, fg=fgcolor, bg=bgcolor, text=text, font=("蘋方", 10)) # 設定標簽位置 showlabel.place(x=0, y=0, width=200, height=35)def doubleClicktoPlay(event):global playflag# 播放playflag = Truemarquee(showlabel)def playStart():global playflag# 播放playflag = Truemarquee(showlabel)def playStop():global playflag# 暫停播放playflag = Falsedef setPosition(dx,dy):s = str(w) + "x" + str(h) +"+"+ str(dx) + "+" + str(dy)root.geometry(s)def getPosition():dx=root.winfo_x()dy=root.winfo_y()s = str(w) + "x" + str(h) +"+"+ str(dx) + "+" + str(dy)# 配置格式:位置 播放速度 with open("偏好配置.txt", "w",encoding='utf-8') as f:f.write(s+" "+str(fs))def Preference():global root,showlabel,fs,wtry:with open("偏好配置.txt", "r",encoding='utf-8') as f:setting=f.readlines()settinglist = setting[0].split(" ")temp=settinglist[0].split("x")w=temp[0]print("huifu:"+settinglist[0])fs=int(settinglist[1])showlabel['font']=("蘋方",fs)# 設定標簽位置showlabel.place(x=0, y=0, width=200, height=35)root.geometry(settinglist[0])except OSError as reason:# 如果不處理錯誤,打包的程序將無法運行 # 窗口居中s=Center(root,w,h)# 窗口大小root.geometry(s)print('沒有配置文件,將使用默認配置\n'+ str(reason))def setSize_old(h):global w,fs#縮放窗口時,保持左上角位置不變x = root.winfo_x() y = root.winfo_y() w = int(h*5.71)fs = int(h/2.14)global showlabel#限制最大和最小尺寸if 20<h<4000:g=Center(root,w,h)#g = f'{w}x{h}+{x}+{y}'root.geometry(g)showlabel['font']=("蘋方",fs)showlabel.place(x=0, y=0, width=w, height=h)def setSize(s,fs):# 根據(jù)指定參數(shù)設定窗口大小global showlabelroot.geometry(s)showlabel['font']=("蘋方",fs)def FullScreen():getPosition()# 創(chuàng)建一個窗口global backback = tk.Tk()# 窗口設定為無邊框back.overrideredirect(True)back.configure(background='black')#得到屏幕寬度sw = root.winfo_screenwidth()#得到屏幕高度sh = root.winfo_screenheight()# 窗口大小,字體w,h=sw,sh# 居中偏移量# 需要取整dx = int((sw-w) / 2)dy = int((sh-h) / 2)# 窗口大小back.geometry(str(w) + "x" + str(h) +"+"+str(dx)+"+"+str(dy))tk.Button(back,text='退出全屏',command=notFullScreen).pack()setSize_old(407)back.mainloop()def notFullScreen():back.destroy()Preference()# 傳值變量 tf=tk.StringVar() # 設置默認值 tf.set("") def Input():# 創(chuàng)建頂級窗口,才可以獲取文本框的值# 但是頂級窗口上亦可接收鼠標拖動,這是一個bugframe = tk.Toplevel()frame.title(" ")# 創(chuàng)建標簽L1 = tk.Label(frame,text="鍵入彈幕:")L1.pack(side='left')# 創(chuàng)建文本框textfield=tk.Entry(frame,bd=5,width=20,textvariable=tf)textfield.pack(side='left')# 綁定文本框textfield.bind('<Return>',ChangeText)# 按鈕button = tk.Button(frame, text="確定")# 按鈕布局button.pack(side='right')# 綁定按鈕button.bind('<Button-1>',ChangeText)frame.mainloop()def ChangeText(event):global show_str# 接收文本框的值res=tf.get()print(res)if len(res) - textwidth < 0:res=" "*int(det/2)+res+" "*int(det/2)res=res*20with open(file, "w",encoding='utf-8') as f:f.write(res)replay()# 創(chuàng)建彈出式菜單 menu = tk.Menu(root, tearoff=0) # 為菜單添加命令標簽 menu.add_command(label="設定文本", command=Input) menu.add_command(label="全屏模式", command=FullScreen) menu.add_command(label="播放", command=playStart) menu.add_command(label="暫停", command=playStop) menu.add_command(label="保存配置", command=getPosition) menu.add_command(label="恢復配置", command=Preference) menu.add_command(label="退出", command=sys.exit)def popUpMenu(event):#在鼠標點擊的位置彈出菜單menu.post(event.x_root, event.y_root)# 為消息事件(按鍵、點擊)綁定函數(shù) root.bind_all("<ButtonRelease-3>", popUpMenu) def moveStart(event):global startX, startY#獲取鼠標的點擊位置的x、ystartX = event.xstartY = event.ydef move(event):#新坐標=鼠標點擊坐標+窗口坐標-初始坐標new_x = (event.x) + root.winfo_x() - startXnew_y = (event.y) + root.winfo_y() - startYs = str(w) + "x" + str(h) +"+"+ str(new_x) + "+" + str(new_y)print(s+" "+str(fs))# 重新設置窗口大小及其位置root.geometry(s)w,h,fs=200,35,10 #鼠標滾輪調整窗口大小 def onMouseWheel(event):global w, h,fs#縮放窗口時,保持左上角位置不變x = root.winfo_x() y = root.winfo_y() if event.delta > 0:h = int(h*1.05)w = int(h*5.71)fs = int(h/2.14)else:h = int(h*0.95)w = int(h*5.71)fs = int(h/2.14)if fs<=10:fs=10elif fs>300:fs=300global showlabelprint(w,h,fs)#限制最大和最小尺寸if 20<h<4000:g = f'{w}x{h}+{x}+{y}'root.geometry(g)showlabel['font']=("蘋方",fs)showlabel.place(x=0, y=0, width=w, height=h)elif h<20:w,h,fs=130,20,10# 為消息事件(按鍵、點擊)綁定函數(shù) root.bind_all("<Button-1>", moveStart) root.bind_all("<B1-Motion>", move) root.bind_all("<Double-Button-1>", doubleClicktoPlay) root.bind_all("<MouseWheel>",onMouseWheel) root.mainloop()彈幕版
移除了讀寫文件的操作,需手動設定文本,優(yōu)化了對短文本的播放
import time import tkinter as tk from tkinter import *text="雙擊播放"bgcolor = '#000000' fgcolor = '#FFFFFF'root = Tk() # 窗口設定為無邊框 root.overrideredirect(True) # 窗口前置 root.wm_attributes("-topmost", 1) # 窗口屬性 透明度設置 root.attributes("-alpha", 0.8)# 窗口大小,字體 w,h,fs=200,35,10#得到屏幕寬度 sw = root.winfo_screenwidth() #得到屏幕高度 sh = root.winfo_screenheight()def Center(root,w,h):# 居中偏移量# 需要取整dx = int((sw-w) / 2)dy = int((sh-h) / 2)return str(w) + "x" + str(h) +"+"+str(dx)+"+"+str(dy)# 窗口大小 root.geometry(Center(root,w,h)) # 更新顯示文本 show_str = StringVar(root) # 初始顯示文本 show_str.set("雙擊播放") # 源字符 source_str = text #字符寬度 textwidth = 20 det=textwidth-len(source_str) if len(source_str) - textwidth < 0:print(" "*int(det/2)+source_str+" "*int(det/2))source_str=" "*int(det/2)+source_str+" "*int(det/2)# 播放標記 playflag = Truedef replay():global source_str,pos# 從頭播放pos=0# 重新獲取文字source_str = textplayStop()playStart()# 播放位置 pos = 0 # 滾動 def marquee(widget):global source_str# 源字符長度strlen = len(source_str)det=textwidth-len(source_str)if len(source_str) - textwidth < 0:source_str=" "*int(det/2)+source_str+" "*int(det/2)strlen = len(source_str)# 引用全局變量global pos# 如果字符長度-播放位置<textwidthif strlen - pos < textwidth:# 設定顯示的字符串為源字符串的(播放位置,播放位置+文本寬度)+ 源字符串的(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])#播放位置+1pos += 1#如果播放位置大于字符串長度if pos > strlen:#播放位置設為0pos = 0# 引用全局變量global playflag# 如果當前為播放狀態(tài)if playflag:# 睡眠0.3秒后執(zhí)行滾動函數(shù)widget.after(300, marquee, widget)# 創(chuàng)建標簽 showlabel = Label(root, textvariable=show_str,width=200, fg=fgcolor, bg=bgcolor, text=text, font=("蘋方", 10)) # 設定標簽位置 showlabel.place(x=0, y=0, width=200, height=35)def doubleClicktoPlay(event):global playflag# 播放playflag = Truemarquee(showlabel)def playStart():global playflag# 播放playflag = Truemarquee(showlabel)def playStop():global playflag# 暫停播放playflag = Falsedef setPosition(dx,dy):s = str(w) + "x" + str(h) +"+"+ str(dx) + "+" + str(dy)root.geometry(s)def getPosition():dx=root.winfo_x()dy=root.winfo_y()s = str(w) + "x" + str(h) +"+"+ str(dx) + "+" + str(dy)# 配置格式:位置 播放速度 with open("偏好配置.txt", "w",encoding='utf-8') as f:f.write(s+" "+str(fs))def Preference():global root,showlabel,fs,wtry:with open("偏好配置.txt", "r",encoding='utf-8') as f:setting=f.readlines()settinglist = setting[0].split(" ")temp=settinglist[0].split("x")w=temp[0]print("huifu:"+settinglist[0])fs=int(settinglist[1])showlabel['font']=("蘋方",fs)# 設定標簽位置showlabel.place(x=0, y=0, width=200, height=35)root.geometry(settinglist[0])except OSError as reason:# 如果不處理錯誤,打包的程序將無法運行 # 窗口居中s=Center(root,w,h)# 窗口大小root.geometry(s)print('沒有配置文件,將使用默認配置\n'+ str(reason))def setSize_old(h):global w,fs#縮放窗口時,保持左上角位置不變x = root.winfo_x() y = root.winfo_y() w = int(h*5.71)fs = int(h/2.14)global showlabel#限制最大和最小尺寸if 20<h<4000:g=Center(root,w,h)#g = f'{w}x{h}+{x}+{y}'root.geometry(g)showlabel['font']=("蘋方",fs)showlabel.place(x=0, y=0, width=w, height=h)def setSize(s,fs):# 根據(jù)指定參數(shù)設定窗口大小global showlabelroot.geometry(s)showlabel['font']=("蘋方",fs)def FullScreen():getPosition()# 創(chuàng)建一個窗口global backback = tk.Tk()# 窗口設定為無邊框back.overrideredirect(True)back.configure(background='black')#得到屏幕寬度sw = root.winfo_screenwidth()#得到屏幕高度sh = root.winfo_screenheight()# 窗口大小,字體w,h=sw,sh# 居中偏移量# 需要取整dx = int((sw-w) / 2)dy = int((sh-h) / 2)# 窗口大小back.geometry(str(w) + "x" + str(h) +"+"+str(dx)+"+"+str(dy))tk.Button(back,text='退出全屏',command=notFullScreen).pack()setSize_old(407)back.mainloop()def notFullScreen():back.destroy()Preference()# 傳值變量 tf=tk.StringVar() # 設置默認值 tf.set("") def Input():# 創(chuàng)建頂級窗口,才可以獲取文本框的值# 但是頂級窗口上亦可接收鼠標拖動,這是一個bugframe = tk.Toplevel()frame.title(" ")# 創(chuàng)建標簽L1 = tk.Label(frame,text="鍵入彈幕:")L1.pack(side='left')# 創(chuàng)建文本框textfield=tk.Entry(frame,bd=5,width=20,textvariable=tf)textfield.pack(side='left')# 綁定文本框textfield.bind('<Return>',ChangeText)# 按鈕button = tk.Button(frame, text="確定")# 按鈕布局button.pack(side='right')# 綁定按鈕button.bind('<Button-1>',ChangeText)frame.mainloop()def ChangeText(event):global show_str,text,source_str# 接收文本框的值res=tf.get()print(res)if len(res) - textwidth < 0:res=" "*int(det/2)+res+" "*int(det/2)res=res*20text=ressource_str=resreplay()# 創(chuàng)建彈出式菜單 menu = tk.Menu(root, tearoff=0) # 為菜單添加命令標簽 menu.add_command(label="設定文本", command=Input) menu.add_command(label="全屏模式", command=FullScreen) menu.add_command(label="播放", command=playStart) menu.add_command(label="暫停", command=playStop) menu.add_command(label="保存配置", command=getPosition) menu.add_command(label="恢復配置", command=Preference) menu.add_command(label="退出", command=sys.exit)def popUpMenu(event):#在鼠標點擊的位置彈出菜單menu.post(event.x_root, event.y_root)# 為消息事件(按鍵、點擊)綁定函數(shù) root.bind_all("<ButtonRelease-3>", popUpMenu) def moveStart(event):global startX, startY#獲取鼠標的點擊位置的x、ystartX = event.xstartY = event.ydef move(event):#新坐標=鼠標點擊坐標+窗口坐標-初始坐標new_x = (event.x) + root.winfo_x() - startXnew_y = (event.y) + root.winfo_y() - startYs = str(w) + "x" + str(h) +"+"+ str(new_x) + "+" + str(new_y)print(s+" "+str(fs))# 重新設置窗口大小及其位置root.geometry(s)w,h,fs=200,35,10 #鼠標滾輪調整窗口大小 def onMouseWheel(event):global w, h,fs#縮放窗口時,保持左上角位置不變x = root.winfo_x() y = root.winfo_y() if event.delta > 0:h = int(h*1.05)w = int(h*5.71)fs = int(h/2.14)else:h = int(h*0.95)w = int(h*5.71)fs = int(h/2.14)if fs<=10:fs=10elif fs>300:fs=300global showlabelprint(w,h,fs)#限制最大和最小尺寸if 20<h<4000:g = f'{w}x{h}+{x}+{y}'root.geometry(g)showlabel['font']=("蘋方",fs)showlabel.place(x=0, y=0, width=w, height=h)elif h<20:w,h,fs=130,20,10# 為消息事件(按鍵、點擊)綁定函數(shù) root.bind_all("<Button-1>", moveStart) root.bind_all("<B1-Motion>", move) root.bind_all("<Double-Button-1>", doubleClicktoPlay) root.bind_all("<MouseWheel>",onMouseWheel) root.mainloop()?
總結
以上是生活随笔為你收集整理的Python 文本滚动播放的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Unity Hub安装Android B
- 下一篇: SQLite编译问题