Python GTK更新标签

标签 python gtk3

我对 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/

相关文章:

python - .loc 与 pandas 一次相同的列

pygtk - Gtk3 Paned Widget 默认同质尺寸

rust - 如何在 Rust/gtk-rs 中创建一个简单的 Gtk MessageDialog?

python - 图片中的文字是否加粗?

python - 在客户端创建 UUID 并使用 Django REST Framework 和使用 POST 保存主键

Python :raise error_perm, 和 ftplib.error_perm : 500?

python - Python Gtk+3 中的排序和过滤树模型..?

css - 如何使 GTK3 在 Windows 7 上看起来像原生的?

python - 将 Gtk.Widget 放入带有顶部填充的 Box 中

python - 为什么 Ruby 比 Python 更适合 Rails?