首页 > 解决方案 > How do I make a function for cancel button which when button is clicked unchecks all buttons that I have checked?

问题描述

I have made a menu which consists of checkbuttons which are created by adding values to a list, so to be precise if I want to add a new item on the menu all I need to do is to put something in the list and checkbutton will be created through while loop. I landed on a problem here, I want to make a cancel button which unchecks all the selected buttons but due to variable option in checkbutton being same for all the buttons because there is only one while loop for creating them all my buttons get selected when I press on one.

Note I do not want to use deselect() option, I am trying to make it this way. Typical error I get is:

Ponisti[p] = tkinter.IntVar()
IndexError: list assignment index out of range,

Or it does that thing where it selects all when I press one button. So all in all, I am trying to make the variable in checkbutton change for each new button I add so I can select them independently.

My piece of code is given as an example, I hope you can get a grasp of it and a grasp of my idea.

Piece of code:

import tkinter

window = tkinter.Tk()
Array =[]

p=0
Ponisti =[]
while p != len(Meni):
     Ponisti[p] = tkinter.IntVar()
     p=p+1

def cancel():
    f=0
    for i in Array:
       Ponisti[f].set('0')
       f=f+1

while j != len(Meni):
    items = tkinter.Checkbutton(window, text=Meni[j], onvalue=1, offvalue=0)
   
canceldugme = tkinter.Button(frame1,text="Cancel",command=cancel)

标签: pythonloopstkinter

解决方案


This does what you want.

import tkinter as tk

def reset():
    for var in variables:
        var.set(0)

menu = [str(i) for i in range(8)]

root = tk.Tk()

frame = tk.Frame(root)
frame.pack()

variables = [tk.IntVar(0) for _ in range(len(menu))]

length = len(menu) // 2
for i, var in enumerate(variables):
    row, col = divmod(i, length)
    checkbutton = tk.Checkbutton(frame, variable=var, text=menu[i])
    checkbutton.grid(row=row, column=col, sticky="w")

reset_button = tk.Button(root, text="Reset", command=reset)
reset_button.pack(side="right")

root.mainloop()

Basically you want to create a list of variables and for each variable create a new button that is bound to it. When you call the reset function, all you have to do is iterate over your variables and reset their value.

I put the checkbuttons in a frame so you can use the grid method, since it seeems you want to lay them out in a grid fashion. The reason for using a frame is that you can't mix grid and pack for the same window. Both frame and reset_button are placed using pack(), and the checkuttons inside the frame can then be placed using grid().


推荐阅读