gpt4 book ai didi

python - 如何每n秒运行一个函数而不中断其他代码?也许在后台运行?

转载 作者:太空宇宙 更新时间:2023-11-03 21:27:07 25 4
gpt4 key购买 nike

Python 是我的第一语言,所以如果没有意义请理解我。我正在用 python 制作一个虚拟宠物。我使用 Tkinter 作为 GUI。我想每 5 秒运行一次 Action 类中的显示方法。但是,如果我使用线程、调度或时间并将代码放在按钮之前,它就会卡住并只运行显示方法。如何每 5 秒运行一次显示方法,同时不中断按钮和其他部分?

class Pet:    
def __init__(self, name, hunger=0, boredom=0, tiredness=0, sickness=False,
age=0, waste=0):
self.__name = name
self.hunger = hunger
self.boredom = boredom
self.tiredness = tiredness
self.sickness = sickness
self.age = age
self.waste = waste
self.choice = choice

class Action(Pet):
def __init__(self, name):
Pet.__init__(self, name, hunger=0, boredom=0, tiredness=0,
sickness=False, age=0, waste=0)
self.name = name

def display(self):
print("------------")
print("hunger", self.hunger)
print("boredom", self.boredom)
print("tiredness", self.tiredness)
print("sickness", self.sickness)
print("age", self.age)
class Window(Frame):
def openmenu(self):
petname = self.petnameEntry.get()
user_pet = Action(petname)
print("I am your pet,", petname)
window = tk.Toplevel(root)
w = Label(window, text="What would you like to do?")
w.pack()

btFeed = Button(window, text="Feed", command=lambda: user_pet.eat())
btFeed.pack(pady=3)
btPlay = Button(window, text="Play", command=lambda:
user_pet.play())
btPlay.pack(pady=3)

最佳答案

您可以使用After方法。

import tkinter as tk
root = tk.Tk()

class Pet:
def __init__(self, name, hunger=0, boredom=0, tiredness=0, sickness=False,
age=0, waste=0):
self.__name = name
self.hunger = hunger
self.boredom = boredom
self.tiredness = tiredness
self.sickness = sickness
self.age = age
self.waste = waste

class Action(Pet):
def __init__(self, name):
Pet.__init__(self, name, hunger=0, boredom=0, tiredness=0,
sickness=False, age=0, waste=0)
self.name = name

def display(self):
print("------------")
print("hunger", self.hunger)
print("boredom", self.boredom)
print("tiredness", self.tiredness)
print("sickness", self.sickness)
print("age", self.age)
root.after(5000,self.display)

root.after(5000,Action(Pet).display)

root.mainloop()

关于python - 如何每n秒运行一个函数而不中断其他代码?也许在后台运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53775875/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com