Python: How to create a separate module for the GUI class

tkinter advanced examples
cool tkinter programs
tkinter example python 3
python gui
python gui login application using tkinter
tkinter sample projects
python gui projects
python tkinter tutorial

This code is working fine. MyApp is the class doing all the work and MyGUI is the user interface showing and requesting data from MyApp.

class MyGUI(): # displays results from MyApp and sends request to MyApp (e.g. fetch prices new prices)

    def __init__(self):
        print("GUI running")

    def user_request_price(self,ticker):        
        self.req_price(ticker)

    # methods I request from MyApp 
    def req_price(self,ticker): 
        app.get_price(ticker)

    # methods I receive from MyApp
    def print_price(self,val,price):
        print (val,":",price)    

class MyApp(): # does a lot of stuff, e.g. fetch prices from a server

    def __init__(self):
        self.id = 0
        self.gui = MyGUI() # start gui

    # methods called by GUI
    def get_price(self, ticker):
        if ticker == "MSFT": price = 20.23
        self.output_price(ticker,price)

    # methods sent to GUI
    def output_price(self,ticker,price):
        self.gui.print_price(ticker,price)


if __name__ == "__main__": 
    app = MyApp()
    app.gui.user_request_price("MSFT")

Now I want to put the GUI into a separate module so creating a module file gui.py and import that in the MyApp file:

from gui import *

and that's it. Where I struggle: how does gui.py look like and how can MyGUI() access MyApp methods? Is it wise to do this separation? Any other suggestions for structuring?

The gui.py file would just be

class MyGUI(): # displays results from MyApp and sends request to MyApp (e.g. fetch prices new prices)

def __init__(self):
    print("GUI running")

def user_request_price(self,ticker):        
    self.req_price(ticker)

# methods I request from MyApp 
def req_price(self,ticker): 
    app.get_price(ticker)

# methods I receive from MyApp
def print_price(self,val,price):
    print (val,":",price) 

Add the import to the top of myapp.py and everything should work fine.

I try and Seperate out my code into seperate files if it makes sense. It makes reading things much clearer.

Create UI using Tkinter in Python, Learn how to create an UI in Python using TKinter. a software toolkit having a collection of classes that define a functionality of various GUI elements. PyGTK is the module that ports Python to another popular GUI widget toolkit called GTK. Now we will briefly look at creating a program with a graphical user interface, or GUI. In this chapter we will use tkinter, a module in the Python standard library which serves as an interface to Tk, a simple toolkit. There are many other toolkits available, but they often vary across platforms.

in your gui.py

from myapp import MyApp

class MyGUI(): # displays results from MyApp and sends request to MyApp (e.g. fetch prices new prices)

    app = MyApp()

    def __init__(self):
        print("GUI running")

    def user_request_price(self,ticker):        
        self.req_price(ticker)

    # methods I request from MyApp 
    def req_price(self,ticker): 
        app.get_price(ticker)

    # methods I receive from MyApp
    def print_price(self,val,price):
        print (val,":",price)  

And in your myapp.py (Notice the first line), And make sure both the files are in same directory or else you must change your import relatively.

from gui import MyGUI

class MyApp(): # does a lot of stuff, e.g. fetch prices from a server

    def __init__(self):
        self.id = 0
        self.gui = MyGUI() # start gui

    # methods called by GUI
    def get_price(self, ticker):
        if ticker == "MSFT": price = 20.23
        self.output_price(ticker,price)

    # methods sent to GUI
    def output_price(self,ticker,price):
        self.gui.print_price(ticker,price)

if __name__ == "__main__": 
    app = MyApp()
    app.gui.user_request_price("MSFT")

Introduction to GUI programming with tkinter, In this chapter we will use tkinter , a module in the Python standard library which We are using three widgets: Tk is the class which we use to create the root window Toplevel is a container widget which is displayed as a separate window. Any Python file can be referenced as a module. Some modules are available through the Python Standard Library and are therefore installed with your Python installation. Others can be installed with Python’s package manager pip. Additionally, you can create your own Python modules since modules are comprised of Python .py files.

Finally I did this - seems to be the best approach to have a clear separation and communication between app and gui.

Gui:

import queue

def __init__(self):
    threading.Thread.__init__(self)
    self.requests = queue.Queue()  # request queue for App
    self.start()

def queue_request(self,reqId,val):
    self.requests.put([reqId,val])

APP:

import threading
import queue

def checkGUIQueue(self):
    threading.Timer(1.0, self.checkGUIQueue).start() # check every 1 second                
    while not self.gui.requests.empty():
        (id,value) = self.gui.requests.get()
        ... process request ...

Python GUI Programming Cookbook, We do this by creating a separate class that has the tooltip functionality, and then we create an instance of this class in the same Python module that creates our  GUI programming readily lends itself to an object-oriented style, since a GUI is made up entirely of objects -- labels, buttons, scrollbars, text areas, etc. Since you're already using objects, organizing your code into larger objects makes sense.

(Tutorial) Introduction to GUI With TKINTER in PYTHON, It is implemented as a Python expansion module. The Frame class will help in creating a division between the window. state of the checkbutton will be tracked by IntVar() , which will be stored in a separate variable. Python program to create a list centered on zero; Python Program to create an OTP by squaring and concatenating the odd digits of a number; How to create a Class in JShell of Java 9; Python program to create a list of tuples from given list having number and its cube in each tuple; Python program to find number of local variables in a function; Create Classes Dynamically in Python; Python | Ways to create triplets from given list; Python | Create a dictionary using list with none values

Python GUI and MVC - get variable from other module, You're on the right track. The controller is what binds the app together, so passing it around to the various view and model classes is fine. However, don't think  Learn how to develop GUI applications using Python Tkinter package, In this tutorial, you'll learn how to create graphical interfaces by writing Python GUI examples, you'll learn how to create a label, button, entry class, combobox, check button, radio button, scrolled text, messagebox, spinbox, file dialog and more

How to Build a Python GUI Application With wxPython – Real Python, In this article, you'll learn how to build a graphical user interface with Python using the You can actually pass in multiple flags if you wish as long as you separate A case could also be made for putting each class into its own module, but to  Introduction In Python, a module is a self-contained file with Python statements and definitions. For example, file.py, can be considered a module named file. This differs from a package in that a package is a collection of modules in directories that give structure and hierarchy to the modules. Modules help us break down large programs into small files that are more manageable. With modules

Comments
  • Yea it's okay to seperate them both. And it's easy to import your backend methods via from <module_name> import all
  • "gui.py", line 11 NameError: name 'app' is not defined
  • I've update the code but however your example seems to have lot of interleaving between two classes. You must however always try to attain one-way dependency between classes. So when you write code try to write all the backend methods in one class and import that entire class into your frontend file. And do not bring your frontend methods into your backend class.
  • Thanks but still does not work. > ImportError: cannot import name 'MyGUI' So at least pyhton 3.6. forbids mutual cross referencing. Your comment makes a good point but that's just the nature if you want to strictly seperate GUI from core. GUI sends messages to core and receives messages from core. Very open for a generic approach to solve this.