can't get Variable value of groups of ttk.CheckButtons - python

I'm creating 3 groups of ttk.CheckButtons, using a class clsGrpCheckButton.
The problem is that I can access only the status of the last group created, and not for the previous group.
When clicking on one of the checkButtons of any group, I'm expecting to get the list of checkbuttons check in the group (by using method chkGrpGetValue with is the command parameter of each checkbutton)
However, whatever which button is clicked, the method only and always returns the status of the last group
Here is the code to recreate the issue, and in attachment a picture that shows the problems
Thks for your help.
Rgds
import tkinter as tk
from tkinter import ttk
import pandas as pd
class clsGrpCheckButton(ttk.Checkbutton):
def __init__(self,pContainer, pLstVal,pCommand,pInitValue=True):
self.grpChk=[0]*len(pLstVal)
self.grpKey=[0]*len(pLstVal)
self.grpLstVal = [0]*len(pLstVal)
self.grpVariable= [0]*len(pLstVal)
self.grpActiveKeys = [0]
for l,t in enumerate(pLstVal):
#l : index of the list of tuples
self.grpKey[l] = t[0]
self.grpLstVal[l] = t[1]
self.grpVariable[l] = tk.StringVar()
self.grpChk[l] = ttk.Checkbutton(pContainer, text=self.grpLstVal[l],
state='active' ,
onvalue= self.grpKey[l],
offvalue= '',
variable = self.grpVariable[l],
command=pCommand)
#get default value
if pInitValue :
self.grpVariable[l].set(self.grpKey[l])
self.grpActiveKeys.append(self.grpKey[l])
#get the index in the list of checkboxes
# depending on the key
def chkGrpGetIdx(self, pKey):
i=0
while i <len(self.grpKey):
if self.grpKey[i]==pKey :
return i
i=len(self.grpKey)
else:
i+=1
def chkGrpSetValue(self, pKey, pValue):
#need find correct index first
i=self.chkGrpGetIdx(pKey)
self.grpVariable[i] = pValue
#return the list of keys of the group
def chkGrpKeyLst(self):
return self.grpKey
#return the checkox element of the group of checkox
def chkGrpGetChkObj(self,pKey):
i=self.chkGrpGetIdx(pKey)
return self.grpChk[i]
#action when check/uncheck
#at list one element should be active
def chkGrpGetValue(self):
i=0
r=len(self.grpVariable)
self.grpActiveKeys.clear()
while i < len(self.grpVariable):
if self.grpVariable[i].get() =='':
r-=1
else:
self.grpActiveKeys.append(self.grpKey[i])
i+=1
if r==0:
self.grpVariable[0].set(self.grpKey[0])
self.grpActiveKeys.append(self.grpKey[0])
print(self.grpActiveKeys)
#to avoid accessing to class attribute directly
def chkGetCheckedValues(self):
return self.grpActiveKeys
class clsWindows(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
la = [1,1,1,1,1,2,2,2,2,2,2,2,3,3,3,3]
lb= [10,11,12,14,15,20,21,22,23,24,25,26,30,31,32,33]
lc=['d10','d11','d12','d14','d15','d20','d21','d22','d23','d24','d25','d26','d30','d31','d32','d33']
df = pd.DataFrame(
{'DIVISION': la,
'DEPT_CODE': lb,
'DEPT_NAME': lc
})
lW = list(zip(df['DIVISION'].astype(str) , df['DEPT_CODE'].astype(str)))
lpt = list(zip(df['DEPT_CODE'].astype(str) , df['DEPT_NAME'].astype(str)))
curHead = ""
r=0
c=-1
for head, DPT in lW:
if not curHead==head:
curHead = head
c+=1
r=0
dq=df.query('DIVISION=='+head)
lpt = list(zip(dq['DEPT_CODE'].astype(str) , dq['DEPT_NAME'].astype(str)))
t=ttk.Labelframe(self,text=head)
t.grid(column=c, row=0, sticky='nw')
self.checkGrpDept= clsGrpCheckButton(t,lpt,lambda:self.checkGrpDept.chkGrpGetValue(),True)
self.checkGrpDept.chkGrpGetChkObj(DPT).grid(column=c, row=r, sticky='nw')
t.rowconfigure(r, weight=1)
t.columnconfigure(c, weight=1)
r+=1
def wQuit(self):
self.destroy()
app = clsWindows()
app.mainloop()
Example of issue

finally, I came up with a solution by using partial when assigning the command to each checkbutton.
Here is the full code if someone faces a similar issue
import tkinter as tk
from tkinter import ttk
import pandas as pd
from functools import partial
class clsGrpCheckButton():
def __init__(self,pContainer, pLstVal,pCommand,pInitValue=True):
self.grpChk=[0]*len(pLstVal)
self.grpKey=[0]*len(pLstVal)
self.grpLstVal = [0]*len(pLstVal)
self.grpVariable= [0]*len(pLstVal)
self.grpActiveKeys = [0]
for l,t in enumerate(pLstVal):
#l : index of the list of tuples
self.grpKey[l] = t[0]
self.grpLstVal[l] = t[1]
self.grpVariable[l] = tk.StringVar()
self.grpChk[l] = ttk.Checkbutton(pContainer, text=self.grpLstVal[l],
state='active' ,
onvalue= self.grpKey[l],
offvalue= '',
variable = self.grpVariable[l],
command=partial(pCommand,self))
#get default value
if pInitValue :
self.grpVariable[l].set(self.grpKey[l])
self.grpActiveKeys.append(self.grpKey[l])
#get the index in the list of checkboxes
# depending on the key
def chkGrpGetIdx(self, pKey):
i=0
while i <len(self.grpKey):
if self.grpKey[i]==pKey :
return i
i=len(self.grpKey)
else:
i+=1
def chkGrpSetValue(self, pKey, pValue):
#need find correct index first
i=self.chkGrpGetIdx(pKey)
self.grpVariable[i] = pValue
#return the list of keys of the group
def chkGrpKeyLst(self):
return self.grpKey
#return the checkox element of the group of checkox
def chkGrpGetChkObj(self,pKey):
i=self.chkGrpGetIdx(pKey)
return self.grpChk[i]
#action when check/uncheck
#at list one element should be active
def chkGrpGetValue(self):
i=0
r=len(self.grpVariable)
self.grpActiveKeys.clear()
while i < len(self.grpVariable):
if self.grpVariable[i].get() =='':
r-=1
else:
self.grpActiveKeys.append(self.grpKey[i])
i+=1
if r==0:
self.grpVariable[0].set(self.grpKey[0])
self.grpActiveKeys.append(self.grpKey[0])
print(self.grpActiveKeys)
#to avoid accessing to class attribute directly
def chkGetCheckedValues(self):
return self.grpActiveKeys
class clsWindows(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
la = [1,1,1,1,1,2,2,2,2,2,2,2,3,3,3,3]
lb= [10,11,12,14,15,20,21,22,23,24,25,26,30,31,32,33]
lc=['d10','d11','d12','d14','d15','d20','d21','d22','d23','d24','d25','d26','d30','d31','d32','d33']
df = pd.DataFrame(
{'DIVISION': la,
'DEPT_CODE': lb,
'DEPT_NAME': lc
})
lW = list(zip(df['DIVISION'].astype(str) , df['DEPT_CODE'].astype(str)))
lpt = list(zip(df['DEPT_CODE'].astype(str) , df['DEPT_NAME'].astype(str)))
curHead = ""
r=0
c=-1
for head, DPT in lW:
if not curHead==head:
curHead = head
c+=1
r=0
dq=df.query('DIVISION=='+head)
lpt = list(zip(dq['DEPT_CODE'].astype(str) , dq['DEPT_NAME'].astype(str)))
t=ttk.Labelframe(self,text=head)
t.grid(column=c, row=0, sticky='nw')
checkGrpDept= clsGrpCheckButton(t,lpt,clsGrpCheckButton.chkGrpGetValue,True)
checkGrpDept.chkGrpGetChkObj(DPT).grid(column=c, row=r, sticky='nw')
t.rowconfigure(r, weight=1)
t.columnconfigure(c, weight=1)
r+=1
def wQuit(self):
self.destroy()
app = clsWindows()
app.mainloop()

Related

PYTHON TKINTER set focus to next row instead of next widget

I have frames in a grid with widgets in them. These frames get destroyed and new ones are created. I want to move between these with keyboard.
The Problem: every time there is a new frame it gets treated by focus next as the last one.
The Question: how to focus by row instead.
def create_a_line(i):
p=1 #sometimes there are more widgets in a row, but here just take 1
bframe = Frame(root)
bframe.grid(row=i, column=0)
m = Button(bframe, text=h[i], , takefocus = 1)
m.bind('<Right>', lambda event, i=i: focus_next(i, p))
m.bind('<Double-1>', lambda event, i=i: double_click_text(i))
m.grid(row=0, column=p)
def double_click_text(i)
for widget in root.grid_slaves(row=i):
widget.destroy()
#change h[i] i.e. text of the button to something else
create_a_line(i) #with new text but same row
def focus_next(i, p): #this is what im struggling with
event.widget.tk_focusNext().focus() #this is how it is right now
#this is how i would like it to be, but no idea how:
# if in row=i other widgets with column >p: sometimes there will be more than one widget in a row
# event.widget.tk_focusNext().focus()
# else:
# set_focus(first widget in grid row=i+1)
for i in range(0, 5) #the end number is based on number of lines f.e. 5
create_a_line(i)
For lack of a better solution this is how I solved it based on comments:
labellsall=[]
h = []
def ad_to_labelsall(i, p , z):
ag = ["#"+str(i)+"i#", p, z] #made i more complicated so I dont find random numbers
labelsall.append(ag)
def del_from_labelsall(i):
agi = ("#"+str(i)+"i#")
ngip = [e for e, s in enumerate(labelsall) if agi in s]
for index in sorted(ngip, reverse=True):
del labelsall[index]
def create_a_line(i):
p=1
bframe = Frame(root)
bframe.grid(row=i, column=0)
m = Button(bframe, text=h[i], , takefocus = 1)
m.bind('<Right>', lambda event, i=i: focus_next(event, i))
m.bind('<Double-1>', lambda event, i=i: double_click_text(i))
m.grid(row=0, column=p)
ad_to_labelsall(i, p , z=m)
def double_click_text(i)
del_from_labelsall(i)
for widget in root.grid_slaves(row=i):
widget.destroy()
#some other code change h[i] i.e. text of the button to something else
create_a_line(i) #with new text but same row
def focus_next(event, i):
grid_info = event.widget.grid_info()
p = grid_info["column"]
agi = ("#"+str(i)+"i#")
ngip = [e for e, s in enumerate(labelsall) if agi in s]
for index in sorted(ngip):
the_row = labelsall[index]
if int(the_row[1]) > p: #check if other widget is in the row before jumping to next row
the_row[2].focus_set() #if other widget found focus it
return("break")
else:
pass
i_next = i+1
try:
agi_next = ("#"+str(i_next)+"i#")
ngip_next = [e for e, s in enumerate(labelsall) if agi_next in s]
labelsall[ngip_next[0]][2].focus_set()
except:
agi_next = ("#"+str(i_next+1)+"i#") #sometimes there are rows with no widgets, so just try the next one
ngip_next = [e for e, s in enumerate(labelsall) if agi_next in s]
labelsall[ngip_next[0]][2].focus_set()
return("break")

Is there a way of getting data from entries by rows from a table of entries in Tkinter?

So far I have a portion of code for a function that works fine as is for generating a table off of user input and then getting data from the table generated to be used in a line graph. However, the solution as it stands creates one massive list by iterating through every entry's data and is then graphed as one massive line graph. I intended for the function to create lists from each row of the table which is then inserted into a master list for pyplot to then graph as multiple lines on the same graph. Is there a way to achieve this? This is the code I am using:
import tkinter as tk
import matplotlib.pyplot as plt
graphinput = tk.Tk()
def opentable():
global total_rows
global total_columns
total_rows = int(yaxis.get())
total_columns = int(xaxis.get())
table = tk.Toplevel(graphinput)
table.resizable(0,0)
table.title("Table")
def tcompile():
masterlines = []
for cell in my_entries:
print(cell.get())
masterlines.append(int(cell.get()))
plt.plot(masterlines)
plt.show()
my_entries = []
for i in range(total_rows):
for j in range(total_columns):
cell = tk.Entry(table,width=20,font=('Agency FB',15))
cell.grid(row=i,column=j)
my_entries.append(cell)
tblframe = tk.Frame(table,bd=4)
tblframe.grid(row=i+1,column=j)
compbtn = tk.Button(tblframe,font=("Agency FB",20),text="Compile",command=tcompile)
compbtn.grid(row=0,column=0)
tablegrid = tk.Frame(graphinput,bd=4)
tablegrid.pack()
xlabel = tk.Label(tablegrid,text="Column Entry")
xlabel.grid(row=0,column=0)
ylabel = tk.Label(tablegrid,text="Row Entry")
ylabel.grid(row=0,column=1)
xaxis = tk.Entry(tablegrid)
xaxis.grid(row=1,column=0)
yaxis = tk.Entry(tablegrid)
yaxis.grid(row=1,column=1)
framebtn = tk.Button(tablegrid,text="Create",command=opentable)
framebtn.grid(row=3,column=0)
graphinput.mainloop()
Try something like this:
import tkinter as tk
def tcompile():
masterlines = []
for i in range(total_rows):
row = []
for j in range(total_columns):
data = my_entries[i*total_columns+j].get()
# data = int(data) # Removed for testing purposes
row.append(data)
masterlines.append(row)
print(masterlines)
root = tk.Tk()
total_rows = 3
total_columns = 4
my_entries = []
for i in range(total_rows):
for j in range(total_columns):
cell = tk.Entry(root)
cell.grid(row=i, column=j)
my_entries.append(cell)
# Add a button for testing purposes
button = tk.Button(root, text="Click me", command=tcompile)
button.grid(row=1000, columnspan=total_columns)
root.mainloop()
The key is to use my_entries[i*total_columns+j] to get the entry in row i and column j.
Note: I didn't add the matplotlib stuff because I don't really know how it works.

Turning StringVar value to list

I have been working on a Tkinter project. I have set the listbox as StringVar and I would like to call a list of items inside the right listbox by setting a function 'process'.
enter image description here
After I press the button process in the gui, I am supposed to return a list ['A'] in the above case.
However, it return ['(', "'", 'A', "'", ')']
If I just print app.list_var2.get() it return ('A',)
import tkinter as tk
import pandas as pd
app=tk.Tk()
app.geometry('640x480')
app.resizable(width=True, height=True)
app.title('Simulator')
# list variables
app.list_var1 = tk.StringVar()
app.list_var2 = tk.StringVar()
app.list_var1.set(value=['A','B','C'])
app.list_var2.set(value=[])
# label frame
app.label_frame= tk.Frame(app)
app.label1 = tk.Label(app.label_frame,text='PDC',justify='left')
app.label1.pack(ipadx=10,ipady=10,side='left', anchor='w')
app.label2 = tk.Label(app.label_frame,text='SDC')
app.label2.pack(ipadx=20,ipady=10, side='left',anchor='e')
# main frame
app.main_frame = tk.Frame(app)
app.listbox1 = tk.Listbox(app.main_frame, listvariable=app.list_var1, selectmode='single')
app.listbox2 = tk.Listbox(app.main_frame, listvariable=app.list_var2, selectmode='single')
def init_default_values():
app.list_var1.set(value=['A','B','C'])
app.list_var2.set(value=[])
def move_to_right(only_one_item=False):
if app.listbox1.curselection() == ():
return
# get tuple of selected indices
if only_one_item:
selection = (app.listbox1.curselection()[0],)
else:
selection = app.listbox1.curselection()
# left all/selected values
left_value_list = [line.strip(' \'') for line in app.list_var1.get()[1:-1].split(',')]
left_selected_list = [left_value_list[index] for index in selection]
# values from right side
right_value_list = [line.strip(' \'') for line in app.list_var2.get()[1:-1].split(',')]
# merge w/o duplicates
result_list = sorted(list(set(right_value_list + left_selected_list)))
for x in left_value_list:
if x in result_list:
left_value_list.remove(x)
while("" in left_value_list) :
left_value_list.remove("")
while("" in result_list) :
result_list.remove("")
app.list_var2.set(value=result_list)
app.list_var1.set(value=left_value_list)
def move_to_left(only_one_item=False):
if app.listbox2.curselection() == ():
return
# get tuple of selected indices
if only_one_item:
selection = (app.listbox2.curselection()[0],)
else:
selection = app.listbox2.curselection()
# right all/selected values
right_value_list = [line.strip(' \'') for line in app.list_var2.get()[1:-1].split(',')]
right_selected_list = [right_value_list[index] for index in selection]
# values from left side
left_value_list = [line.strip(' \'') for line in app.list_var1.get()[1:-1].split(',')]
# merge w/o duplicates
result_list = sorted(list(set(left_value_list + right_selected_list)))
for x in right_value_list:
if x in result_list:
right_value_list.remove(x)
while("" in right_value_list) :
right_value_list.remove("")
while("" in result_list) :
result_list.remove("")
app.list_var1.set(value=result_list)
app.list_var2.set(value=right_value_list)
def reset():
init_default_values()
def process():
#if len(app.list_var2.get()) == 1:
lst=app.list_var2.get()
print(len(lst))
lst = str(app.list_var2.get()).replace(',','')
lst=list(lst)
print(type(lst))
print(len(lst))
print(lst)
# little button frame
app.button_frame = tk.Frame(app.main_frame)
app.one_to_right_button = tk.Button(app.button_frame, text='>', command=lambda: move_to_right(True))
app.one_to_left_button = tk.Button(app.button_frame, text='<', command=lambda: move_to_left(True))
app.reset_button = tk.Button(app.button_frame,text='Reset',command=reset)
app.process = tk.Button(app.button_frame,text='Process',command=process)
# packing
app.one_to_right_button.pack()
app.one_to_left_button.pack()
app.reset_button.pack()
app.process.pack()
app.listbox1.pack(side='left', anchor='w')
app.button_frame.pack(side='left')
app.listbox2.pack(side='right', anchor='e')
app.label_frame.pack()
app.main_frame.pack(padx=20,pady=20)
# insert default values
init_default_values()
app.mainloop()
Since app.list_var2 is a StringVar, so app.list_var2.get() will always return a string.
Better use app.listbox2.get(0, "end") to get all the items (a tuple) in the listbox:
def process():
lst = list(app.listbox2.get(0, 'end'))
print(lst, type(lst))
Note that you can use eval() to convert the string returned by app.list_var2.get() to tuple but it is not recommended:
def process():
lst = list(eval(app.list_var2.get()))
print(lst, type(lst))

UnboundLocalError: local variable 'qn' referenced before assignment

I'm getting the error "UnboundLocalError: local variable 'qn' referenced before assignment" on running the code. Why is that? How can I correct it? I'm new to tkinter so please try to keep it simple. This is part of the code for a game I was writing. It would be a great help if I could get an answer soon
from tkinter import *
from tkinter import messagebox
from io import StringIO
root = Tk()
root.title("Captain!")
root.geometry("660x560")
qn = '''1$who are you?$char1$i am joe$3$i am ben$2
2$what are you?$char2$i am a person$1$i am nobody$3
3$how are you?$char3$i am fine$2$i'm alright$1'''
var = '''1$10$-35$20$15$-20
2$9$7$30$-5$-15
3$10$-25$-15$10$5'''
class Game :
def __init__(self):
self.m_cur = {1:["Military",50]}
self.c_cur = {1:["People's",50]}
self.r_cur = {1:["Research",50]}
self.i_cur = {1:["Industrial",50]}
self.p_cur = {1:["Research",50]}
#function to clear all widgets on screen when called
def clear(self):
for widget in root.winfo_children():
widget.destroy()
#function to quit the window
def exit(self):
msg = messagebox.askquestion("Thank you for playing","Are you sure you want to exit?")
if msg == "yes" :
root.destroy()
else:
Game.main(self)
#start function
def start(self):
Label(root,text="Hello, what should we call you?",font=("segoe print",20)).grid(row=0,column=0)
name = Entry(root,width=20)
name.grid(row=1,column=0)
Button(root,text="Enter",font=("segoe print",20),command=lambda: Game.main(self)).grid(row=1,column=1)
self.name=name.get()
#main function
def main(self):
Game.clear(self)
Label(root,text="Welcome to the game",font=("segoe print",20)).grid(row=0,column=0)
Label(root,text='What do you want to do?',font=("segoe print",20)).grid(row=1,column=0)
Button(root,text="Start Game",font=("segoe print",20),command=lambda: Game.qn_func(self,1)).grid(row=2,column=0)
Button(root,text="Exit Game",font=("segoe print",20),command=lambda: Game.exit(self)).grid(row=3,column=0)
#function to check variables and display game over
def game_over(self,x_cur):
if x_cur[1][1]<=0 or x_cur[1][1]>=100 : #condition to check game over
Game.clear(self)
Label(root,text=x_cur)
Label(root,text="GAME OVER",font=("ariel",20)).place(relx=0.5,rely=0.5,anchor=CENTER)
Button(root,text="Continue",font=("segoe print",20),command=lambda: Game.main(self)).place(relx=0.5,rely=0.6)
#function to display question and variables
def qn_func(self,qn_num) :
Game.clear(self)
#accessing the questions
q_file = StringIO(qn)
#reading the question, options, next qn numbers and the character name from the file
qn_list = q_file.readlines()
qn = qn_list[qn_num-1].strip().split("$")[1]
char_name = qn_list[qn_num-1].strip().split("$")[2]
qn1 = qn_list[qn_num-1].strip().split("$")[3]
qn2 = qn_list[qn_num-1].strip().split("$")[5]
n_qn1 = int(qn_list[qn_num-1].strip().split("$")[4])
n_qn2 = int(qn_list[qn_num-1].strip().split("$")[6])
#displaying the character name and the question as a label frame widget with character name as parent
label_frame = LabelFrame(root,text = char_name,font = ("segoe print",20))
label = Label(label_frame,text = qn,font = ("segoe print",20))
label_frame.place(relx=0.5,rely=0.5,anchor=CENTER)
label.pack()
q_file.close()
#accessing variables
v_file = StringIO(var)
#reading values of variables from file
v_list = v_file.readlines()
self.r_cur[1][1] += int(v_list[qn_num-1].strip().split("$")[1])
self.c_cur[1][1] += int(v_list[qn_num-1].strip().split("$")[2])
self.i_cur[1][1] += int(v_list[qn_num-1].strip().split("$")[3])
self.m_cur[1][1] += int(v_list[qn_num-1].strip().split("$")[4])
self.p_cur[1][1] += int(v_list[qn_num-1].strip().split("$")[5])
#running each variable through game_over to see if you are dead
Game.game_over(self,self.r_cur)
Game.game_over(self,self.c_cur)
Game.game_over(self,self.i_cur)
Game.game_over(self,self.m_cur)
Game.game_over(self,self.p_cur)
#defining the Doublevar variables
s_var1 = DoubleVar()
s_var2 = DoubleVar()
s_var3 = DoubleVar()
s_var4 = DoubleVar()
s_var5 = DoubleVar()
#setting the values in the scales
s_var1.set(self.r_cur[1][1])
s_var2.set(self.c_cur[1][1])
s_var3.set(self.i_cur[1][1])
s_var4.set(self.m_cur[1][1])
s_var5.set(self.p_cur[1][1])
#variables as scale widgets
scale1 = Scale(root,from_=100,to=0,orient=VERTICAL,sliderlength=10,variable=s_var1)
scale2 = Scale(root,from_=100,to=0,orient=VERTICAL,sliderlength=10,variable=s_var2)
scale3 = Scale(root,from_=100,to=0,orient=VERTICAL,sliderlength=10,variable=s_var3)
scale4 = Scale(root,from_=100,to=0,orient=VERTICAL,sliderlength=10,variable=s_var4)
scale5 = Scale(root,from_=100,to=0,orient=VERTICAL,sliderlength=10,variable=s_var5)
#displaying the scale widgets on the screen
scale1.grid(row=0,column=0)
scale2.grid(row=0,column=1)
scale3.grid(row=0,column=2)
scale4.grid(row=0,column=3)
scale5.grid(row=0,column=4)
#disabling the scales
scale1.config(state=DISABLED)
scale2.config(state=DISABLED)
scale3.config(state=DISABLED)
scale4.config(state=DISABLED)
scale5.config(state=DISABLED)
v_file.close()
#displaying the buttons on the screen
Button(root,text=qn1,command=lambda: Game.qn_func(self,n_qn1)).place(relx=0.2,rely=0.7,anchor=W,width=200,height=50)
Button(root,text=qn2,command=lambda: Game.qn_func(self,n_qn2)).place(relx=0.8,rely=0.7,anchor=E,width=200,height=50)
game = Game()
game.start()
root.mainloop()
You can see in this particular section that you have called on 'qn' before it was even defined:
#function to display question and variables
def qn_func(self,qn_num) :
Game.clear(self)
#accessing the questions
q_file = StringIO(qn)
#reading the question, options, next qn numbers and the character name from the file
qn_list = q_file.readlines()
qn = qn_list[qn_num-1].strip().split("$")[1]
The variable needs to be assigned a value before being used. Here, you call q_file = StringIO(qn) before you have defined qn = qn_list....

How do I determine what checkbuttons selected when created dynamically?

I am creating a custom file chooser in tkinter. I am creating a grid of checkbuttons representing files in a directory. Right now all i want to do is get a list of the file names a user chooses. As of now my code displays the gui nicely but when I try to determine what boxes the user checked it's not working. I'm not sure what I'm doing wrong. Most likely in the way i'm setting the variable for the checkbutton. I know this would be easy for a python pro but i'm not a pro so any help would be greatly appreciated. See my code below. Apologies ahead of time for the huge amount of code but i'm not sure where i'm going wrong so i put it all in.
Mark
class scareGUI:
def __init__(self, master):
self.selectedFileName = StringVar()
#filter non video file types
includes = ['*.mp4','*.py']
includes = r'|'.join([fnmatch.translate(x) for x in includes])
#master.attributes('-zoomed', True)
self.frame_header = ttk.Frame(master)
self.frame_header.pack()
ttk.Label(self.frame_header, text="TerrorForm ScareBox").grid(row=0, column = 0, rowspan = 2)
self.frame_files = ttk.Frame(master)
self.frame_files.pack()
self.frame_footer = ttk.Frame(master)
self.frame_footer.pack()
#pull file names from file system
for root, dirs, self.files in os.walk('./movies'):
self.files = [os.path.join(root, f) for f in self.files]
self.files = [f for f in self.files if re.match(includes, f)]
#Determine number of rows in grid
numfiles = len(self.files)
dividesBy = False
numRows = IntVar()
numColumns = 4
while (dividesBy == False):
if(numfiles % numColumns == 0):
numRows=int(numfiles/numColumns)
dividesBy = True
else:
numfiles+=1
#Print Check Boxes in Grid layout
filmIcon = PhotoImage(file='tf_film_icon.gif')
i=0
self.checkedFiles=[None]*len(self.files)
for r in range(numRows):
for c in range(4):
if (i<len(self.files)):
self.checkedFiles[i] = IntVar()
checkbutton = ttk.Checkbutton(self.frame_files, text=self.files[i], variable=self.checkedFiles[i])
checkbutton.config(image = filmIcon,compound = TOP)
checkbutton.image = filmIcon
checkbutton.grid(row = r, column = c)
i += 1
def getChosenFiles(self):
self.chosenFiles=[]
for x in range(len(self.files)):
if(self.checkedFiles[x].get()):
self.chosenFiles.append(self.files[x])
print (self.chosenFiles[0])
return self.chosenFiles
def main():
root = Tk()
scaregui = scareGUI(root)
root.mainloop()
if __name__ == "__main__": main()

Categories

Resources