I'm having trouble decoding an image when I import it from another file.
I have four .py files to make two buttons.
In the first, on line 21, the button works and brings the image, in the second, on line 28, which is imported from another file, it appears as a button but without an image. How can I resolve this?
lab.py
import tkinter as tk
import base64
from imagens import *
from cores import *
from widgets import *
class Janela(Images):
def __init__(self) -> None:
self.images_base64()
self.tamJanela()
def tamJanela(self):
self.janela_doMenu = tk.Tk()
janela = self.janela_doMenu
# janela.state('zoomed')
janela.title('Disk Gás Gonçalves')
janela.configure(background=preto_claro)
janela.geometry("%dx%d" % (janela.winfo_screenwidth(), janela.winfo_screenheight()))
# Here the code works ###############################################################
self.img_icoName = tk.PhotoImage(data=base64.b64decode(self.editUser))
self.rotulo_nome2 = tk.Button(master=janela, image=self.img_icoName, activebackground='#00FA9A', bg='#4F4F4F',
highlightbackground='#4F4F4F', highlightcolor='#4F4F4F')
self.rotulo_nome2.grid(row=0, column=0)
# Here the code does not work #######################################################
# I'm importing from widgets.py #####################################################
Botoes(janela)
janela.minsize(1200, 640)
janela.mainloop()
Janela()
widgets.py
import tkinter as tk
import base64
from imagens import *
from cores import *
class Botoes(Images):
def __init__(self, local) -> None:
self.images_base64()
self.local = local
self.bt()
def bt(self):
self.img_icoName = tk.PhotoImage(data=base64.b64decode(self.editUser))
self.rotulo_nome2 = tk.Button(master=self.local, image=self.img_icoName, activebackground='#00FA9A', bg='#4F4F4F',
highlightbackground='#4F4F4F', highlightcolor='#4F4F4F')
self.rotulo_nome2.grid(row=1, column=0)
cores.py
preto_claro = '#4F4F4F'
verde_médio = '#00FA9A'
vermelho_salmão = '#FA8072'
azul_seleção = '#F0FFFF'
verde_limão = '#00FF00'
branco_gelo = '#EDEBE6'
imagens.py
import base64
class Images:
def images_base64(self):
self.addUser = 'iVBORw0KGgoAAAANSUhEUgAAADIAAAAyCAYAAAAeP4ixAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAABmJLR0QA/wD/AP+gvae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ss2dWx/qt1hpHTYDACSoCH/+a9Kx7nfwAPPztG5sk4owAAACV0RVh0ZGF0ZTpjcmVhdGUAMjAyMi0wOS0yMlQyMjoxNjoxNyswMDowMOu8Z3oAAAAldEVYdGRhdGU6bW9kaWZ5ADIwMjItMDktMjJUMjI6MTY6MTcrMDA6MDCa4d/GAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAAAABJRU5ErkJggg=='
I tried to create a button by importing the base64 image from another file.
There are two buttons in the application, one works and the image appears, the other does not work and the image does not appear. I would like to make the second one work.
All the code will generate this image. The bottom button that doesn't show the image is in the widgets.py file
I don't know why, but when I import it, it doesn't work.
Thank you in advance for your attention and I apologize if something was wrong or out of standard, my English is not very good.
It is because there is no variable referencing the instance of Botoes(), so it will be garbage collected (so as the image inside it).
Just use a variable to store the instance of Botoes():
class Janela(Images):
def __init__(self) -> None:
self.images_base64()
self.tamJanela()
def tamJanela(self):
self.janela_doMenu = tk.Tk()
janela = self.janela_doMenu
# janela.state('zoomed')
janela.title('Disk Gás Gonçalves')
janela.configure(background=preto_claro)
janela.geometry("%dx%d" % (janela.winfo_screenwidth(), janela.winfo_screenheight()))
# Here the code works ###############################################################
self.img_icoName = tk.PhotoImage(data=base64.b64decode(self.editUser))
self.rotulo_nome2 = tk.Button(master=janela, image=self.img_icoName, activebackground='#00FA9A', bg='#4F4F4F',
highlightbackground='#4F4F4F', highlightcolor='#4F4F4F')
self.rotulo_nome2.grid(row=0, column=0)
# need a variable to store the instance of Botoes
# to avoid garbage collection
botoes = Botoes(janela)
janela.minsize(1200, 640)
janela.mainloop()
Result:
I would like to make a window construction for a photo previewer. I am stuck. My code doesn't work.
I made a frame hierarchy shown below.
I would like to show thumbnails in the thumbnail frame.
# TODO 0: IMPORT REQUIRED LIBRARIES AND MODULES
from tkinter import *
from PIL import Image, ImageTk
# TODO 1: CREATE A CLASS
class EditScreen:
def __init__(self, file_directory_list):
self.edit_window_init()
self.file_directory_list = file_directory_list
self.display_selected_images()
self.edit_window.mainloop()
# TODO 2: CREATE A NEW EDIT SCREEN
def edit_window_init(self):
self.edit_window = Toplevel()
self.edit_window.title("Edit")
self.edit_window.geometry('1200x800')
self.background_color = "#F8F1F1"
self.my_font_color = "#0A065D"
self.my_font = 'Poppins'
# TODO 3: DISPLAY SELECTED IMAGES IN THIS SCREEN
def display_selected_images(self):
thumbnail_frame = Frame(self.edit_window, height=1200, width=300)
thumbnail_frame.pack(side='left')
thumbnail_frame_canvas= Canvas(master=thumbnail_frame)
thumbnail_frame_canvas.place(x=0,y=0)
# TODO 3.1: PUT ALL SELECTED IMAGES THUMBNAIL TO LEFT HAND SIDE OF THE EDIT SCREEN
for selected_image_directory in self.file_directory_list:
print(self.file_directory_list.index(selected_image_directory))
selected_image = ImageTk.PhotoImage(file=selected_image_directory)
selected_image_location = thumbnail_frame_canvas.create_image((30,30),image=selected_image)
selected_image_location.pack()
#.grid(row=self.file_directory_list.index(selected_image_directory),column=0)
Consider these lines of code:
selected_image_location = thumbnail_frame_canvas.create_image((30,30),image=selected_image)
selected_image_location.pack()
create_image is documented to return an integer, which is an internal id of the canvas object that was created. You then try to call pack on that integer, but integers don't have a pack method. You need to remove the call to pack
Another problem was mentioned in a comment to your question: you're not saving a reference to the image, so it's going to get destroyed by python's garbage collector.
You can save a reference by using a global list, and appending the images to that list:
def display_selected_images(self):
global selected_images
...
selected_images = []
for selected_image_directory in self.file_directory_list:
...
selected_image = ImageTk.PhotoImage(file=selected_image_directory)
selected_images.append(selected_image)
...
I want to make a kind of chat box, and I would like the letters to be word by word, I did that function but it stays loading until the loop ends, and it gives me the final result, i see in other pages and questions, and i saw that the "after" funtion works, maybe i did something wrong when implementing it, sorry for my english
import tkinter as tk
from tkinter import ttk
import os
from PIL import ImageTk
import PIL.Image
# parent window where is an image of the chatbox
def Ventana_Text_Box(event):
#Ventana De Text box
global ventana_BT
ventana_BT = tk.Tk()
ventana_BT.geometry("300x300+"+str(200)+"+"+str(100))
ventana_BT.configure(background="gray")
I_Text_Box_Image = ImageTk.PhotoImage(I_Text_Box)
Box_Texto = tk.Label(ventana_BT, image = I_Text_Box_Image, bg="gray")
Box_Texto.pack()
Box_Texto.bind("<Button-1>", Ventana_Texto)
Box_Texto.bind("<Button-3>", escribir_texto)
#ventana_BT.wm_attributes("-topmost", 1)
ventana_BT.wm_attributes("-transparentcolor", "gray")
ventana_BT.overrideredirect(1)
ventana_BT.mainloop()
# window where the text will be
def Ventana_Texto(event):
# Ventana hija para el texto
global ventana_T
global W_texto
ventana_T = tk.Toplevel()
ventana_T.geometry("300x300+"+str(ventana_BT.winfo_rootx()-70)+"+"+str(ventana_BT.winfo_rooty()+140))
ventana_T.configure(background="gray")
W_texto = tk.Label(ventana_T, text="", bg="pink")
W_texto.config(fg="black", font=("Consola", 15))
W_texto.pack()
#escribir_texto("Hola")
#ventana_T.wm_attributes("-topmost", 1)
ventana_T.wm_attributes("-transparentcolor", "gray")
ventana_T.overrideredirect(1)
ventana_T.mainloop()
# Function that changes the text from letter to letter
def mecanografiar(texto):
for i in range(len(texto)+1):
return W_texto.config(text=texto[0:i])
# test function to see if it works write "HOLA"
def escribir_texto(event):
texto = "hola"
W_texto.after(400, mecanografiar(texto))
scriptpath = os.path.abspath(__file__)
scriptdir = os.path.dirname(scriptpath)
Text_Box = os.path.join(scriptdir, "Dialogo", "text_box.png")
#800x712
I_Text_Box = PIL.Image.open(Text_Box)
W_I = 350
H_I = W_I*712/800
I_Text_Box = I_Text_Box.resize((W_I,int(H_I)), PIL.Image.ANTIALIAS)
if __name__ == "__main__":
Ventana_Text_Box(None)
import tkinter as tk
root = tk.Tk()
root.geometry('200x200')
# this is whatever string you want to type out slowly
chat_str = 'Hello, friend!'
# storing text in a StringVar will update the label automatically
# whenever the value of the variable is changed (see 'textvariable' below)
text_var = tk.StringVar()
label = tk.Label(textvariable=text_var)
label.pack()
# index represents the character index in 'chat_str'
index = 0
# we need an empty string to store the typed out string as it updates
placeholder = ''
def type_text():
# use 'global' to allow the function to access these variables
global index
global placeholder
try:
# concat the placeholder with the next character in 'chat_str'
placeholder += chat_str[index]
# set 'text_var' to update the label automatically
text_var.set(placeholder)
# go to the next index (character) in 'chat_str'
index += 1
# call this function again after 150mS
# (change this number to modify the typing speed)
root.after(150, type_text)
except IndexError: # when you run out of characters...
return # bail
# NOTE:
# using a 'try:except' block above avoids issues stopping 'root.after()'
type_text()
root.mainloop()
I'm trying to use data from a csv file ( https://www.kaggle.com/jingbinxu/sample-of-car-data ). I only need the horsepower and weight columns as variables for the equation: ( 1/4 mile et = 6.290 * (weight/hp) ** .33 ), but it won't apply it. I don't know if the storage is working or I shouldn't do it as a class. When I run the program it doesn't show any errors, but it doesn't show results either. Then I got to plot the results, but I don't think it's even calculating and storing results. Any help is appreciated. Thanks in advance.
Here's the current code i have:
import numpy as np
class car_race_analysis():
def __init__(self, filename):
import numpy as np
self.data = np.genfromtxt(filename,delimiter= ',', skip_header = 1 )
def race_stats(self,w,h):
#cars in data
cars = np.unique(self.data[:,0])
#storage for output
race_times = []
#for each car
for car in cars:
#mask
mask = self.data[:,0] == car
#get data
w = self.data[mask,12]
h = self.data[mask,18]
#apply formula
qrtr_mile = 6.290 * ( w / h ) ** .33
race_times.append(qrtr_mile)
#new atribute
self.race_times = np.array(race_times)
print(race_times)
def trend_plotter(self):
import matlib.pyplot as plt
#inputs
self.race_stats
cars = np.unique(self.data[:,0])
#plot
plt.plot(cars,self.race_times)
plt.xlabel("Car")
plt.ylabel("1/4 Mile Time")
plt.savefig("trend_plot.png")
filename = 'car_data.csv'
Two problems:
I think you meant matplotlib instead of matlib. Make sure you install it pip3 install matplotlib --user and edit your code accordingly.
Your previous code wasn't working because you weren't instantiating a class or running any methods. The only "work" your program did was to define the class and then set a filename variable.
To solve #2, replace your filename=... line with the code below.
Here's what it does:
It checks to see if the file is being run directly (i.e. from command prompt such as python3 <your_file_name>.py. If this class is being imported and used from a different python file, this code would not be executed. More reading: https://www.geeksforgeeks.org/what-does-the-if-name-main-do/
We instantiate a instance of your class and supply the filename variable since that it was your class' __init__ method expects.
We invoke the trend_plotter method on the instance of the class.
if __name__ == '__main__':
filename = 'car_data.csv'
car_analysis = car_race_analysis(filename)
car_analysis.trend_plotter()
Even with those changes, your program will not work because it has other errors. I made a guess at fixing it, which I've pasted below, but I strongly encourage you do diff my changes to understand what I altered to be sure it does what you want.
import numpy as np
import matplotlib.pyplot as plt
class car_race_analysis():
race_times = []
cars = []
def __init__(self, filename):
import numpy as np
self.data = np.genfromtxt(filename, delimiter=',', skip_header=1)
def race_stats(self, w, h):
#cars in data
self.cars = np.unique(self.data[:, 0])
# storage for output
self.race_times = []
# for each car
for car in self.cars:
# mask
mask = self.data[:, 0] == car
# get data
w = self.data[mask, 12]
h = self.data[mask, 18]
# apply formula
qrtr_mile = 6.290 * (w / h) ** .33
self.race_times.append(qrtr_mile)
# new atribute
self.race_times = np.array(self.race_times)
def trend_plotter(self):
# inputs
self.race_stats(len(self.cars), len(self.race_times))
# plot
plt.plot(self.cars, self.race_times)
plt.xlabel("Car")
plt.ylabel("1/4 Mile Time")
plt.savefig("trend_plot.png")
plt.show()
if __name__ == '__main__':
filename = 'car_data.csv'
car_analysis = car_race_analysis(filename)
car_analysis.trend_plotter()
First of All, I have to say that I am a beginner in Python, so my code might appears redundant or muddled.
I made this code which consists of two classes that are both tkinter frame. The class ExportGUI inherits from Hdf5GUI and is called by the function export. The thing is I am trying to access the parent variable datasetsfilter through a child function but it doesnt work :
# Parent class
class Hdf5GUI(GUI):
def __init__(self,hdf5w,master):
# Frame definition
self.master = master # parent root
self.hdf5w = hdf5w #root
self.hdf5w.title('Hdf5 Reader')
self.hdf5w.rowconfigure(0,weight=1)
self.hdf5w.columnconfigure(0,weight=1)
self.hdf5w.columnconfigure(1,weight=1)
self.frameDataset = Frame(self.hdf5w,padx=5,pady=5)
self.frameDataset.grid(row=0,column=0,sticky='wesn')
self.frameDataset.rowconfigure(1,weight=1)
self.frameDataset.columnconfigure(0,weight=1)
self.datasetpath_button = Button(self.frameDataset,text="Export dataset path",command = self.exportDatasetPath)
self.datasetpath_button.grid(row=0,column=0,columnspan=2,pady=5,sticky='nwe')
self.dataset_scrollbar = Scrollbar(self.frameDataset)
self.dataset_scrollbar.grid(row=1,column=1,sticky='esn')
self.dataset_listbox = Listbox(self.frameDataset,exportselection=0)
self.dataset_listbox.grid(row=1,column=0,sticky='wesn')
self.dataset_listbox.bind('<<ListboxSelect>>', self.onSelectDataset)
self.dataset_listbox.config(yscrollcommand=self.dataset_scrollbar.set)
self.dataset_scrollbar.config(command=self.dataset_listbox.yview)
self.datatype_scrollbar = Scrollbar(self.frameDataset)
self.datatype_scrollbar.grid(row=2,column=1,sticky='esn')
self.datatype_listbox = Listbox(self.frameDataset,selectmode='extended',exportselection=0)
self.datatype_listbox.grid(row=2,column=0,sticky='wesn')
# self.dataset_listbox.bind('<<ListboxSelect>>', self.onSelectDataset)
#
self.datatype_listbox.config(yscrollcommand=self.datatype_scrollbar.set)
self.datatype_scrollbar.config(command=self.datatype_listbox.yview)
self.frameFilter = Frame(self.frameDataset)
self.frameFilter.grid(row=3,column=0,sticky='wen')
self.frameFilter.columnconfigure(0,weight=1)
self.frameFilter.columnconfigure(1,weight=1)
self.frameFilter.columnconfigure(2,weight=1)
self.frameFilter.columnconfigure(3,weight=1)
self.filter_label = Label(self.frameFilter,text="Dataset filter")
self.filter_label.grid(row=0,column=0,columnspan=4,sticky='wen')
self.filter0 = Listbox(self.frameFilter,exportselection=0)
self.filter0.grid(row=1,column=0,sticky='wen')
self.filter0.bind('<<ListboxSelect>>', self.onSelectFilter0)
self.filter1 = Listbox(self.frameFilter,exportselection=0)
self.filter1.grid(row=1,column=1,sticky='wen')
self.filter1.bind('<<ListboxSelect>>', self.onSelectFilter1)
self.filter2 = Listbox(self.frameFilter,exportselection=0)
self.filter2.grid(row=1,column=2,sticky='wen')
self.filter2.bind('<<ListboxSelect>>', self.onSelectFilter2)
self.filter3 = Listbox(self.frameFilter,exportselection=0)
self.filter3.grid(row=1,column=3,sticky='wen')
self.frameFile = Frame(self.hdf5w,padx=5,pady=5)
self.frameFile.grid(row=0,column=1,sticky='wesn')
self.frameFile.rowconfigure(1,weight=1)
self.frameFile.columnconfigure(0,weight=1)
self.folderPath_button = Button(self.frameFile,text="Open files in directory",command=self.exportFiles)
self.folderPath_button.grid(row=0,column=0,columnspan=2,pady=5,sticky='wen')
self.files_listbox = Listbox(self.frameFile,selectmode='extended',exportselection=0)
self.files_listbox.grid(row=1,column=0,sticky='wesn')
self.files_scrollbar = Scrollbar(self.frameFile)
self.files_scrollbar.grid(row=1,column=1,sticky='esn')
self.files_listbox.config(yscrollcommand=self.files_scrollbar.set)
self.files_scrollbar.config(command=self.files_listbox.yview)
self.displayData_button = Button(self.frameFile, text="display dataset", command=self.displayData)
self.displayData_button.grid(row=2,column=0,columnspan=2,padx=10,pady=5,sticky='wen')
self.displayTxt_button = Button(self.frameFile, text="Export", command=self.export)
self.displayTxt_button.grid(row=2,column=1,columnspan=2,padx=10,pady=5,sticky='wen')
# self.lblFrame = LabelFrame()
self.hdf5w.protocol("WM_DELETE_WINDOW", self.onClosing)
self.hdf5w.mainloop()
def exportDatasetPath(self):
self.dataset_listbox.delete(0,'end')
self.filter0.delete(0,'end')
self.filter1.delete(0,'end')
self.filter2.delete(0,'end')
self.filter3.delete(0,'end')
self.ohdf5 = Hdf5()
print(self.ohdf5.loadcase_label_list)
i = 0
for dataset in self.ohdf5.datasets:
self.dataset_listbox.insert(i,dataset)
i+=1
i = 0
for item in self.ohdf5.filter0:
self.filter0.insert(i,item)
i+=1
def onSelectDataset(self,evt):
self.datatype_listbox.delete(0,'end')
index = self.dataset_listbox.curselection()[0]
datasetPath = self.dataset_listbox.get(index)
self.odataset = self.ohdf5.getDataset(datasetPath)
i=0
for col in self.odataset.columns:
self.datatype_listbox.insert(i,col)
i+=1
def onSelectFilter0(self,evt):
self.dataset_listbox.delete(0,'end')
self.filter1.delete(0,'end')
self.filter2.delete(0,'end')
self.filter3.delete(0,'end')
index = self.filter0.curselection()[0]
item0 = self.filter0.get(index)
if item0 == 'NASTRAN':
i = 0
for dataset in self.ohdf5.datasets:
self.dataset_listbox.insert(i,dataset)
i+=1
else:
self.ohdf5.setFilterGroupPath(item0)
self.ohdf5.setFilterGroup(self.ohdf5.filterGroupPath)
i = 0
self.datasetsfilter = self.ohdf5.getDatasets(self.ohdf5.filterGroupPath)
for dataset in self.datasetsfilter:
self.dataset_listbox.insert(i,dataset)
i+=1
i = 0
for item in self.ohdf5.filter1:
self.filter1.insert(i,item)
i+=1
def onSelectFilter1(self,evt):
self.dataset_listbox.delete(0,'end')
self.filter2.delete(0,'end')
self.filter3.delete(0,'end')
index = self.filter0.curselection()[0]
item0 = self.filter0.get(index)
index = self.filter1.curselection()[0]
item1 = self.filter1.get(index)
self.ohdf5.setFilterGroupPath(item0,item1)
self.ohdf5.setFilterGroup(self.ohdf5.filterGroupPath)
i = 0
self.datasetsfilter = self.ohdf5.getDatasets(self.ohdf5.filterGroupPath)
print(self.datasetsfilter)
for dataset in self.datasetsfilter:
self.dataset_listbox.insert(i,dataset)
i+=1
i = 0
for item in self.ohdf5.filter2:
self.filter2.insert(i,item)
i+=1
def onSelectFilter2(self,evt):
self.dataset_listbox.delete(0,'end')
self.filter3.delete(0,'end')
index = self.filter0.curselection()[0]
item0 = self.filter0.get(index)
index = self.filter1.curselection()[0]
item1 = self.filter1.get(index)
index = self.filter2.curselection()[0]
item2 = self.filter2.get(index)
self.ohdf5.setFilterGroupPath(item0,item1,item2)
self.ohdf5.setFilterGroup(self.ohdf5.filterGroupPath)
i = 0
self.datasetsfilter = self.ohdf5.getDatasets(self.ohdf5.filterGroupPath)
print(self.datasetsfilter)
for dataset in self.datasetsfilter:
self.dataset_listbox.insert(i,dataset)
i+=1
i = 0
for item in self.ohdf5.filter3:
self.filter3.insert(i,item)
i+=1
def exportFiles(self):
self.files_listbox.delete(0,'end')
title = 'Choose the working HDF5 directory where there are *.h5 files :'
Tk().withdraw()
dirname_root = askdirectory(initialdir=os.getcwd(), title = title)
self.filePath_list = []
for folders, subfolders,files in os.walk(dirname_root):
for f in files:
ext = os.path.splitext(f)[1]
if ext == '.h5': self.filePath_list.append(os.path.join(folders,f))
i = 0
for path in self.filePath_list:
self.files_listbox.insert(i,os.path.basename(path))
i+=1
def onClosing(self):
# if tkMessageBox.askokcancel("Quit", "Do you want to quit?"):
self.hdf5w.destroy()
self.show(self.master)
def displayData(self):
print('function dislaying datas')
datas = self.datatype_listbox.curselection()
print(datas)
new_window = Toplevel(self.frameFile)
w = DisplayDataGUI(new_window, self.odataset, datas)
def get_datasetsfilter(self):
return self.datasetsfilter
def export(self):
new_window2 = Toplevel(self.frameFile)
w = ExportGUI(self.hdf5w,new_window2)
So until now my code perfectly works but I had to complete my program with some other functions that I call in ExportGUI. For example export_filter.
#==============================================================================
# Child class
#==============================================================================
class ExportGUI(Hdf5GUI):
def __init__(self,hdf5w, master):
self.master = master
self.master.title("Export")
self.master.geometry('200x200')
label = Label(self.master, text="Choose the kind of export")
label.place(x=20, y=0)
export_selected = Button(self.master, text = 'Export filters',command=self.export_filter)
export_selected.place(x=20, y=50)
self.master.mainloop()
def export_filter(self):
print(self.ohdf5.datatsetsfilter)
But I got the following error :
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\ProgramData\Anaconda2\lib\lib-tk\Tkinter.py", line 1542, in __call__
return self.func(*args)
File "GUI\GUI.py", line 397, in export_filter
print(self.ohdf5.datatsetsfilter)
AttributeError: 'ExportGUI' object has no attribute 'ohdf5'
Neither ohdf5 or datatsetsfilter is known by ExportGUI(I had the same error with self.datatsetsfilter).
Considering this code didnt work I tried to use the super function. I created a function get_datasetsfilter in Hdf5GUI :
def get_datasetsfilter(self):
return self.datasetsfilter
and then called it in ExportGUI (I added __metaclass__ = type to fix type prblm in 2.7) :
def export_filter(self):
super(ExportGUI, self).get_datasetsfilter
I admit I saw many other exemple with Super but they all seems to be used in __init__ method. However, it still doesnt work. I am now wondering if the error results from my bad comprehension of inheritance or tkinter.
The problem is that you have overwritten the __init__ method from the parent class. Usually what you is first call the __init__ method from the parent class that can be accessed using the super(). So your code should be something like:
class ExportGUI(Parent_Class):
def __init__(self, hdf5w, master):
super().__init__(hdf5w, master)
self.master = master
self.master.title("Export")
self.master.geometry('200x200')
UPDATE:
Now that you've cleared certain details I can augment this answer. Notice that the __init__ call from the ExportGUI is now called with two passed arguments, namely hdf5w and master, the first one is needed to successfully call the __init__ from the parent class. Thus you need to change the code in the definiton of Parent_Class where you're creating an instance of ExportGUI, so that a proper value for hdf5w will be passed in -- my guess would be, you want to pass the value from the parent class:
def export(self):
new_window2 = Toplevel(self.frameFile)
w = ExportGUI(self.hdf5w, new_window2)
And I can't help but notice, that the arguments passed to Parent_Class.__init__ namely hdf5w and master are not used anywhere. Maybe you want to either save those in variables, for example:
class Parent_Class(GUI):
def __init__(self,hdf5w,master):
self.hdf5w = hdf5w
self.master = master
If those are the same and should be carried across to the ExportGUI they can be simply passed when you're creating an instance in the export function of the Parent_Class. If you don't need them and decide to remove them, make sure to modify the __init__ call of the Parent_Class as well as the super().__init__ call in the ExportGUI.