Skip to content Skip to sidebar Skip to footer

Trying To Make An Object Move In A Grid With Tkinter Through Player Inputs

So I'm developing a dungeon crawler like game in tkinter and not pygame. I'm finding it very difficult because the grid won't work within the code, and I can't find a way to create

Solution 1:

As Bryan said, you can use the move method of the canvas. Below is a simple example where the player is a red circle you can move around the canvas with the keyboard arrows. You can add additional keys to the move_player function to implement other actions in the game.

import tkinter as tk

class Game(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.can = tk.Canvas(self, width=200, height=200)
        self.can.pack(fill="both", expand=True)
        self.player = self.can.create_oval(50,50,70,70, fill="red")
        self.bind("<Key>", self.move_player)

    def move_player(self, event):
        key = event.keysym
        if key == "Left":
            self.can.move(self.player, -20, 0)        
        elif key == "Right":
            self.can.move(self.player, 20, 0)    
        elif key == "Up":
            self.can.move(self.player, 0, -20)        
        elif key == "Down":
            self.can.move(self.player, 0, 20) 

if __name__ == '__main__':
    game = Game()
    game.mainloop()

Post a Comment for "Trying To Make An Object Move In A Grid With Tkinter Through Player Inputs"