我一直在尝试使用Python创建计时器程序时遇到问题。 我希望用户可以输入计时器倒计时的时间,并且每隔0.1秒更新一次。 到目前为止,我有以下代码:
from gi.repository import Gtk
import time
import threading
class TimerWindow(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title = "Timer")
self.box = Gtk.Box(spacing = 1)
self.add(self.box)
self.entry = Gtk.Entry()
self.entry.connect("activate", self.start, self.entry)
self.box.pack_start(self.entry, True, True, 0)
def start(self, widget, entry):
starttime = time.time()
totaltime = float(entry.get_text())
self.update(starttime, totaltime, entry)
def update(self, starttime, totaltime, entry):
entry.set_text(str(totaltime - (time.time() - starttime)))
if float(entry.get_text()) > 0:
t = threading.Timer(0.1, self.update, [starttime, totaltime, entry])
t.start()
win = TimerWindow()
win.connect("delete-event", Gtk.main_quit)
win.set_keep_above(True)
win.show_all()
Gtk.main()
这似乎在一段时间内有点起作用,但有时会返回以下内容:
timer.py:31: Warning: g_object_ref: assertion 'object->ref_count > 0' failed
Gtk.main()
Segmentation fault
我不知道是什么原因导致这种情况发生,需要一些帮助。能否有人帮我找到停止这种情况发生的方法?
GObject.timeout_add
的方式运行良好。当使用线程时,即使添加了schedule_update
,我仍然会遇到与之前相同的错误。也许我做错了什么,但毕竟,我对 Python 线程和相关内容还很陌生,所以随便了。 - K ZhangGObject.timeout_add
能够满足您的需求,那么请忘记线程(就此目的而言),因为它们会引入许多复杂性和问题。一旦您在 Python 和 GTK 方面获得更多经验,您将能够在必要时安全地使用线程。 - user4815162342