简体   繁体   中英

Python tkinter creating object on canvas

I'm new to python and trying to design a GUI for a simulator using tkinter.

My issue is that I need to create an object image onto a canvas from clicking of a button and must be able to drag around the canvas area.

However, currently I am only able to create an image onto the canvas and unable to drag

Here is my partial codes:

from tkinter import *
def show_train():
     canvas.create_image(30,30, image=image1)
root = Tk()
canvas = Canvas(iframe5, height=600, width=520, bg="white")
image1 = PhotoImage(file='train.png')
b1=Button(frame,justify=LEFT)
b1.config(image=image1,width="80",height="80", command=show_train)
b1.pack(side=LEFT)
b1.place(x=0, y=12)
canvas.pack(side=RIGHT, expand=True)
root.mainloop()

any kind soul? Thanks in advance

Solve my own problem, this piece of code works for now.

class CreateCanvasObject(object):
    def __init__(self, canvas, image_name, xpos, ypos):
        self.canvas = canvas
        self.image_name = image_name
        self.xpos, self.ypos = xpos, ypos
        self.tk_image = tk.PhotoImage(file="{}{}".format(IMAGE_PATH, image_name))
        self.image_obj= canvas.create_image(xpos, ypos, image=self.tk_image)
        canvas.tag_bind(self.image_obj, '<Button1-Motion>', self.move)
        canvas.tag_bind(self.image_obj, '<ButtonRelease-1>', self.release)
        self.move_flag = False

    def move(self, event):
        if self.move_flag:
            new_xpos, new_ypos = event.x, event.y
            self.canvas.move(self.image_obj, new_xpos-self.mouse_xpos ,new_ypos-self.mouse_ypos)
            self.mouse_xpos = new_xpos
            self.mouse_ypos = new_ypos
        else:
            self.move_flag = True
            self.canvas.tag_raise(self.image_obj)
            self.mouse_xpos = event.x
            self.mouse_ypos = event.y

    def release(self, event):
        self.move_flag = False

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM