如何在画布Tkinter上移动按钮?

时间:2018-09-05 11:00:00

标签: python user-interface tkinter

嗨,我希望能够在屏幕上移动一个带有按钮的灯泡。我试图使按钮将灯泡从白色更改为黄色,以使其看起来像已打开或关闭。我的程序只是将灯泡添加到画布上,但是您不能移动它或更改颜色而不会出现错误。我还想在画布上添加多个灯泡,灯泡可以自行移动。

from tkinter import *

root=Tk()
root.grid()

canvas=Canvas(root,height=600,width=600)
canvas.grid()

input_id=0

def addInputs():
   global input_id
   input_id+=1
   input_tag="input-%s"%input_id
   tags=("input",input_tag)
   canvas.create_oval(200,200,250,250,fill="WHITE",width=5,tag=tags)
   canvas.create_rectangle(210,245,237,275,fill="LIGHTGREY",width=5,tag=tags)
   onBtn=Button(root,text="On/Off",command=lambda:inputStatusOn())
   onBtn.place(x=200,y=212)
   canvas.tag_bind(input_tag,onBtn,"<B1-Motion>", lambda event,tag=input_tag:moveInput(event,tag,onBtn))

def inputStatusOn():
   global input_id
   input_id+=1
   input_tag="input-%s"%input_id
   tags=("input",input_tag)
   canvas.delete("input")
   canvas.create_oval(200,200,250,250,fill="YELLOW",width=5,tag=tags)
   canvas.create_rectangle(210,245,237,275,fill="LIGHTGREY",width=5,tag=tags)
   onBtn=Button(root,text="On/Off",command=lambda:inputStatusOff(),tag=tags)
   onBtn.place(x=200,y=212)
   canvas.tag_bind(input_tag,onBtn,"<B1-Motion>", lambda event,tag=input_tag:moveInput(event,tag,onBtn))

def inputStatusOff():
   global input_id
   input_id+=1
   input_tag="input-%s"%input_id
   tags=("input",input_tag)
   canvas.delete("input")
   canvas.create_oval(200,200,250,250,fill="WHITE",width=5,tag=tags)
   canvas.create_rectangle(210,245,237,275,fill="LIGHTGREY",width=5,tag=tags)
   onBtn=Button(root,text="On/Off",command=lambda:inputStatusOn(),tag=tags)
   onBtn.place(x=200,y=212)
   canvas.tag_bind(input_tag,onBtn,"<B1-Motion>", lambda event,tag=input_tag:moveInput(event,tag,onBtn))




def moveInput(event, tag,onBtn):
   x=event.x
   y=event.y
   coords=canvas.coords(tag,onBtn)
   movex=x-coords[0]
   movey=y-coords[1]
   canvas.move(tag,onBtn, movex, movey)

btn=Button(root,text="Add Input",command=lambda:addInputs())
btn.place(x=100,y=100)

0 个答案:

没有答案