如何在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()

解决方法

您只有一个example_checkbutton。每当您调用.place()方法时,此按钮就会四处移动。

如果您想要新的,只需将它们创建为新的Checkbox-widgets:

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...