在JavaScript中,我习惯于能够调用稍后要执行的函数,就像这样
function foo() {
alert('bar');
}
setTimeout(foo, 1000);
Run Code Online (Sandbox Code Playgroud)
这不会阻止其他代码的执行.
我不知道如何在Python中实现类似的东西.我可以睡觉
import time
def foo():
print('bar')
time.sleep(1)
foo()
Run Code Online (Sandbox Code Playgroud)
但这会阻止其他代码的执行.(实际上在我的情况下阻塞Python本身并不是问题,但我无法对该方法进行单元测试.)
我知道线程是为不同步执行而设计的,但我想知道是否更容易,类似setTimeout或setInterval存在.
我对 python 开发非常陌生,我需要每 x 秒调用一个函数。
所以我尝试使用计时器来实现这一点,例如:
def start_working_interval():
def timer_tick():
do_some_work() // need to be called on the main thread
timer = threading.Timer(10.0, timer_tick)
timer.start()
timer = threading.Timer(10.0, timer_tick)
timer.start()
Run Code Online (Sandbox Code Playgroud)
do_some_work() 方法需要在主线程上调用,我认为使用计时器会导致它在不同的线程上执行。
所以我的问题是,如何在主线程上调用这个方法?
我有以下Python Tkinter代码,它每10秒重绘一次标签.我的问题是,对我而言似乎是在旧标签上一遍又一遍地绘制新标签.因此,最终,几个小时后将有数百个绘图重叠(至少从我的理解).这会占用更多内存还是会导致问题?
import Tkinter as tk
import threading
def Draw():
frame=tk.Frame(root,width=100,height=100,relief='solid',bd=1)
frame.place(x=10,y=10)
text=tk.Label(frame,text='HELLO')
text.pack()
def Refresher():
print 'refreshing'
Draw()
threading.Timer(10, Refresher).start()
root=tk.Tk()
Refresher()
root.mainloop()
Run Code Online (Sandbox Code Playgroud)
在我的例子中,我只使用一个标签.我知道我可以使用textvariable更新标签的文本甚至text.config.但实际上做的是刷新标签网格(如表格)+按钮和内容以匹配可用的最新数据.
从我的初学者的理解,如果我把这个Draw()函数写成类,我可以frame通过使用frame.destroy每当我执行Refresher函数来销毁它.但是我目前拥有的代码是在没有类的函数中编写的(我不希望将整个代码重写为类).
我能想到的另一个选择是frame在Draw()全局和使用中声明frame.destroy()(我不愿意这样做,因为如果我有太多帧(这样做),这可能会导致名称冲突)
如果对旧图纸进行透支不会导致任何问题(除了我看不到旧图纸),我可以忍受.
这些都只是我初学者的想法.我应该在重绘更新的帧之前销毁帧吗?如果是这样,如果代码结构就像我的示例代码一样,我应该以什么方式销毁它?或透支旧标签是好的?
编辑
有人提到python tkinter不是线程安全的,我的代码可能会随机失败.
我实际上把这个链接作为参考使用threading作为我的解决方案,我没有找到任何关于该帖子中的线程安全性.
我想知道我不应该使用的一般情况是threading什么,我可以使用的一般情况是什么threading?
我目前正在制作一个数学游戏,用户有 60 秒的时间来回答尽可能多的问题。到目前为止,除了计时器应该倒计时到 0 或计数到 60 然后停止游戏之外,我一切正常。现在,我将计时器设置为 time.clock() 以计数到 60,当计时器小于该值时,游戏将继续运行。然而,出于某种原因, time.clock() 并没有像我期望的那样工作。我还尝试同时运行两个 while 循环,但也没有用。任何人都可以帮助我吗?只是寻找一种在后台运行计时器的方法。
这是我的代码:
score = 0
timer = time.clock()
lives = 3
while timer < 60 and lives > 0:
if score >= 25:
x = random.randint(-100,100)
y = random.randint(-100,100)
answer = int(raw_input("What is %d + %d? " % (x,y)))
if answer == x + y:
print "Correct!"
score += 1
else:
print "Wrong!"
lives -= 1
elif score >= 20:
x = random.randint(-75,75)
y = random.randint(-75,75)
answer …Run Code Online (Sandbox Code Playgroud)