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

Consider the following code that 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 result of the GUI is as follows:

enter image description here

I would like to achieve the same effect, but move the window title setting to the class definition. (I tried self.root.title = "This is a game window"in __init__, but this did not seem to have an effect). Is it possible?

+4
source share
1 answer

Of course. You need to call a method .title. Performance

root.title = "This is a game window" 

does not 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()

self.root.title("This is a game window"), , self.root , root, __init__, self.root , root - .

+7

Source: https://habr.com/ru/post/1651416/


All Articles