2 回答

TA貢獻1779條經驗 獲得超6個贊
問題似乎與您的程序的組織有關。while不需要那個循環(huán)。我做了一個簡單的例子,說明如何after工作。在after循環(huán)中調用的函數(shù)應該從decide_colour()函數(shù)中獲取它需要的數(shù)據(jù)。在這個例子中,它將是my_count().
from tkinter import *
class Counter(Frame):
def __init__(self, master=None):
self.count = 0
super().__init__(master)
self.grid()
self.__create_widgets()
def __create_widgets(self):
self.count_label = Label(self)
self.count_label["text"] = str(self.count)
self.count_label["pady"] = 5
self.count_label.grid()
def my_count(self):
self.count = self.count+1
self.count_label["text"] = str(self.count)
root = Tk()
counter = Counter(master=root)
#do you app set up here
root.title("Counter")
root.geometry('460x400')
def do_one_iteration():
counter.my_count()
root.after(500, do_one_iteration)
do_one_iteration()
counter.mainloop()

TA貢獻1772條經驗 獲得超8個贊
好吧,這不是我想要的答案,但它仍然是一個答案
我把代碼放在一起,經過一些調整,我來到了這個。
from tkinter import *
import sounddevice as sd
import numpy as np
import time
duration = 1 #
def decide_colour():
def print_sound(indata, outdata, frames, tijd, status):
global colour
volume_norm = np.linalg.norm(indata)
time.sleep(1)
# set fill colour
if 2 < volume_norm < 4:
colour = "yellow"
elif volume_norm > 4:
colour = "red"
else:
colour = "green"
print(volume_norm, colour)
with sd.Stream(callback=print_sound):
sd.sleep(duration * 1000)
class TrafficLights:
def __init__(self):
root = Tk()
root.title("Stoplicht")
root.configure(bg='black')
root.geometry('460x400')
# Frame voor widgets
frame = Frame(root)
frame.grid()
self.colour = StringVar()
# canvas voor lichten
self.canvas = Canvas(root, width=460, height=400, bg="black")
self.canvas.create_rectangle(190, 10, 310, 350, outline='white', fill='black')
self.canvas.grid()
self.oval_red = self.canvas.create_oval(200, 20, 300, 120, fill="red")
self.oval_yellow = self.canvas.create_oval(200, 130, 300, 230, fill="white")
self.oval_green = self.canvas.create_oval(200, 240, 300, 340, fill="white")
def create_frame():
decide_colour()
if colour == 'red':
self.canvas.itemconfig(self.oval_red, fill="red")
self.canvas.itemconfig(self.oval_yellow, fill="white")
self.canvas.itemconfig(self.oval_green, fill="white")
elif colour == 'yellow':
self.canvas.itemconfig(self.oval_red, fill="white")
self.canvas.itemconfig(self.oval_yellow, fill="yellow")
self.canvas.itemconfig(self.oval_green, fill="white")
elif colour == 'green':
self.canvas.itemconfig(self.oval_red, fill="white")
self.canvas.itemconfig(self.oval_yellow, fill="white")
self.canvas.itemconfig(self.oval_green, fill="green")
create_frame()
root.update()
time.sleep(1)
root.destroy()
return
while True:
TrafficLights()
所以現(xiàn)在它在一秒鐘后打開一個新的主循環(huán)并破壞之前的主循環(huán)。我實際上希望它在一個主循環(huán)中更新,但不知道如何更新,所以如果有人知道請告訴我
添加回答
舉報