我有一个按钮,当按下该按钮时,该按钮会添加一个可移动的黄色圆圈和一个关闭开关。我希望用户关闭并在黄色圆圈上,当选中复选按钮时,它将把圆圈变成白色,而当选中按钮时,将把圆圈变成黄色。
from tkinter import *
root=Tk()
root.grid()
input_id=0
yco=212
canvas=Canvas(root,height=600,width=600)
canvas.grid()
def addInput():
global input_id
global yco
input_id+=1
yco+=50
input_tag="input-%s"%input_id
tags=("input",input_tag)
canvas.create_oval(200,200,225,225,fill="WHITE",width=5,tag=tags)
canvas.tag_bind(input_tag,"<B1-Motion>",lambda event,tag=input_tag:moveInput(event,tag))
def checkStatus(status):
if status.get()==0:
canvas.delete(tags)
canvas.create_oval(200,200,225,225,fill="YELLOW",width=5,tag=tags)
canvas.tag_bind(input_tag,"<B1-Motion>",lambda event,tag=input_tag:moveInput(event,tag))
else:
canvas.delete(tags)
canvas.create_oval(200,200,225,225,fill="WHITE",width=5,tag=tags)
canvas.tag_bind(input_tag,"<B1-Motion>",lambda event,tag=input_tag:moveInput(event,tag))
status=IntVar()
statusCkbtn=Checkbutton(canvas,text="Off",command=checkStatus(status),variable=status,bg="white")
statusCkbtn.var=status
statusCkbtn.place(x=200,y=yco)
def moveInput(event, tag):
x=event.x
y=event.y
coords=canvas.coords(tag)
movex=x-coords[0]
movey=y-coords[1]
canvas.move(tag, movex, movey)
btn=Button(canvas,text="Add Input",command=lambda:addInput())
btn.place(x=100,y=100)
root.mainloop()
答案 0 :(得分:0)
在这种情况下,最好使status
处于布尔状态。就是说,在试用了您的代码并更改了某些样式之后,我设法使其正常工作。
def checkStatus():
print(status.get())
if (not status.get()):
canvas.delete(tags)
canvas.create_oval(200,200,225,225,fill="YELLOW",width=5,tag=tags)
canvas.tag_bind(input_tag,"<B1-Motion>",lambda event,tag=input_tag:moveInput(event,tag))
else:
canvas.delete(tags)
canvas.create_oval(200,200,225,225,fill="WHITE",width=5,tag=tags)
canvas.tag_bind(input_tag,"<B1-Motion>",lambda event,tag=input_tag:moveInput(event,tag))
status = BooleanVar()
statusCkbtn=Checkbutton(canvas,text="Press",command=checkStatus,variable=status)
请注意,您不需要statusCkbtn.var=status
,因为可以使用小部件和status
函数来检索.get()
。除此之外,请确保将正确的参数传递给函数,由于.get()
,您无需将status
作为参数传递给checkStatus()