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()
添加回答
舉報