Python Forum
[Tkinter] HOW TO: Use Globals In Module ???
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tkinter] HOW TO: Use Globals In Module ???
#3
Thanks metulburr!
Your suggestion looks reasonable and your advice is sound. I did a LOT of searching, and did find MANY caveats regarding Globals. However, I did also find the following ELEGANT and sanctioned solution, which works great for my program:

Python Software Foundation
Programming FAQ: How do I share global variables across modules?

It is very brief and is well worth looking at. Basically, you just put all the Globals in a "config.py" file. That puts them all in a single file in their own namespace ... I use "import config as G", so each Global is "G.name". Without this I would be passing TONS of stuff ... 3 arrays of 65 widgets each, a dictionary of complex dynamic widget formats, and many other variables. Each of the FIVE steps of the State Machine manipulates them differently.

# Module config.py
Root = []       # Global Window identifier
Label1 = []     # Global Label identifier
Count = 0       # Global Keystroke counter
# Module Test for Globals and Modules
import tkinter as tk
import config as G
import setup
 
G.Root = tk.Tk()  # Create the GLOBAL root window

# Create and load the display label
setup.setup()
 
# #########  Keyboard 'Keypress' event handler  #########
def key(event):
    G.COUNT += 1
    msg = '%d %r %d %d' %(G.COUNT,event.keysym,event.keysym_num,event.state)
    print(msg)
# #######################################################
 
# Bind the Keypress event to the 'key' event handler
G.Root.bind_all('<Key>', key)
# Exit to the running event-driven app
G.Root.mainloop()
# MODULE "setup.py" in moduletest
import tkinter as tk
import config as G
 
def setup():
    # Create and load the display label into the window
    prompt = '        Press any key        '
    G.Label1 = tk.Label(G.Root, text=prompt, width=len(prompt), bg='yellow')
    G.Label1.pack()   #  <-- pack/grid MUST be on separate line !!!
    return
Blessings in abundance, all the best, & ENJOY!
Art in Carlisle, PA USA
Reply


Messages In This Thread
HOW TO: Use Globals In Module ??? - by Webtest - May-09-2019, 12:45 PM
RE: HOW TO: Use Globals In Module ??? - by Webtest - May-10-2019, 04:28 AM
RE: HOW TO: Use Globals In Module ??? - by snippsat - May-10-2019, 06:30 AM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020