我对 Python 中的 GTK 编程完全陌生。我想解决以下任务:单击“开始”按钮后,应生成 20 个随机数,并显示在窗口中。每个数字之间的时间在增加。
当然,获取随机数不是问题,但我的标签中只显示最后一个数字。但是,print num
命令显示,数字是按照我希望的方式生成的。现在如何显示标签中的数字?
非常感谢,
约瑟夫
我的代码如下所示:
import time as t
import random as rd
import math
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, GLib
class MyWindow(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title="Window 1")
box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=10)
box.set_homogeneous(False)
self.label1 = Gtk.Label()
box.pack_start(self.label1, True, True, 0)
button = Gtk.Button(label="Start")
button.connect("clicked", self.on_button_clicked)
box.pack_start(button, True, True, 0)
self.add(box)
def on_button_clicked(self, widget):
itr=20
for i in range(itr):
waittime=(float(i)/float(itr)*1)**3
num=rd.randint(1,10)
print num
self.label1.set_text(str(num))
t.sleep(waittime)
win = MyWindow()
win.connect("destroy", Gtk.main_quit)
win.show_all()
Gtk.main()
最佳答案
您不允许/强制 Gtk 更新标签文本。例如:
import time as t
import random as rd
import math
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, GLib
class MyWindow(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title="Window 1")
box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=10)
box.set_homogeneous(False)
self.label1 = Gtk.Label()
box.pack_start(self.label1, True, True, 0)
button = Gtk.Button(label="Start")
button.connect("clicked", self.on_button_clicked)
box.pack_start(button, True, True, 0)
self.add(box)
def on_button_clicked(self, widget):
itr=20
for i in range(itr):
waittime=(float(i)/float(itr)*1)**3
num=rd.randint(1,10)
print num
self.label1.set_text(str(num))
while Gtk.events_pending():
Gtk.main_iteration()
t.sleep(waittime)
win = MyWindow()
win.connect("destroy", Gtk.main_quit)
win.show_all()
Gtk.main()
关于Python GTK更新标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53650809/