Python Forum
[Tkinter] How to canvas.move images (png)
Thread Rating:
  • 1 Vote(s) - 4 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tkinter] How to canvas.move images (png)
#1
Im trying to get my sprte imported from a folder moving, I tried using 

 def move_Knight(self, event):
        if event.keysym == "Up":
            canvas.move(self.Knight1, 0, -self.Knight1_Speed)
        elif event.keysym == "Down":
            canvas.move(self.Knight1, 0, self.Knight1_Speed)
        elif event.keysym == "Left":
            canvas.move(self.Knight1, -self.Knight1_Speed, 0)
        elif event.keysym == "Right":
            canvas.move(self.Knight1, self.Knight1_Speed, 0)
however this doesn't seem to work ... it works for objects such as canvas.create_oval, no errors just my image is locked in place.

pls help me <3

Moderator Larz60+: Added code tags -- see: https://python-forum.io/misc.php?action=help&hid=25
Reply
#2
Hi Rainblade

Please try out the following skript:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from functools import partial

try:
    # Tkinter for Python 2.xx
    import Tkinter as tk
except ImportError:
    # Tkinter for Python 3.xx
    import tkinter as tk

APP_TITLE = "Move Image (png)"
APP_XPOS = 100
APP_YPOS = 100
APP_WIDTH = 300
APP_HEIGHT = 200


class Application(tk.Frame):

    def __init__(self, master):
        self.master = master
        tk.Frame.__init__(self, master)
        
        self.master.bind('<KeyPress>', self.move_Knight)
        
        self.canvas = tk.Canvas(self, bg='steelblue', highlightthickness=0)
        self.canvas.pack()
        
        self.knight1_speed = 2
        
        self.image = tk.PhotoImage(file='my_image.png')
        self.canvas.create_image(10, 10, anchor='nw', image=self.image,
            tags='my_image') 

    def move_Knight(self, event):
        print(event.keysym)
        if event.keysym == "Up":
            self.canvas.move('my_image', 0, -self.knight1_speed)
        elif event.keysym == "Down":
            self.canvas.move('my_image', 0, self.knight1_speed)
        elif event.keysym == "Left":
            self.canvas.move('my_image', -self.knight1_speed, 0)
        elif event.keysym == "Right":
            self.canvas.move('my_image', self.knight1_speed, 0)
                       
def main():
    app_win = tk.Tk()
    app_win.title(APP_TITLE)
    app_win.geometry("+{}+{}".format(APP_XPOS, APP_YPOS))
    app_win.geometry("{}x{}".format(APP_WIDTH, APP_HEIGHT))
    
    app = Application(app_win).pack(fill='both', expand=True)
    
    app_win.mainloop()
 
 
if __name__ == '__main__':
    main()
   

wuf Wink
Reply
#3
Wow thanks dude you're awesome !!!!!!!!!!!!!!!!!!!!!!!!!!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tkinter] Resizing image inside Canvas (with Canvas' resize) Gupi 2 25,026 Jun-04-2019, 05:05 AM
Last Post: Gupi

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020