繁体   English   中英

在Python中,更改作为输入传递给__init__的类实例的属性

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM