Is there a way to wrap a tkinter GUI in a class that can be created and interacted with from another object? (*without* hanging in mainloop)
Is there a way to wrap a tkinter GUI in a class that can be created and interacted with from another object? For this to be really useful, the class has to work so mainloop or its equivalent doesn't hold the application. If so, can someone point me to a working example?
For context, what I'm trying to 开发者_开发问答do is make a SimpleUI class that I can use in any application to allow it to display information or register functions to be executed on button or key presses. So any threading, queues, etc. I would like to have hidden in the SimpleUI class.
Based on what I've gathered from reading around, the answer is No without re-implementing mainloop. Rather, the GUI should be the main application which farms out work through one method or another. However, this would make any application with tkinter (perhaps other GUIs as well?) feel like the tail is wagging the dog. Hopefully I have misunderstood what I have beeing reading.
I know this may seem like a repost of this and other similar questions but I can't comment on those and the answers seem to be doing the opposite of what I want to do. In addition to that question, I've found bits and pieces of related code in many places, but I have not been able to put them together. If there is a way, I'll learn Python threads or whatever to make it work.
I'm using Python 3.1 if it makes any difference.
Example of how I would like it to work.
ui = SimpleUI()
ui.hide()
ui.show()
ui.add_frame...
ui.add_button...
ui.register_function(button, function)
Is this what you're looking for?
#The threading module allows you to subclass it's thread class to create
#and run a thread, in this case we will be starting SimpleUI in a seperate thread
import threading
from Tkinter import *
def printfunction():
print "ButtonPress"
class NewClass:
def __init__(self):
self.ui = SimpleUI()
self.ui.add_frame("frame1")
self.ui.add_button("button1","frame1")
self.ui.register_function("button1",printfunction)
self.ui.start()
#self.ui = Threader().start()
def PrintSuccess(self):
print "Success!"
class SimpleUI:
def __init__(self):
self.root = Tk()
self.frames = {}
self.buttons = {}
def start(gui):
class Threader(threading.Thread):
def run(self):
gui.root.mainloop()
Threader().start()
def hide(self):
self.root.withdraw()
if(raw_input("press enter to show GUI: ")==""):self.show()
def show(self):
self.root.update()
self.root.deiconify()
def add_frame(self,name):
tmp = Frame(self.root)
tmp.pack()
self.frames[name] = tmp
def add_button(self,name,frame):
tmp = Button(self.frames[frame])
tmp.pack()
self.buttons[name] = tmp
def register_function(self,button,function):
self.buttons[button].config(command=function)
NC = NewClass()
NC.PrintSuccess()
精彩评论