1

我想创建一个程序,用户可以通过单击鼠标创建不同的按钮,这些按钮应该是独立的。使用这个逻辑,用户可以创建一个可以工作的复选按钮,当被选中时从绿色变为红色。我的问题是,如果用户再次单击鼠标,则检查按钮会移动,而不是创建新的检查按钮。有什么建议怎么做吗?

from tkinter import *

root = Tk()

button1 = IntVar()

def color_checkbutton():  # define the colors of the checkbutton
    if button1.get() == 1:
        example_checkbutton.configure(bg='red')
    else:
        example_checkbutton.configure(bg='green')
example_checkbutton = Checkbutton(root, variable=button1, textvariable=button1, command=color_checkbutton)

def place_checkbutton_in_canvas(e):  # order to insert the checkbutton
    xx_and = e.x
    yy_and = e.y
    example_checkbutton.place(x=xx_and, y=yy_and)

root.bind('<Button-1>', place_checkbutton_in_canvas)

root.mainloop()
4

1 回答 1

3

您只有一个 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()
于 2020-08-18T12:22:33.783 回答