Question

I'm trying to make a launcher for my Python program with Tkinter. I used the execfile function, and fortunately it opened the target GUI. However, none of the buttons would work, and it would say the global variable most functions reference isn't defined.

The code to launch the program:

def launch():
    execfile("gui.py")

That works. The base code for the target program:

from Tkinter import *
gui = Tk()
gui.title("This is a GUI")

EDIT: Example of a button:

def buttonWin():
    buttonWindow = Toplevel(gui)
    button = Button(buttonWindow, text = "Button", width = 10, command = None)
    button.pack()

When it references that 'gui' variable for Toplevel, it comes up with an error. I tried defining the 'gui' variable in the Launcher script, but that only caused the target script to open first, instead of the Launcher:

gui = Tk()
launcher = Tk()
launcher.title("Launcher")
def launch():
    return execfile("gui.py")
launchButton = Button(launcher, text = "Launch", width = 10, command = launch)

When I try pressing one of this program's buttons, I get a NameError: $NameError: Global variable 'gui' is not defined$ Also this is in Python 2.7.5. Thank you anyone who answers, and sorry for any errors with the code blocks; I'm new.

Was it helpful?

Solution

The problem is that you have structured the Tkinter program incorrectly.

In "gui.py" you should have something like:

from Tkinter import *

gui= Tk()
gui.mainloop()

You can add buttons to perform functions and customize it:

from Tkinter import *

gui = Tk()
gui.title("This is a GUI")    

def launch():
    execfile("gui.py")

launchbutton = Button(gui, text='Launch Program', command=launch)
launchbutton.pack()

gui.mainloop()

I think with your function buttonWin you were trying to do what is normally handled by a class; see unutbu's answer here.

I'm not sure if I've addressed your problem, but this should be a start.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top