尝试在 tkinter 中进行简单的移动:
import tkinter as tk
class GameApp(object):
"""
An object for the game window.
Attributes:
master: Main window tied to the application
canvas: The canvas of this window
"""
def __init__(self, master):
"""
Initialize the window and canvas of the game.
"""
self.master = master
self.master.title = "Game"
self.master.geometry('{}x{}'.format(500, 500))
self.canvas = tk.Canvas(self.master)
self.canvas.pack(side="top", fill="both", expand=True)
self.start_game()
#----------------------------------------------#
def start_game(self):
"""
Actual loading of the game.
"""
player = Player(self)
#----------------------------------------------#
#----------------------------------------------#
class Player(object):
"""
The player of the game.
Attributes:
color: color of sprite (string)
dimensions: dimensions of the sprite (array)
canvas: the canvas of this sprite (object)
window: the actual game window object (object)
momentum: how fast the object is moving (array)
"""
def __init__(self, window):
self.color = ""
self.dimensions = [225, 225, 275, 275]
self.window = window
self.properties()
#----------------------------------------------#
def properties(self):
"""
Establish the properties of the player.
"""
self.color = "blue"
self.momentum = [5, 0]
self.draw()
self.mom_calc()
#----------------------------------------------#
def draw(self):
"""
Draw the sprite.
"""
self.sprite = self.window.canvas.create_rectangle(*self.dimensions, fill=self.color, outline=self.color)
#----------------------------------------------#
def mom_calc(self):
"""
Calculate the actual momentum of the thing
"""
self.window.canvas.move(self.sprite, *self.momentum)
self.window.master.after(2, self.mom_calc)
#----------------------------------------------#
#----------------------------------------------#
root = tk.Tk()
game_window = GameApp(root)
Where self.momentum
是一个包含 2 个整数的数组:一个用于 x 运动,另一个用于 y 运动。然而,矩形的实际移动速度非常慢(大约每秒 5 次移动),self.window.master.after()
时间似乎没有影响。
之前在另一个 tkinter 项目中,我已经成功地获得了真正响应式的 tkinter 运动,所以我只是想知道是否有一种方法可以在这种情况下最大限度地减少运动更新时间,通过使用不同风格的 OOP,或者只是不同的代码共。
更新:结果是时间.after()
方法确实很重要,并且它实际上叠加到方法的实时上。使用后timeit
调用该方法时,我得到以下输出:
>>> print(timeit.timeit("(self.window.master.after(2, self.mom_calc))", number=10000, globals={"self":self}))
0.5395521819053108
所以我想真正的问题是:为什么会这样.after()
方法需要这么长时间?
更新 2:在多台计算机上进行测试,在任何平台上移动仍然很慢。