亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 python 中通過單擊鼠標創建新的復選按鈕

如何在 python 中通過單擊鼠標創建新的復選按鈕

夢里花落0921 2023-06-06 10:28:00
我想創建一個程序,用戶可以通過單擊鼠標創建不同的按鈕,這些按鈕應該是獨立的。有了這個邏輯,用戶可以創建一個有效的復選按鈕,當它被選中時從綠色變為紅色。我的問題是,如果用戶再次單擊鼠標,復選按鈕會移動,而不是創建新的復選按鈕。任何建議如何去做?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()
查看完整描述

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


查看完整回答
反對 回復 2023-06-06
  • 1 回答
  • 0 關注
  • 114 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號