请考虑以下代码,该代码生成(基本)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()
Run Code Online (Sandbox Code Playgroud)
生成的GUI如下所示:
我想实现相同的效果,但将窗口标题的设置移动到类定义.(我试过self.root.title = "This is a game window"了,__init__但这似乎没有效果).这可能吗?
当然.你需要调用该.title方法.干
root.title = "This is a game window"
Run Code Online (Sandbox Code Playgroud)
没有设置标题,它用字符串覆盖方法.
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()
Run Code Online (Sandbox Code Playgroud)
您也可以这样做,self.root.title("This is a game window")但它更多的是打字,并且使用self.root效率略低于使用root传递给__init__方法的 参数,因为self.root需要属性查找但是root是一个简单的局部变量.
| 归档时间: |
|
| 查看次数: |
65 次 |
| 最近记录: |