Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python, change the attributes of a class instance which is passed as input to __init__

Tags:

python

tkinter

Consider the following code, which generates a (basic) GUI:

import Tkinter as tk

class Game:
    def __init__(self, root):
        self.root = root
        button = tk.Button(root, text="I am a button")
        button.pack()

root = tk.Tk()
root.title("This is a game window")     # I would like to move this code to the Game class
game = Game(root)
root.mainloop()

The resulting GUI looks like this:

enter image description here

I'd like to achieve the same effect but move the setting of the window title to the class definition. (I've tried self.root.title = "This is a game window" in the __init__ but this seemed to have no effect). Is this possible?

like image 880
Kurt Peek Avatar asked Mar 11 '23 10:03

Kurt Peek


1 Answers

Sure. You need to call the .title method. Doing

root.title = "This is a game window" 

doesn't set the title, it overwrites the method with the string.

import Tkinter as tk

class Game:
    def __init__(self, root):
        self.root = root
        root.title("This is a game window")

        button = tk.Button(root, text="I am a button")
        button.pack()

root = tk.Tk()
game = Game(root)
root.mainloop()

You could also do self.root.title("This is a game window") but it's more typing, and using self.root is slightly less efficient than using the root parameter that was passed to the __init__ method, since self.root requires an attribute lookup but root is a simple local variable.

like image 148
PM 2Ring Avatar answered Apr 28 '23 10:04

PM 2Ring