Python Tkinter在画布上创建对象 [英] Python tkinter creating object on canvas
本文介绍了Python Tkinter在画布上创建对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是python的新手,正在尝试使用tkinter为模拟器设计GUI.
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
这是我的部分代码:
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
这篇关于Python Tkinter在画布上创建对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文