1 回答
TA贡献1853条经验 获得超18个赞
您只有一个 example_checkbutton。每当您调用该.place()方法时,此按钮都会四处移动。
如果你想要新的,只需将它们创建为新的复选框小部件:
def place_checkbutton_in_canvas(e): # order to insert the checkbutton
if len(str(e.widget))<3: ## Don't place a new one if a checkbox was clicked
xx_and = e.x
yy_and = e.y
Checkbutton(root, variable=button1, textvariable=button1, command=color_checkbutton).place(x=xx_and, y=yy_and)
这将创建新的复选按钮,这些复选按钮都链接到button1变量。
编辑:
如果你想要新的复选按钮,你必须维护一个 IntVar() 和 Checkbutton() 对象的列表,每次点击都会变长。下面的代码应该可以工作。我还在创建时执行颜色更改以将它们创建为绿色和红色。
from tkinter import *
root = Tk()
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=0): # define the colors of the checkbutton
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))<3: ## Don't place a new one if a checkbox was clicked
b = IntVar()
pos = len(buttons)
xx_and = e.x
yy_and = e.y
buttons.append([b,pos, Checkbutton(root, variable=b, textvariable=b, command=CMD(color_checkbutton,pos))])
buttons[-1][2].place(x=xx_and, y=yy_and)
color_checkbutton(pos)
root.bind('<Button-1>', place_checkbutton_in_canvas)
root.mainloop()
添加回答
举报