简体   繁体   English

Python Tkinter在画布上创建对象

[英]Python tkinter creating object on canvas

I'm new to python and trying to design a GUI for a simulator using tkinter. 我是python的新手,正在尝试使用tkinter为模拟器设计GUI。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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