在Python中,更改作为输入传递给_init的类实例的属性__
考虑以下生成(基本)GUI的代码: 生成的GUI如下所示:在Python中,更改作为输入传递给_init的类实例的属性__,python,tkinter,Python,Tkinter,考虑以下生成(基本)GUI的代码: 生成的GUI如下所示: 我希望达到相同的效果,但将窗口标题的设置移动到类定义中。(我在\uuu init\uuuu中尝试了self.root.title=“这是一个游戏窗口”,但似乎没有效果)。这可能吗?当然可以。您需要调用.title方法。做 root.title = "This is a game window" 不设置标题,它将用字符串覆盖方法 import Tkinter as tk class Game: def __init__(s
我希望达到相同的效果,但将窗口标题的设置移动到类定义中。(我在
\uuu init\uuuu
中尝试了self.root.title=“这是一个游戏窗口”
,但似乎没有效果)。这可能吗?当然可以。您需要调用.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(“这是一个游戏窗口”)
,但它需要更多的输入,使用self.root
比使用传递给\uuu init\uu
方法的root
参数效率稍低,因为self.root
需要属性查找,但是root
是一个简单的局部变量
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()