【发布时间】:2020-08-24 14:56:24
【问题描述】:
我有一个程序在选择选项(另一个支票禁止)时,可以将CheckButtons放置在画布中。我有另一个选项(另一个复选按钮)来画一条线。为了画线,首先我应该选择复选按钮“画一条线”,然后单击放置在画布中的任何复选按钮,然后单击画布上的任何位置。这适用于我放置的第一个检查按钮,但如果我放置多个检查按钮,它只会从画布中的最后一个检查按钮位置绘制线,而不是从我选择的检查点绘制线。 我相信我应该创建一个字典来跟踪我放置的复选按钮,以便我可以回调它们,但我不知道如何实现它,知道该怎么做吗?
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", variable=chosen_option, value = 2)
choose_line.place(x=10, y=100)
top_canvas.bind('<Button-1>', place_checkbutton_in_canvas)
root.mainloop()
【问题讨论】:
标签: python python-3.x dictionary tkinter canvas