如何解决用python tkinter中的一行连接2个checkbutton
我在画布的程序以地方checkbuttons,选择了选项(另一checkbutton)时。我还有另一个选择(另一个检查按钮)来画一条线。为了绘制线条,首先我应该选择“绘制线条”复选框,然后单击放置在画布中的任何复选框,然后单击画布上的任何位置。可以与我放置的第一个检查按钮一起使用,但是如果我放置多个检查按钮,则它只会从画布中最后一个检查按钮位置画线,而不会从我选择的检查点画线。 我相信我应该创建一个词典来跟踪我放置的复选按钮,以便可以给他们回叫,但是我不知道如何实现它,不知道该怎么做?
from tkinter import *
root = Tk()
top_canvas = Canvas(root,width=1376,height=768,bg='light blue')
top_canvas.pack()
buttons = []
class CMD: #Auxilliary function for callbacks using parameters. Syntax: CMD(function,argument1,argument2,...)
def __init__(s1,func,*args):
s1.func = func
s1.args = args
def __call__(s1,*args):
args = s1.args+args
s1.func(*args)
def color_checkbutton(pos): # define the colors of the checkbutton
checkbutton_available()
if buttons[pos][0].get() == 1:
buttons[pos][2].configure(bg='red')
else:
buttons[pos][2].configure(bg='green')
def place_checkbutton_in_canvas(e): # order to insert the checkbutton
if len(str(e.widget))<12: ## Don't place a new one if a checkbox was clicked
b = IntVar()
pos = len(buttons)
global xx,yy
xx = e.x
yy = e.y
buttons.append([b,pos,Checkbutton(top_canvas,variable=b,textvariable=b,command=CMD(color_checkbutton,pos))])
buttons[-1][2].place(x=xx,y=yy)
color_checkbutton(pos)
def place_checkbutton(): #to run when checkbutton is selected. Now the checkbutton will be placed where mouse clicked if choose_line is selected
top_canvas.bind('<Button-1>',place_checkbutton_in_canvas)
def checkbutton_available():
def drawline(ev):
flx = ev.x
fly = ev.y
def auxiliary():
lineor = top_canvas.create_line(xx,yy,flx,fly,width =3,fill = 'red')
auxiliary()
if chosen_option.get() == 2:
top_canvas.bind('<Button-1>',drawline)
chosen_option = IntVar()
choose_checkbutton = Radiobutton(top_canvas,text = "place checkbutton",variable=chosen_option,value = 1,command = place_checkbutton)
choose_checkbutton.place(x=10,y=10)
choose_line = Radiobutton(top_canvas,text = "draw line",value = 2)
choose_line.place(x=10,y=100)
top_canvas.bind('<Button-1>',place_checkbutton_in_canvas)
root.mainloop()
解决方法
在代码中,您从(xx,yy)到(flx,fly)画了一条线,但是坐标(xx,yy)似乎是仅在place_checkbutton_in_canvas(e)函数中定义的全局变量。
因此(xx,yy)包含您放置的最后一个复选框的坐标。而且,只有当您放置新的复选按钮时,线的起点才重新定义。
要解决此问题,应在选中复选框后分配(xx,yy)全局变量。
此外,如果要从多个起点绘制线,则仅两个int变量(xx和yy)是不够的。您需要具有两个整数数组(或成对数组)来存储所有当前已检查值的位置。
如果您不希望同时绘制多条线,则也许应该使用单选按钮而不是复选框。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。