Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/333.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Tkinter while在后台循环_Python_Python 3.x_Loops_Tkinter - Fatal编程技术网

Python Tkinter while在后台循环

Python Tkinter while在后台循环,python,python-3.x,loops,tkinter,Python,Python 3.x,Loops,Tkinter,我正在Tkinter中编写节拍器代码,其中会弹出一个窗口,其中有一个文本框,您可以在其中键入bpm和一个退出按钮来停止代码。我遇到了一个问题,当播放节拍声音的while循环运行时,我无法单击窗口上的任何内容,因此,我无法单击quit按钮。我(短暂地)尝试过线程化,但我发现它在执行之前运行了所有代码,因此它将文本框读取为空,并在代码将字符串转换为整数以计算播放节拍的频率时返回值错误。简而言之,我需要在Tkinter窗口的背景中运行while循环。 这是我的代码: from tkinter impo

我正在Tkinter中编写节拍器代码,其中会弹出一个窗口,其中有一个文本框,您可以在其中键入bpm和一个退出按钮来停止代码。我遇到了一个问题,当播放节拍声音的while循环运行时,我无法单击窗口上的任何内容,因此,我无法单击quit按钮。我(短暂地)尝试过线程化,但我发现它在执行之前运行了所有代码,因此它将文本框读取为空,并在代码将字符串转换为整数以计算播放节拍的频率时返回值错误。简而言之,我需要在Tkinter窗口的背景中运行while循环。 这是我的代码:

from tkinter import *
from time import sleep
import os
import sys
def quit_():
    screen.destroy()
    sys.exit()
def run():
    bpm = bpm_.get()
    bpm = int(bpm)
    bpm = bpm/60
    bpm = 1/bpm
    while True:
            sleep(bpm)
            os.system("afplay metronome.wav&")

def main():
    global bpm_
    bpm_ = StringVar()
    Label(screen, text="").pack()
    Label(screen, text = "enter a bpm").pack()
    entry = Entry(screen, textvariable=bpm_)
    entry.pack()
    Label(screen, text="").pack()
    Button(screen, text = "enter", command = run).pack()
    Label(screen, text="").pack()
    Button(screen, text = "quit", command = quit_).pack()
screen = Tk()
main()
screen.mainloop()

单击按钮后,会有一个命令自动运行函数,而不是:

while True:
    sleep(bpm)
    os.system("afplay metronome.wav&")
付诸表决:

阅读
sleep(bpm)
os.system("afplay metronome.wav&")
screen.after(1,run)