0

I am trying to collect some input data from a GUI to feed another portion of code. The GUI is defined by a class, I thought the best way was defining some global variable and function to both closing the GUI and updating the variable. If the 'Exit' button is associated with a simple destroy command (option 2 in my script), the GUI is closed but the variable remain undefined. If the button call a separate function (option 1) the GUI remain open and if you close it with X button the variable remain unchanged. Here's the code:

from tkinter import *
from tkinter import ttk

entryVar = ''

class myFrame():
    
    def __init__(self, container):
                
        self.globalFrame = LabelFrame(container, text='Frame name', height=100, width=600, padx=5, pady=5)
        self.globalFrame.pack(fill='x', expand=False) 
        self.myLabel = Label(self.globalFrame, text = 'Change content and check', padx=5)
        self.myLabel.pack(side='left')
        
        self.eVar = StringVar(self.globalFrame)
        self.eVar.set('lorem ipsum')
        
        self.info = Entry(self.globalFrame, textvariable=self.eVar, width=30, justify='right') 
        self.info.pack(side='left')
        
        withExtFunct = True    
        
        if withExtFunct:
            ''' --- option 1 --- '''
            self.myButton = Button(self.globalFrame, text="Exit", command = self.frExit(container))
        else:
            ''' --- option 2 --- '''
            self.myButton = Button(self.globalFrame, text="Exit", command = container.destroy)
        
        self.myButton.pack()
        
    def frExit(self, container):
        global entryVar
        entryVar = 'The entry box is filled with: ' + str(self.eVar.get())
        container.quit

mainWin = Tk()
mainWin.title('Main window')
mainWin.geometry('600x300')

firstFrame = myFrame(mainWin)

mainWin.mainloop()

print('Exiting...')
print(entryVar)

Any help would be appreciated, thanks in advance.

enGG
  • 1
  • 1
  • i think you are just missing the brackets in `container.quit` -> `container.quit()` – Ahmed AEK Jan 25 '23 at 18:16
  • Thanks Ahmed AEK but I tried and it doesn't work – enGG Jan 25 '23 at 18:23
  • 1
    `command = self.frExit(container)` calls the method *right now* (as the Button is being created), and uses its return value (which is None) as the action to be performed when the Button is clicked. You need to pass an actual function here, rather than calling one. – jasonharper Jan 25 '23 at 19:03
  • Thank you for the replies and for pointing me at the right topic. Just in case someone came across this question, the code (working correctly) is now: self.myButton = Button(self.globalFrame, text="Exit", command = lambda: self.frExit(container)) I also modified the frExit function, changing quit with destroy: container.destroy() – enGG Jan 27 '23 at 11:46

0 Answers0