import time
from pygame import mixer
from tkinter import filedialog, Tk, BOTH
from tkinter.ttk import Frame, Button
from tkinter import *
def playFile(filePath, interval = 5, playTime = 60):
playCount = int(playTime//interval)
for play in range(0, playCount):
mixer.init()
mixer.music.load(filePath)
mixer.music.play()
time.sleep(interval*60)
global clicked
clicked = False
def findFile():
global clicked
clicked = True
fileLocation = filedialog.askopenfilename(initialdir = "C:/", title = "Select file", filetypes = (("mp3 files","*.mp3"), ("m4a files", ".m4a"), ("all files","*.*")))
return fileLocation
file = ''
class Example(Frame):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.master.title("Interval Player")
self.pack(fill=BOTH, expand = 1)
openButton = Button(self, text = "Open", command=findFile)
openButton.place(x=0, y=0)
def main():
root = Tk()
root.geometry("250x150+300+300")
if clicked == True:
file = str(openButton.invoke())
playFile(file)
app = Example()
root.mainloop()
if __name__ == '__main__':
main()
当我选择调用按钮的结果时,在单击openButton之前将打开文件浏览器窗口。在调用按钮中的值之前,如何使程序等待按钮按下?
我尝试使用带有True / False的全局变量来查找是否已单击按钮。但是,我觉得程序没有重复检查此布尔值。也许有一个必须添加playFile的特定功能?
答案 0 :(得分:0)
您的代码
if clicked == True:
file = str(openButton.invoke())
playFile(file)
从不使用。
您需要做的是在弹出消息框后采取行动
因此
def findFile():
global clicked
clicked = True
fileLocation = filedialog.askopenfilename(initialdir = "C:/", title = "Select file", filetypes = (("mp3 files","*.mp3"), ("m4a files", ".m4a"), ("all files","*.*")))
return fileLocation
成为
def findFile():
global clicked
clicked = True
fileLocation = filedialog.askopenfilename(initialdir = "C:/", title = "Select file", filetypes = (("mp3 files","*.mp3"), ("m4a files", ".m4a"), ("all files","*.*")))
if fileLocation:
playFile(fileLocation)
return fileLocation
完整的示例
import time
from pygame import mixer
from tkinter import filedialog, Tk, BOTH
from tkinter.ttk import Frame, Button
from tkinter import *
def playFile(filePath, interval = 5, playTime = 60):
playCount = int(playTime//interval)
for play in range(0, playCount):
mixer.init()
mixer.music.load(filePath)
mixer.music.play()
time.sleep(interval*60)
global clicked
clicked = False
def findFile():
global clicked
clicked = True
fileLocation = filedialog.askopenfilename(initialdir = "C:/", title = "Select file", filetypes = (("mp3 files","*.mp3"), ("m4a files", ".m4a"), ("all files","*.*")))
playFile(fileLocation)
return fileLocation
file = ''
class Example(Frame):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.master.title("Interval Player")
self.pack(fill=BOTH, expand = 1)
openButton = Button(self, text = "Open", command=findFile)
openButton.place(x=0, y=0)
def main():
root = Tk()
root.geometry("250x150+300+300")
app = Example()
root.mainloop()
if __name__ == '__main__':
main()