【问题标题】:Python GTK update labelPython GTK 更新标签
【发布时间】:2018-12-06 20:30:08
【问题描述】:

我对 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()

【问题讨论】:

    标签: python gtk3


    【解决方案1】:

    您不允许/强制 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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-15
      • 2015-05-24
      • 1970-01-01
      相关资源
      最近更新 更多