python – Tkinter – set master in another script

Question:

I'm creating a GUI with Tkinter and I'm having problems separating the functions from the main file (as it's getting too big).

I created a new functions file, when I try to import the function that creates a new screen (Toplevel) I get the error that the parent (master) window is not recognized:

consumeScreen = Toplevel(mainScreen)

NameError: name 'mainScreen' is not defined

follow the code from the first screen:

from tkinter import *
import funções as fc

mainScreen = Tk()
mainScreen.geometry('600x415')
mainScreen.title('System')
mainScreen['bg'] = 'black'

fc.consume() 

Now the constructor function which is in a 2nd file called 'functions':

def consume():
    consumeScreen = Toplevel(mainScreen)
    consumeScreen.geometry('500x500')
    consumeScreen.title('Report Consume')

How do I make the second file recognize the name of the splash screen (mainScreen)?

Answer:

You can't just drop a variable from the .py file that is running to an imported file. To solve the problem, you can pass mainScreen as an argument to the consume function. Example:

Second .py file

def consume(mainScreen):
    consumeScreen = Toplevel(mainScreen)
    consumeScreen.geometry('500x500')
    consumeScreen.title('Report Consume')

.py script that will be executed.

from tkinter import *
import funções as fc

mainScreen = Tk()
mainScreen.geometry('600x415')
mainScreen.title('System')
mainScreen['bg'] = 'black'

fc.consume(mainScreen) 
Scroll to Top