-1

I'm writing a metronome code in Tkinter where a window pops up with a text box where you can type in the bpm and a quit button to stop the code. I've run into a problem where when the while loop that plays the beat sound is running, I can't click anything on the window and because of that, I can't click the quit button. I've (briefly) tried threading but what I found was that it ran all the code before executing it so it read the text box as empty and returned a Value error when the code turns the string into an integer to calculate how often to play a beat. In short, I need to run a while loop in the background of a Tkinter window. This is my code:

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()
  • Read [While Loop Locks Application](https://stackoverflow.com/questions/28639228/python-while-loop-locks-application) – stovfl Jan 18 '20 at 17:47

1 Answers1

-1

There is a command to auto run a function once you click a button instead of:

while True:
    sleep(bpm)
    os.system("afplay metronome.wav&")

Put:

sleep(bpm)
os.system("afplay metronome.wav&")
screen.after(1,run)
martineau
  • 119,623
  • 25
  • 170
  • 301