Home > Enterprise >  tkinter how to change attribute value of object using OOP?
tkinter how to change attribute value of object using OOP?

Time:02-08

How can I change an attribute on the object when the attribute is Frame? I want to change the color of the frame.

class MyFrame:
   def __init__(self, bg_color)
   self.window = tk.Frame(self.parent, bg=bg_color)

mainApp:
    frame_obj = MyFrame("blue")

    #want to change the color after the frame obj has been created
    frame_obj.window.bg = "red" #this does not work

CodePudding user response:

Tkinter is based on different progamming language, named tcl and thats why things seem a bit unpythonic here.

The tk.Frame object isnt a pure python object, rather its an wrapped object in a tcl interpreter and thats why you cant address the attributes you intuitivly think you can. You need to adress the attributes in a way the tcl interpreter is abel to handle and therefor methods are created like widget.configure.

To achive what you want with your current code, it would look like:

import tkinter as tk

root = tk.Tk()

class MyFrame():
    def __init__(self, bg_color):
        self.window = tk.Frame(width=500,height=500,bg=bg_color)

frame_obj = MyFrame('blue')
frame_obj.window.pack(fill=tk.BOTH)
frame_obj.window.configure(bg='yellow')

root.mainloop()

In addition, the proper way for an OOP approach for a frame would look like this:

class MyFrame(tk.Frame):
    def __init__(self,master,**kwargs):
        super().__init__(master)
        self.configure(**kwargs)

frame_obj = MyFrame(root,width=500,height=500,bg='green')
frame_obj.pack(fill=tk.BOTH)

This way your class becomes a child of the tk.Frame object and you can adress it directly. The syntax self in this context refers directly to the tk.Frame object. Also it is good practice to use the format of

def __init__(self,master,**kwargs):

while its the same for the parent/tk.Frame. It has a single positional argument, named master and keywords arguments for the configuration of the Frame.

Please take a look at a tutorial for tkinter and for OOP. If you had you would know that. Please dont feel offended, but StackOverflow requiers a brief reasearch and that includes to read documentation and take tutorials.

  •  Tags:  
  • Related