Creating widgets that automatically update in gtk while still being able to control other widgets

孤街浪徒 提交于 2019-12-10 22:59:10

问题


Ok, In one of my side projects in my process to learn more Python I have been trying to build a gtk app to monitor water temp and update a text box within a gtk app at 10 second intervals. I also want to be able to have a countdown timer that can be displayed in gtk while refreshing every second. I have a GUI built by using glade and gtk but I ran into the issue of the app locking up and becoming unresponsive. After a bit of reading I have figured out that I am going to have to use threading. I have no idea what I am doing when it comes to threading and thought that maybe someone here could help me. I would really like to see how to use threading when using gtk and Glade as the GUI builder. I found this code that uses gtk but I am still having issues. Could I get some help?

import sys
import time
import gtk

from threading import Thread

threadcount=0

class Test (Thread):
    def __init__ (self,button, count=0):
        Thread.__init__(self)
        self.count = count
        self.button=button

    def run (self):
        for i in range(0,10):
            time.sleep(1)
            # Acquire and release the lock each time.
            gtk.threads_enter()
            self.button.set_label("Thread %002d - %d" % (self.count,i))
            gtk.threads_leave()
        gtk.threads_enter()
        self.button.set_label("  Start Thread  ")
        gtk.threads_leave()

def start_new_thread (button, data=None):
    global threadcount
    threadcount += 1
    a = Test(button,threadcount)
    a.start()


def hello(*args):
    """ Callback function that is attached to the button """
    print "Hello World"
    window.destroy()

def destroy(*args):
    """ Callback function that is activated when the program is destoyed
"""
    window.hide()
    gtk.main_quit()

# Initialize threads
gtk.threads_init()

window = gtk.Window(gtk.WINDOW_TOPLEVEL)
window.connect("destroy", destroy)
window.set_border_width(10)

button = gtk.Button("  Start Thread  ")
button.connect("clicked", start_new_thread,button)
window.add(button)
button.show()

window.show_all()
gtk.threads_enter()
gtk.main()
gtk.threads_leave()

Here is the code that I have tried to use that is stripped down to just the timer function. I am not sure how to make everything work. I have read something about gobjects but I know even less about that.

import gtk
import time
import sys
import os
import threading

TIME = 0
LOCK = threading.Lock()

class Timer(threading.Thread):
    def __init__(self, nMinutes):
        threading.Thread.__init__(self)
        self.nMin = nMin
    def run(self):
        global TIME
        nSeconds = self.nMinutes*60
        TIME = nSeconds
        startTime = time.time()
        while TIME != 0:
            ElapTime = time.time() - startTime
            LOCK.acquire()
            TIME = nSeconds - ElapTime
            LOCK.release()

class GUI_Timer_Update(threading.Thread):
    def __init__(self, TIME):
        threading.Thread.__init__(self)
        self.TIME = TIME
    def run(self):
        while TIME != 0:
            timeFormatted = self.format_time(TIME)
            LOCK.acquire()
            # Code that updates the GUI after formatting it
            LOCK.release()


    def format_time(self, x):
        minutes, seconds_rem = divmod(x, 60)
        if minutes >= 60:
            hours, minutes_rem = divmod(minutes, 60)
            return "%02d:%02d:%02d" % (hours, minutes_rem, seconds_rem)
        else:
            minutes, seconds_rem = divmod(x, 60)
            return "00:%02d:%02d" % (minutes, seconds_rem)

class GUI(object):
    def __init__(self):
        self.builder = gtk.Builder()
        self.builder.add_from_file("Timer.glade")
        self.window1 = self.builder.get_object("window1")
        self.window1.show()
        self.builder.connect_signals(self)

    def on_window1_destroy(self, object, data=None):
        print "quit on destroy"
        gtk.main_quit()

    def on_startTimer_clicked(self, widget):
        self.timer = self.builder.get_object("timer").get_text() # get time in minutes from timer text box 
        self.timer = int(self.timer) # convert the text to an int

    def on_timerReset_clicked(self, widget):
        self.builder.get_object("timer").set_text('')
        self.builder.get_object("TIME").set_text('')

    def main(self):
        gtk.main()  


if __name__ == "__main__":
    gui = GUI()
    gui.main()

I would also like to incorporate a Stop/ Pause button too. Any help would be appreciated. Thanks


回答1:


Ok, I have edited my code to the following:

import gtk, time, sys, os, gobject

COUNTER = 0
COUNTER2 = 0

class GUI(object):
    def __init__(self):
        self.builder = gtk.Builder()
        self.builder.add_from_file("Timer.glade")
        self.window1 = self.builder.get_object("window1")
        self.window1.show()
        self.builder.connect_signals(self)
        self.g = 0

    def on_window1_destroy(self, object, data=None):
        print "quit on destroy"
        gtk.main_quit()

    def on_startTimer_clicked(self, widget):
        global COUNTER
        self.time = self.builder.get_object("time").get_text()
        COUNTER = int(self.time)
        self.g = gobject.timeout_add(1000, self.timer)


    def on_startTimer2_clicked(self, widget):
        global COUNTER2
        self.time2 = self.builder.get_object("time2").get_text()
        COUNTER2 = int(self.time2)
        self.g2 = gobject.timeout_add(1000, self.timer2)

    def timer2(self):
        global COUNTER2
        while COUNTER2 >= 0:
            if COUNTER2 != 0:
                self.builder.get_object("time2").set_text(str(self.format_time(COUNTER2)))
                COUNTER2 -=1
                return True
            else:
                self.builder.get_object("time2").set_text("Finished")
                return False

    def timer(self):
        global COUNTER
        while COUNTER >= 0:
            if COUNTER != 0:
                self.builder.get_object("time").set_text(str(self.format_time(COUNTER)))
                COUNTER -=1
                return True
            else:
                self.builder.get_object("time").set_text("Finished")
                return False


    def format_time(self, x):
        minutes, seconds_rem = divmod(x, 60)
        if minutes >= 60:
            hours, minutes_rem = divmod(minutes, 60)
            return "%02d:%02d:%02d" % (hours, minutes_rem, seconds_rem)
        else:
            minutes, seconds_rem = divmod(x, 60)
            return "00:%02d:%02d" % (minutes, seconds_rem)



    def main(self):
        gtk.main()  


if __name__ == "__main__":
    gui = GUI()
    gui.main()

This video series got me on my way to understanding how to use gobject.timeout_add(). Thank you user4815162342 for the suggestion.



来源:https://stackoverflow.com/questions/24833194/creating-widgets-that-automatically-update-in-gtk-while-still-being-able-to-cont

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!