Skip to content
Advertisement

tkinter: How to create a class object with a function called by a Button?

I created an entry where I enter some value. By clicking the submit button I want the function create_object to get the entry value, then an object of the class Test_Class is created with the gotten value as a parameter and the object is returned.

But obviously that object has not yet been created and therefore cannot be accessed, right? How do I actually create a class object and then access it?

from tkinter import *

class Test_Class:
    def __init__(self, parameter ):
        self.parameter = parameter

root = Tk()

def create_object():
    parameter = entry.get()
    object = Test_Class(parameter)
    return object

entry = Entry(root, width=30)
entry.grid(row=0, column=0)

submit = Button(root, text="Submit", command=create_object)
submit.grid(row=1, column=0)

root.mainloop()

Advertisement

Answer

You could simply stop using procedural programming altogether, and then you don’t have to worry about scope issues. All I did was turn your code into classes and refactor it a little so you can test your write and read results.

Another simple change was: instead of worrying about things that may or may not exist, I simply created something that definitely exists to hold the aforementioned things, and you can just loop through that to find out what exists.

import tkinter as tk
from typing import *

class Test_Class:
    def __init__(self, parameter ):
        self.parameter = parameter
        
    def __str__(self):
        #allows us to call print on the entire class to print self.parameter value
        return self.parameter

#extend the root
class Root(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)            
        #you don't have to "strict type" this. I just did, cause I do
        self.param_objects:List[Test_Class] = []
        
        self.entry = tk.Entry(self, width=30)
        self.entry.grid(row=0, column=0, columnspan=2)
        
        #unless you intend for your script to modify or delete these buttons, there is no need for a reference
        tk.Button(self, text="Submit", command=self.create_pobjs).grid(row=1, column=0)
        tk.Button(self, text="Check", command=self.print_pobjs).grid(row=1, column=1)
        
    def create_pobjs(self):
        #create a new Test_Class instance
        self.param_objects.append(Test_Class(self.entry.get()))
        
    def print_pobjs(self):
        for param in self.param_objects:
            #call print on the entire Test_Class instance
            print(param)


if __name__ == "__main__":
    Root().mainloop()
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement