猿问

如何在 python 中通过单击鼠标创建新的复选按钮

我想创建一个程序,用户可以通过单击鼠标创建不同的按钮,这些按钮应该是独立的。有了这个逻辑,用户可以创建一个有效的复选按钮,当它被选中时从绿色变为红色。我的问题是,如果用户再次单击鼠标,复选按钮会移动,而不是创建新的复选按钮。任何建议如何去做?


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()


梦里花落0921
浏览 92回答 1
1回答

慕容森

您只有一个 example_checkbutton。每当您调用该.place()方法时,此按钮都会四处移动。如果你想要新的,只需将它们创建为新的复选框小部件:def place_checkbutton_in_canvas(e):&nbsp; # order to insert the checkbutton&nbsp; &nbsp; if len(str(e.widget))<3: ## Don't place a new one if a checkbox was clicked&nbsp; &nbsp; &nbsp; &nbsp; xx_and = e.x&nbsp; &nbsp; &nbsp; &nbsp; yy_and = e.y&nbsp; &nbsp; &nbsp; &nbsp; 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, ...)&nbsp; &nbsp; def __init__(s1, func, *args):&nbsp; &nbsp; &nbsp; &nbsp; s1.func = func&nbsp; &nbsp; &nbsp; &nbsp; s1.args = args&nbsp; &nbsp; def __call__(s1, *args):&nbsp; &nbsp; &nbsp; &nbsp; args = s1.args+args&nbsp; &nbsp; &nbsp; &nbsp; s1.func(*args)def color_checkbutton(pos=0):&nbsp; # define the colors of the checkbutton&nbsp; &nbsp; if buttons[pos][0].get() == 1:&nbsp; &nbsp; &nbsp; &nbsp; buttons[pos][2].configure(bg='red')&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; buttons[pos][2].configure(bg='green')def place_checkbutton_in_canvas(e):&nbsp; # order to insert the checkbutton&nbsp; &nbsp; if len(str(e.widget))<3: ## Don't place a new one if a checkbox was clicked&nbsp; &nbsp; &nbsp; &nbsp; b = IntVar()&nbsp; &nbsp; &nbsp; &nbsp; pos = len(buttons)&nbsp; &nbsp; &nbsp; &nbsp; xx_and = e.x&nbsp; &nbsp; &nbsp; &nbsp; yy_and = e.y&nbsp; &nbsp; &nbsp; &nbsp; buttons.append([b,pos, Checkbutton(root, variable=b, textvariable=b, command=CMD(color_checkbutton,pos))])&nbsp; &nbsp; &nbsp; &nbsp; buttons[-1][2].place(x=xx_and, y=yy_and)&nbsp; &nbsp; &nbsp; &nbsp; color_checkbutton(pos)root.bind('<Button-1>', place_checkbutton_in_canvas)root.mainloop()
随时随地看视频慕课网APP

相关分类

Python
我要回答