![](/img/trans.png)
[英]How to access to instance variable(which is not defined in "__init__") in class in python?
[英]In Python, change the attributes of a class instance which is passed as input to __init__
请考虑以下代码,该代码生成(基本)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()
生成的GUI如下所示:
我想实现相同的效果,但将窗口标题的设置移动到类定义。 (我在__init__
尝试过self.root.title = "This is a game window"
,但这似乎没有效果)。 这可能吗?
当然。 您需要调用.title
方法。 干
root.title = "This is a game window"
没有设置标题,它用字符串覆盖方法。
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
效率略低于使用传递给__init__
方法的root
参数,因为self.root
需要属性查找但root
是一个简单的局部变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.