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:
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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With