Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
77 views
in Technique[技术] by (71.8m points)

python - Tkinter after method not working as expected

I have not seen any post about this issue but sorry it there is one already.

I am coding a Space Invaders on Python in OOP (complete newbie in it).

I have an image in a canvas that I want to move with the keyboard arrows, so I bound a method on the Right Arrow press, which initiates a continuous movement on the right, and another when the key is released, which stops the movement.

I wanted the icon to move regularily as long as the key is held pressed so here is how I tried :

class Ship():
    def __init__(self,window,canvas):
        self.window = window
        self.canvas = canvas
        
        self.width = 55
        self.height = 58
        self.RIGHT = False
        
        self.image_ship = ImageTk.PhotoImage(file="../Images/ship.jpg")
        self.sprite_ship = self.canvas.create_image((self.canvas.winfo_width() - self.width)//2,(self.canvas.winfo_height() - self.height)-5,image = self.image_ship,anchor='nw')
    
    def press_right(self,event):
        self.RIGHT = True
        
        self.keep_right()
        
    def keep_right(self):
        if self.RIGHT == True:
            self.x = self.canvas.coords(self.sprite_ship)[0]
            self.y = self.canvas.coords(self.sprite_ship)[1]
            
            self.canvas.coords(self.sprite_ship,self.x+10,self.y)
            
            self.window.after(1000,self.keep_right)
            
    def stop_right(self,event):
        self.RIGHT = False

But the keep_right method is called about every 0.01 second instead of 1s.

Could someone say me why so ?

question from:https://stackoverflow.com/questions/65848778/tkinter-after-method-not-working-as-expected

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Problem solved :

I thought the command bound to KeyPress was only called on press, but it is aswell when hold. So the function press_right was called every few ms. Here is how to fix it :

def press_right(self,event):
    if self.RIGHT == False:
        self.RIGHT = True
        self.keep_right()

Instead of

def press_right(self,event):
    self.RIGHT = True
        
    self.keep_right()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...