Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 [Tkinter] Extrakt a Variable from a closed tkinter window
#1
Hello together,

in the following code I want to start to create a tkinter window and open an Excel file, choose the sheet from a tkinter Dropdown and after pressing a Close button I want to Progress with the sheetname and the filename to create a dataframe and going for plots. However, I get enought code to create my tkinter GUI and choose the sheet, but I cant Transfer this sheetname out of the tkinter setup. I post a solution with class, but I am not sure, if ist necessary. Furthermore I am struggeling with the self command. I every case, the main Problem is usual the Output

TypeError: __init__() missing 1 required positional argument: 'master'

and I don't know how to handle this. How can I extract the tkvar right, is the self. command used right and do I have to make a class to work with tkinter as sheet selector. .... I am pretty new in Python and mainly used numpy and matplotlib at the beginning

from tkinter.filedialog import askopenfilename
import tkinter
import pandas as pd
import matplotlib.pyplot as plt

 
class App:
    def __init__(self,master):
        self.master = master
        Filename = askopenfilename(filetypes = (("ExcelFiles","*.xlsm *.xlsx *.xls"),("all files","*.*")),title='Jetzt wähl endlich die Kagg-Datei')
        print(Filename)
        
        self.xl = pd.ExcelFile(Filename)
        print(self.xl.sheet_names)
        print(self.xl.sheet_names[0])
        
        # Add a grid
        self.mainframe = tkinter.Frame(self.master)
        self.mainframe.grid(column=0,row=0, sticky=(tkinter.N,tkinter.W,tkinter.E,tkinter.S) )
        self.mainframe.columnconfigure(0, weight = 2)
        self.mainframe.rowconfigure(0, weight = 2)
        self.mainframe.pack(pady = 100, padx = 100)
        
        self.button = tkinter.Button(self.mainframe, 
                             text="Auswahl", fg="red",
                             command = master.destroy)
        
        # Create a Tkinter variable
        self.tkvar = tkinter.StringVar(self.master)
        
        #Convert xl_SheetNameList into Dictionary
        self.dictOfxl = dict.fromkeys(self.xl.sheet_names , 1)
        
        # Dictionary with options
        choices = self.dictOfxl
        self.tkvar.set(self.xl.sheet_names[0]) # set first xl_Sheet as default option
        
        self.popupMenu = tkinter.OptionMenu(self.mainframe, self.tkvar, *choices)
        tkinter.Label(self.mainframe, text="Choose a sheet").grid(row = 1, column = 1)
        self.popupMenu.grid(row = 2, column =1)
        self.button.grid(row = 3, column = 1)
        
        # on change dropdown value
        def change_dropdown(*args):
           print(self.tkvar.get() )
           
        # link function to change dropdown
        self.tkvar.trace('w', change_dropdown)


master = tkinter.Tk()
master.title("Sheetauswahl") 
app = App(master)
master.mainloop()

print(App().tkvar.get())
sheet = App().tkvar.get()
df = pd.read_excel(Filename, sheet_name=sheet)
print(df)
Best greetings
Quote
#2
why
Quote:command = master.destroy

you destroy the main window.

You never get a main window with your code.

try this and add your other functions

from tkinter.filedialog import askopenfilename
import tkinter
import pandas as pd
import matplotlib.pyplot as plt
from gi.repository import GLib ### linux only
  
class myApp:
    def __init__(self,master):
        self.master = master
        # Add a grid
        self.mainframe = tkinter.Frame(self.master)
        self.mainframe.grid(column=0,row=0, sticky=(tkinter.N,tkinter.W,tkinter.E,tkinter.S) )
        self.mainframe.columnconfigure(0, weight = 2)
        self.mainframe.rowconfigure(0, weight = 2)
        self.mainframe.pack(pady = 100, padx = 100)
         
        self.button = tkinter.Button(self.mainframe, 
                             text="Auswahl", fg="red",
                             command = self.openFile)

        self.popupMenu = tkinter.OptionMenu(self.mainframe, None, None)
        tkinter.Label(self.mainframe, text="Choose a sheet").grid(row = 1, column = 1)
        self.popupMenu.grid(row = 2, column =1)
        self.button.grid(row = 3, column = 1)

    def openFile(self):
        docs = GLib.get_user_special_dir(GLib.USER_DIRECTORY_DOCUMENTS) ### linux only
        Filename = askopenfilename(initialdir=docs, filetypes = (("ExcelFiles","*.xlsm *.xlsx *.xls"),("all files","*.*")),title='Jetzt wähl endlich die Kagg-Datei')
        print(Filename)
        return Filename

if __name__ == '__main__':
    master = tkinter.Tk()
    master.title("Sheetauswahl") 
    sheet = myApp(master).mainframe
    master.mainloop() 
Quote
#3
Ok sorry, I add some additional description:

The programm shall do the following steps in order:

1. Choosing an ExcelFile with openfiledialog automatically after starting the programm
2. Open tkinter GUI and list the sheets from the file of openfiledialog
3. After choosing the right sheet from the dropdownmenu tkinter shall be closed with the button "Auswahl" and additionally the chosen entry of the dropdownmenu shall be extracted as variable for the subsequent algorithm

Is the Main Window necessary to extract the variable? And do I just put the Attributes of the tkinter setup in the class? The window ist not necessary for the further programm.
Quote
#4
When you close the main window there is no variable anymore.
Quote
#5
Well, when I am doing it like this, it worked

from tkinter.filedialog import askopenfilename
import tkinter
import pandas as pd
import matplotlib.pyplot as plt
 
master = tkinter.Tk()
master.title("Sheetauswahl")

Filename = askopenfilename(filetypes = (("ExcelFiles","*.xlsm *.xlsx *.xls"),("all files","*.*")),title='Jetzt wähl endlich die Kagg-Datei')
xl = pd.ExcelFile(Filename)
print(xl.sheet_names)
 
# Add a grid
mainframe = tkinter.Frame(master)
mainframe.grid(column=0,row=0, sticky=(tkinter.N,tkinter.W,tkinter.E,tkinter.S) )
mainframe.columnconfigure(0, weight = 2)
mainframe.rowconfigure(0, weight = 2)
mainframe.pack(pady = 100, padx = 100)

def Quit():
    return master.destroy
 
button = tkinter.Button(mainframe, 
                     text="Auswahl", fg="red",
                     command = Quit())


# Create a Tkinter variable
tkvar = tkinter.StringVar(master)

 
#Convert xl_SheetNameList into Dictionary
dictOfxl = dict.fromkeys(xl.sheet_names , 1)
 
# Dictionary with options
choices = dictOfxl
tkvar.set(xl.sheet_names[0]) # set first xl_Sheet as default option
 
popupMenu = tkinter.OptionMenu(mainframe, tkvar, *choices)
tkinter.Label(mainframe, text="Choose a sheet").grid(row = 1, column = 1)
popupMenu.grid(row = 2, column =1)
button.grid(row = 3, column = 1)
 
# on change dropdown value
def change_dropdown(*args):
    return tkvar.get()
    
# link function to change dropdown
tkvar.trace('w', change_dropdown)

master.mainloop()

sheet = tkvar.get()
print('Der Name ist',sheet)
df = pd.read_excel(Filename, sheet_name=sheet)
print(df)
I don't know if I explained it wrong, but this should be faster to solve...hätte es auch in deutsch erklären können, dass ich einfach nur nach ner Excel Sheet Auswahl Tkinter weghaben wollte und dann mein Programm nach der Mainloop bzw. dem Tkinter weiterlaufen soll mit dem Ausgewählten Tabllenblatt aus dem Dropdown ... wieso soll das nicht gehen?


Best wishes
Quote
#6
If you want to access a variable after the tkinter window closes, then you have to make it an instance object. Snipped version of your code
        def change_dropdown(*args):
           self.remaining_variable=self.tkvar.get()
           print(self.tkvar.get() )
            
        # link function to change dropdown
        self.tkvar.trace('w', change_dropdown)
 
 
master = tkinter.Tk()
master.title("Sheetauswahl") 
app = App(master)
master.mainloop()
 
## app=instance,  App=class
## app remains until you destroy it or close the program
print(app.remaining_variable)
sheet = app.remaining_variable
df = pd.read_excel(Filename, sheet_name=sheet)
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  tkinter window and turtle window error 1885 3 154 Nov-02-2019, 12:18 PM
Last Post: 1885
  [Tkinter] Tkinter window pop up again when i click button Orimura_Sandy 1 519 May-12-2019, 08:17 PM
Last Post: joe_momma
  [Tkinter] Top Level Window - from tkinter import * francisco_neves2020 6 550 Apr-23-2019, 09:27 PM
Last Post: francisco_neves2020
  tkinter- adding a new window after clicking a button built on the gui ShashankDS 2 680 Apr-18-2019, 12:48 PM
Last Post: ShashankDS
  [WxPython] how to reopen a closed tab of wx.aui.Notebook? royer14 2 457 Feb-18-2019, 12:31 AM
Last Post: royer14
  tkinter - global variable not working albry 2 1,240 Jan-26-2019, 04:22 AM
Last Post: Larz60+
  [Tkinter] Tkinter window minimize,appear frequency 5 1,879 Dec-28-2018, 02:02 PM
Last Post: frequency
  [Tkinter] Tkinter window issue frequency 4 652 Dec-24-2018, 10:49 AM
Last Post: frequency
  Variable not sharing same value between two different functions Python 2.7 Tkinter albert 0 546 Aug-31-2018, 10:45 AM
Last Post: albert
  Python, Tkinter, can only view partial GUI when called from another window Philia 1 898 Jul-17-2018, 06:38 PM
Last Post: woooee

Forum Jump:


Users browsing this thread: 1 Guest(s)