2017-05-03 729 views
0

我收到以下錯誤:_tkinter.TclError:無效的命令名稱」 0.14574424"

_tkinter.TclError: invalid command name 「.14574424」

我無法理解的錯誤。我究竟做錯了什麼?

# Import tkinter 
from tkinter import * 

class AnimationDemo: 
    def __init__(self): 
     window = Tk()  # Create a window 
     window.title("Animation Demo")  # Set a title 

     width = 250   # Width of the canvas 
     canvas = Canvas(window, bg = "white", width = 250, height = 50) 
     canvas.pack() 

     x = 0   # Starting x position 
     canvas.create_text(x, 30, text = "Message moving?", tags = "text") 

     dx = 3 
     while True: 
      canvas.move("text", dx, 0)  # Move text dx unit 
      canvas.after(100)   # Sleep for 100 milliseconds 
      canvas.update()   # Update canvas 
      if x < width: 
       x += dx   # Get the current position for string 
      else: 
       x = 0  # Reset string position to the beginning 
       canvas.delete("text") 
       # Redraw text at the beginning 
       canvas.create_text(x, 30, text = "Message moving?", tags = "text") 
     window.mainloop()  # Create an event loop 

AnimationDemo()  # Create GUI 
+0

錯誤:回溯(最近通話最後一個): 文件「d :/sem4/t/lesson4/task1/task.py「,第29行,在 AnimationDemo()#創建GUI 文件」D:/sem4/t/lesson4/task1/task.py「,第17行,in __init__ canvas.move(「text」,dx,0)#移動文本dx單位 F (self._w,'move')+移動到第一行,然後移動到第一行, args) _tkinter.TclError:無效的命令名稱「.14440096」 – hss

+0

你在做什麼導致錯誤?順便說一句,這是用Tkinter做動畫的錯誤方法。見http://stackoverflow.com/a/11505034/7432 –

+0

謝謝@BryanOakley,但我可以知道爲什麼它顯示錯誤,如果我們使用while循環 – hss

回答

0

正如布萊恩提到的,而不是使用while循環,嘗試將您的文字直接與.after()方法動畫:

import tkinter as tk 

class AnimationDemo: 
    def __init__(self): 
     self.window = tk.Tk() 
     self.window.title("Animation Demo") 

     # Create a canvas 
     self.width = 250 
     self.canvas = tk.Canvas(self.window, bg="white", width=self.width, 
          height=50) 
     self.canvas.pack() 

     # Create a text on the canvas 
     self.x = 0 
     self.canvas.create_text(self.x, 30, text = "Message moving?", tags="text") 
     self.dx = 3 

     # Start animation & launch GUI 
     self.animate_text() 
     self.window.mainloop() 

    def animate_text(self): 
     # Move text dx unit 
     self.canvas.move("text", self.dx, 0) 
     if self.x < self.width: 
      # Get the current position for string 
      self.x += self.dx 
     else: 
      # Reset string position to the beginning 
      self.x = 0 
      self.canvas.delete("text") 
      self.canvas.create_text(self.x, 30, text = "Message moving?", tags="text") 
     self.window.after(100, self.animate_text) 

# Create GUI 
AnimationDemo() 
+1

謝謝你@Josselin它的工作 – hss