python - 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)
解决方案
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()
.
推荐阅读
- python-3.x - 属性错误:模块“pytest”没有属性“hookimpl”
- java - 从缓存中删除 log4j 1.2.12
- c++ - 如何允许 C++ 程序用户请求返回程序的前一个步骤?
- bash - 生成的 SHA256 值与预期的 SHA256 值不同
- html - 从数据库中提取字符串时如何在 JSX 中呈现 HTML 标签
- twitter-bootstrap - 您如何在 Bootstrap 4.5 中使用 $spacer 变量?
- vue.js - vue.js 函数仅在值大于零时工作
- numpy - 带有 3d 数组的 Numpy 点积
- javascript - 滚动时菜单变成纯色?JS?
- c# - 错误 CS0246 使用枚举时找不到类型或命名空间名称