I'm completely new to GTK programming in python. I want to solve the following task: After clicking a START button, 20 random numbers should be generated, and be shown in the window. The time between each number is increasing.
Of course getting the random numbers is not a problem, but only the last number is shown in my label. However, the print num
command shows, that the numbers are generated the way I want them to be generated. How can I show the numbers in the label now?
Thanks a lot,
Josef
My code looks the following:
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()
You are not allowing/forcing Gtk to update the label text. For example:
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()