Tkinter - set master in another script

Asked

Viewed 54 times

3

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

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

consumeScreen = Toplevel(mainScreen)

NameError: name 'mainScreen' is not defined

follows 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 2° 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 home screen (mainScreen)?

1 answer

0

You can’t just play a file variable .py running to an imported file. To troubleshoot the problem, you can pass mainScreen as a function argument consume. Example:

Second file . py

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

Script . py to be executed.

from tkinter import *
import funções as fc

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

fc.consume(mainScreen) 
  • It does not work because the command parameter set with the function inside a button does not accept arguments: bt_Consume = Button(text = 'Report Consume', command = Fc.consume)

  • 1

    Can you please leave all the code so I can help you ?

  • The whole code is too big, it makes it impossible to share. I managed to solve by creating a smaller function that only matters the constructor function (where there is all the code of the new window). I don’t think that’s the best solution, but it worked.

  • For the code you presented in the question, the only way to correct it is the one I put in the answer. But other parts of your code apparently have some problems like you said in the comment above. This parameter "command" for example, I didn’t even know it existed.

  • This parameter is the Tkinter for buttons, where I pass a function that will be executed when pressing the button, however, this function can not receive any parameter. So the solution I found is to create a smaller function, responsible for calling the main function (which builds the app screen) and pass it to the command parameter. But thanks for your help!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.