Home>

import tkinter

key = ""
def key_down (e):
global key
key = e.keysym
def key_up (e):
global key
key = ""

mx = 1
my = 1
def main_proc ():
global mx, my
if key == "Up" and maze [my-1] [mx] == 0:
my = my --1
if key == "Down" and maze [my + 1] [mx] == 0:
my = my + 1
if key == "Left" and maze [my] [mx-1] == 0:
mx = mx --1
if key == "Right" and maze [my] [mx + 1] == 0:
mx = mx + 1
canvas.coords ("MYCHR", mx * 80 + 40, my * 80 + 40)
root.after (300, main_proc)

root = tkinter.Tk ()
root.title ("Move in the maze")
root.bind ("", key_down)
root.bind ("", key_up)
canvas = tkinter.Canvas (width = 800, height = 560, bg = "white")
canvas.pack ()

maze = [
[1,1,1,1,1,1,1,1,1,1],
[1,0,0,0,0,0,1,0,0,1],
[1,0,1,1,0,0,1,0,0,1],
[1,0,0,1,0,0,0,0,0,1],
[1,0,0,1,1,1,1,1,0,1],
[1,0,0,0,0,0,0,0,0,1],
[1,1,1,1,1,1,1,1,1,1]
]
for y in range (7):
for x in range (10):
if maze [y] [x] == 1:
canvas.create_rectangle (x * 80, y * 80, x * 80 + 79, y * 80 + 79, fill = "skyblue", width = 0)

img = tkinter.PhotoImage (file = "mimi_s.png")
canvas.create_image (mx * 80 + 40, my * 80 + 40, image = img, tag = "MYCHR")
main_proc ()
root.mainloop ()

What are the roles of tag = "MYCHR" and canvas.coords ("MYCHR", mx * 80 + 40, my * 80 + 40)?
Where did the MYCHR with tag = "MYCHR" come from?
I'm studying with books, but I don't understand, so please.

  • Answer # 1

    The method of pasting the source is different and it is difficult to read, but the answer is as the link shown by 1T2R3M4 in the question column.

    The coords () function moves the position of the item specified by the argument to the location of the specified foods. item is specified by id or tag.

    The create_image () function creates an image and returns an id. Also, the "name" specified by the argument tag is attached to the image.

    So, for the image to be moved by coords, you can specify the id that is set when you make it, but if it is troublesome to carry around the body, an appropriate name (in this case "MY CHR") It means that you can also add and use it.