Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
Combobox Widget in tkinter | Python
Next article icon

TheCanvas class of Tkinter supports functions that are used to move objects from one position to another in any canvas or Tkinter top-level.

Syntax: Canvas.move(canvas_object, x, y)
Parameters: 
canvas_object is any valid image or drawing created with the help of Canvas class. To know how to create object using Canvas class take reference of
this
x is horizontal distance from upper-left corner. 
y is vertical distance from upper-left corner.

We will use class to see the working of the move() method.

Class parameters-  

Data members used: 
master 


canvas 
rectangle
Member functions used: 
movement() 
left() 
right() 
up() 
down()
Widgets used: Canvas
Tkinter method used: 
Canvas.create_rectangle() 
pack() 
Canvas.move() 
after() 
bind() 
 

Below is the Python implementation:  

Python3
importtkinterastkclassMoveCanvas(tk.Canvas):def__init__(self,*args,**kwargs):super().__init__(*args,**kwargs)self.dx=0self.dy=0self.box=self.create_rectangle(0,0,10,10,fill="black")self.dt=25self.tick()deftick(self):self.move(self.box,self.dx,self.dy)self.after(self.dt,self.tick)defchange_heading(self,dx,dy):self.dx=dxself.dy=dyif__name__=="__main__":root=tk.Tk()root.geometry("300x300")cvs=MoveCanvas(root)cvs.pack(fill="both",expand=True)ds=3root.bind("<KeyPress-Left>",lambda_:cvs.change_heading(-ds,0))root.bind("<KeyPress-Right>",lambda_:cvs.change_heading(ds,0))root.bind("<KeyPress-Up>",lambda_:cvs.change_heading(0,-ds))root.bind("<KeyPress-Down>",lambda_:cvs.change_heading(0,ds))root.mainloop()

Output: 
 


Extra print statements are used in the above code to show the proper working of themove() method. keysymkeyword (Tkinter reserved) is used to print which keyboard key is pressed.
 


Improve

Similar Reads

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood ourCookie Policy &Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp