Get Checkbox states in array - Tkinter - python

I just started coding less than 3 weeks ago (took a class in Lynda) and now working on a GUI that enable user to tick/untick a lists. I manage to get it done but in inefficient workaround (someone gave me a heads up on this).
What i have done basically calling a variables for each checkbox and insert the checkbox states into it. So if I have 100 of checkboxes in the list, I will need to create 100 variables. Below is the working code that I wrote.
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
var1t1 = tk.IntVar()
var2t1 = tk.IntVar()
var3t1 = tk.IntVar()
var_name = []
root.title("Testing Checkbox")
root.geometry("200x150")
def boxstates_t1():
var_name = [var1t1.get(), var2t1.get(), var3t1.get()]
print(var_name)
# -----------------Checkbox-----------------
labelName = tk.Label(root, text = "Name")
labelName.pack(anchor = tk.W)
check1_t1 = ttk.Checkbutton(root, text = "Mike", variable = var1t1)
check1_t1.pack(anchor = tk.W)
check2_t1 = ttk.Checkbutton(root, text = "Harry", variable = var2t1)
check2_t1.pack(anchor = tk.W)
check3_t1 = ttk.Checkbutton(root, text = "Siti", variable = var3t1)
check3_t1.pack(anchor = tk.W)
# -----------------Button-----------------
btn2 = ttk.Button(root, text="Show", command = boxstates_t1)
btn2.pack(side=tk.RIGHT)
root.mainloop()
Then i googled around and found few code that lead me to use for loop to print the list. I initialize the var_name = [] so that it will capture each checkbox state from the list.
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
var1 = tk.IntVar()
var_name = []
root.title("Testing Checkbox")
root.geometry("200x150")
def boxstates():
var_name = var1.get()
print(var_name)
# ------------------Chekbox-------------
name1 = ["Mike", "Harry", "Siti"]
labelName = tk.Label(root, text = "Name")
labelName.pack(anchor = tk.W)
for checkboxname in name1:
check1_t1 = ttk.Checkbutton(root, text=checkboxname, variable=var1)
check1_t1.pack(anchor = tk.W)
# ------------------Button-------------
btn2 = ttk.Button(root, text="Show", command = boxstates)
btn2.pack(side=tk.RIGHT)
root.mainloop()
But I was unable to tick the checkbox independently and the print out result also comes back as if it's in single variable. Am I doing the array var_name = [] wrongly? I'm currently lost and have no clue where to head next.
Any advise is greatly appreciate.

Try this:
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
root.title("Testing Checkbox")
root.geometry("200x150")
def boxstates():
for var in vars:
print (var.get())
names = ["Mike", "Harry", "Siti"]
labelName = tk.Label(root, text = "Name")
labelName.pack(anchor = tk.W)
vars = []
for i, checkboxname in enumerate(names):
vars.append(tk.IntVar())
check = ttk.Checkbutton(root, text=checkboxname, variable=vars[i])
check.pack(anchor = tk.W)
btn = ttk.Button(root, text="Show", command = boxstates)
btn.pack(side=tk.RIGHT)
root.mainloop()

import tkinter as tk
from tkinter import ttk
def boxstates():
finalValue = []
for x in checkboxList:
finalValue.append(x.get())
print(finalValue)
root = tk.Tk()
root.title("Testing Checkbox")
root.geometry("200x150")
# ------------------Chekbox-------------
checkboxList = [tk.IntVar(), tk.IntVar(), tk.IntVar()] # if you want to add more you can either append to it or declare it before runtime
name1 = ["Mike", "Harry", "Siti"]
labelName = tk.Label(root, text = "Name")
labelName.pack(anchor = tk.W)
def createCheckboxes():
for x, y in zip (checkboxList, name1):
check1_t1 = ttk.Checkbutton(root, text=y, variable=x)
check1_t1.pack(anchor = tk.W)
# ------------------Button-------------
btn2 = ttk.Button(root, text="Show", command = boxstates)
btn2.pack(side=tk.RIGHT)
createCheckboxes()
root.mainloop()

Related

Label Not Continually Updating Tkinter

I have read through several answers to similar topics but none of them are relevant to my situation, I am trying to display a list on a label and whenever the button is pressed to update the list the label should update as well but it only updates when submitbtn_name is clicked. Any help appreciated I am very new to Tkinter.
My Code:
from tkinter import *
root = Tk()
root.title("Path Creator")
root.geometry('1680x1080')
root['background'] = '#aaaaaa'
list_of_paths_list = []
path_list = []
name = Entry(root, width=400)
name.insert(0, "Name")
name.pack()
def add_name():
path_list.append(name.get())
list_label = Label(root, text="path name:" + str(path_list))
list_label.pack()
submitbtn_name = Button(root, text="submit name", command=add_name)
submitbtn_name.pack()
value1 = Entry(root, width=400)
value1.insert(0, "value1")
value1.pack()
distance1 = Entry(root, width=400)
distance1.insert(0, "distance1")
distance1.pack()
def submitbtn_value_dist():
temp_list = []
temp_list.append(value1.get())
temp_list.append(distance1.get())
path_list.append(tuple(temp_list))
list_label = Label(root, text="current path: " + path_list)
list_label.pack()
submitbtn_pathpart = Button(root, text="submit path part", )
submitbtn_pathpart.pack()
root.mainloop()
Using f-string format. Added command in submitbtn_pathpart
Snippet:
def submitbtn_value_dist():
temp_list = []
temp_list.append(value1.get())
temp_list.append(distance1.get())
path_list.append(tuple(temp_list))
list_label = Label(root, text=f"current path:{path_list}")
list_label.pack()
submitbtn_pathpart = Button(root, text="submit path part", command=submitbtn_value_dist )
submitbtn_pathpart.pack()
root.mainloop()
Output for name:
Output for value and distance:

Python entry to store input into a variable stores nothing, returns initial value

Ok, so basic story. I have created an entry. After you introduce text, you have to click a button to store the inputted text into a variable that is later printed.
Here is the code:
from Tkinter import *
def myClick(entry_name, var):#defines function to get input from entry and store into var
var = entry_name.get()
root = Tk()#creates initial tk
lbl1 = Label(root, text = "hello")#before entry label
lbl1.grid(row = 0, column = 0)#label griding
ent = Entry(root, width = 15)# the entry
ent.grid(row = 1, column = 0)#entry gridding
hello = None #variable to store entry input
bt1 = Button(root, command = myClick(ent, hello))#button 1 creation and function attribution
bt1.grid(row = 3, column = 0)#button 1 griding
root.mainloop()
print(hello)
It is very unclear to me why the function does not get the input from the entry.
bt1 = Button(root, command = myClick(ent, hello))
In this line, you call myClick function with parameters, not just pass it. That means that myClick is executed once after the module is launched and then it does nothing. If you want to print the entry input, I recommend you do the following:
from tkinter import *
root = Tk()
lbl1 = Label(root, text="hello")
lbl1.grid(row=0, column=0)
ent = Entry(root, width=15)
ent.grid(row=1, column=0)
def myClick():
var = ent.get()
print(var)
bt1 = Button(root, command=myClick)
bt1.grid(row=3, column=0)
root.mainloop()
Also code after root.mainloop() doesn't excecute.
just define a normal function :
from tkinter import *
def blinta():
var = ent.get()
ent.delete(0,END)
print(var)
root = Tk()#creates initial tk
lbl1 = Label(root, text = "hello")#before entry label
lbl1.grid(row = 0, column = 0)#label griding
ent = Entry(root, width = 15)# the entry
ent.grid(row = 1, column = 0)#entry gridding
bt1 = Button(root, command = blinta)
bt1.grid(row = 3, column = 0)
root.mainloop()
This will work I'm sure.

clearing multiple labels values

I am losing my peanuts here. I am trying to clear two label values but i get an error
AttributeError: 'Label' object has no attribute 'delete'
basically if i were to click the calculate subtotal button then click the divide total button. I get my intended values. Now if I were to click on the clear values button i get an error. Literally shaking my head as I type this. Anyone care to explain why this is the case?
try:
import Tkinter as tk
except:
import tkinter as tk
class GetInterfaceValues():
def __init__(self):
self.root = tk.Tk()
self.totalValue = tk.StringVar()
self.root.geometry('500x200')
self.calculateButton = tk.Button(self.root,
text='Calculate Subtotal',
command=self.getSubtotals)
self.divideTotalButton = tk.Button(self.root,
text='Divide total',
command=self.divide)
self.textInputBox = tk.Text(self.root, relief=tk.RIDGE, height=1, width = 6, borderwidth=2)
self.firstLabel = tk.Label(self.root, text="This is the subtotal:")
self.secondLabel = tk.Label(self.root, text="This is the Divide Total:")
self.clearTotalButton = tk.Button(self.root, text='clear the values',command = self.clear)
self.firstLabel.pack(side="bottom")
self.secondLabel.pack(side="bottom")
self.textInputBox.pack()
self.calculateButton.pack()
self.divideTotalButton.pack()
self.clearTotalButton.pack()
self.root.mainloop()
def getTextInput(self):
result = self.textInputBox.get("1.0", "end")
return result
def getSubtotals(self):
userValue = int(self.getTextInput())
self.firstLabel["text"] = self.firstLabel["text"] + str(userValue * 5)
def divide(self):
userValue = int(self.getTextInput())
self.secondLabel["text"] = self.secondLabel["text"] + str(userValue / 10)
def clear(self):
self.firstLabel["text"] = self.firstLabel.delete("1.0","end")
app = GetInterfaceValues()
try:
import Tkinter as tk
except:
import tkinter as tk
class GetInterfaceValues():
def __init__(self):
self.root = tk.Tk()
self.totalValue = tk.StringVar()
self.root.geometry('500x200')
self.calculateButton = tk.Button(self.root,
text='Calculate Subtotal',
command=self.getSubtotals)
self.divideTotalButton = tk.Button(self.root,
text='Divide total',
command=self.divide)
self.textInputBox = tk.Text(self.root, relief=tk.RIDGE, height=1, width = 6, borderwidth=2)
self.firstLabelDefault = "This is the subtotal:"
self.secondLabelDefault = "This is the Divide Total:"
self.firstLabel = tk.Label(self.root, text=self.firstLabelDefault)
self.secondLabel = tk.Label(self.root, text=self.secondLabelDefault)
self.clearTotalButton = tk.Button(self.root, text='clear the values',command = self.clear)
self.firstLabel.pack(side="bottom")
self.secondLabel.pack(side="bottom")
self.textInputBox.pack()
self.calculateButton.pack()
self.divideTotalButton.pack()
self.clearTotalButton.pack()
self.root.mainloop()
def getTextInput(self):
result = self.textInputBox.get("1.0", "end")
return result
def getSubtotals(self):
userValue = int(self.getTextInput())
self.firstLabel["text"] = self.firstLabel["text"] + str(userValue * 5)
def divide(self):
userValue = int(self.getTextInput())
self.secondLabel["text"] = self.secondLabel["text"] + str(userValue / 10)
def clear(self):
self.firstLabel["text"] = self.firstLabelDefault
self.secondLabel["text"] = self.secondLabelDefault
self.textInputBox.delete("1.0", "end")
app = GetInterfaceValues()
You may have confused the methods of tkinter.Text and tkinter.Label. The method you called was tkinter.label.delete, which is not defined (does not exist), however it does exist for the tkinter.Text. Therefore, the only way to 'reset' would be to change the text attribute of the tkinter.Labels back to a 'default' string. It would perhaps be more appropriate to use another widget instead.

How to use class and self here to get two different entries?

With my current code, it does not matter whether I click on "Input Folder" - Change or "JukeBox" change the result always gets displayed in "JukeBox" entry. This is incorrect, using class and self how can I change the code to display result from "Input Folder" - Change in "Input Folder" entry and the result from "Jukbox" - Change in "Jukebox" entry?
Also, how can I save the selected folders to a file so that it is there on app exit and re open?
My code:
import os
from tkinter import *
from tkinter import filedialog
inPut_dir = ''
jukeBox_dir = ''
def inPut():
opendir = filedialog.askdirectory(parent=root,initialdir="/",title='Input Folder')
inPut_dir = StringVar()
inPut_dir = os.path.abspath(opendir)
entry.delete(0, END)
entry.insert(0, inPut_dir)
def jukeBox():
opendir = filedialog.askdirectory(parent=root,initialdir="/",title='JukeBox')
jukeBox_dir = StringVar()
jukeBox_dir = os.path.abspath(opendir)
entry.delete(0, END)
entry.insert(0, jukeBox_dir)
root = Tk()
root.geometry("640x240")
root.title("Settings")
frametop = Frame(root)
framebottom = Frame(root)
frameright = Frame(framebottom)
text = Label(frametop, text="Input Folder").grid(row=5, column=2)
entry = Entry(frametop, width=50, textvariable=inPut_dir)
entry.grid(row=5,column=4,padx=2,pady=2,sticky='we',columnspan=20)
text = Label(frametop, text="JukeBox").grid(row=6, column=2)
entry = Entry(frametop, width=50, textvariable=jukeBox_dir)
entry.grid(row=6,column=4,padx=2,pady=2,sticky='we',columnspan=20)
ButtonA = Button(frametop, text="Change", command=inPut).grid(row=5, column=28)
ButtonB = Button(frametop, text="Change", command=jukeBox).grid(row=6, column=28)
ButtonC = Button(frameright, text="OK").grid(row=5, column=20, padx=10)
ButtonD = Button(frameright, text="Cancel").grid(row=5, column=15)
frametop.pack(side=TOP, fill=BOTH, expand=1)
framebottom.pack(side=BOTTOM, fill=BOTH, expand=1)
frameright.pack(side=RIGHT)
root.mainloop()
See attached image:enter image description here
Your code has both:
entry = Entry(frametop, width=50, textvariable=inPut_dir)
entry.grid(row=5,column=4,padx=2,pady=2,sticky='we',columnspan=20)
and
entry = Entry(frametop, width=50, textvariable=jukeBox_dir)
entry.grid(row=6,column=4,padx=2,pady=2,sticky='we',columnspan=20)
with jukeBox_dir/row 6 overriding inPut_dir/row 5
Therefore, in def input:
where you have:
entry.insert(0, inPut_dir)
You'll get the result in row 5 (jukebox_dir)

get previous Entry

I am trying to make a tkinter widget that will remember the previous entry. The problem I am having is the that the button method I made erases the previous entry every time its pressed.
from Tkinter import *
class step1():
def __init__(self):
pass
def getTextbook(self):
temp = str(textbook.get())
textbook.delete(0, END)
x = " "
x += temp
print x
def equal_button(self):
print getTextbook(self)
root = Tk()
root.title("step1")
root.geometry("600x600")
s = step1()
app = Frame(root)
app.grid()
label = Label(app, text = "step1")
label.grid()
textbook = Entry(app, justify=RIGHT)
textbook.grid(row=0, column = 0, columnspan = 3, pady = 5)
textbook2 = Entry(app, justify=RIGHT)
textbook2.grid(row=1, column = 0, columnspan = 3, pady = 5)
button1 = Button(app, text = "Return", command = lambda: s.getTextbook())
button1.grid()
button2 = Button(app, text="Equal")
button2.grid()
root.mainloop()
The variable X in your getTextbook() is being overwritten every time you set it to " ". Try a list instead, and append each entry to the list when the button is pressed:
from Tkinter import *
root = Tk()
textbookList = []
def getTextbook():
textbookList.append(textbook.get())
textbook.delete(0,END)
print textbookList
textbook = Entry(root)
textbook.pack()
btn1 = Button(root, text='Return', command=getTextbook)
btn1.pack()
root.mainloop()

Categories

Resources