使用tkinter在画布中移动矩形时出错

时间:2016-01-23 16:43:56

标签: python canvas tkinter

我制作一个正方形并让它移动但当我退出时会带来错误。我究竟做错了什么?感谢

这是我的代码:

from tkinter import *
import time


root = Tk()

canvas = Canvas(root, height=500, width=500)
canvas.pack()

a = canvas.create_rectangle(10, 10, 50, 50)


for i in range(0, 60):
    canvas.move(a,5,0)
    root.update()
    time.sleep(0.1)


root.mainloop()

这是我的错误:

Traceback (most recent call last):
  File "C:\Users\Owner\Documents\Brad\Test.py", line 17, in <module>
    canvas.move(a,5,0)
  File "C:\Python34\lib\tkinter\__init__.py", line 2434, in move
    self.tk.call((self._w, 'move') + args)
_tkinter.TclError: invalid command name ".57748176"

1 个答案:

答案 0 :(得分:1)

有许多例子如何使用after重复运行。

after是比for循环和sleep更好的解决方案 - 它是tkinter的一部分。

after将时间和函数名称添加到特殊列表中,mainloop将调用此函数。

from tkinter import *

# --- functions ---

def move_rectangle():

    # move rectangle 
    canvas.move(a,5,0)

    # run `move_rectangle` again after 100ms (0.1s)
    root.after(100, move_rectangle) # function name without ()

# --- main ----

root = Tk()

canvas = Canvas(root, height=500, width=500)
canvas.pack()

a = canvas.create_rectangle(10, 10, 50, 50)

# run `move_rectangle` first time after 100ms (0.1s)
root.after(100, move_rectangle) # function name without ()
#move_rectangle() # or run first time immediately

# "start the engine"
root.mainloop()

-

btw:如果您需要运行长时间运行的功能,那么您将需要线程。

相关问题