how to delete a specific item in the list after a button is clicked in tkinter python - python-3.x

Below is a small code where if you click add button a pop-up will appear where you write desired number. The number in the bottom represents the sum of all numbers you entered.
What I am trying to achieve is to update the sum_lbl and index_no as I delete any of the labels.
Code:
from tkinter import *
root = Tk()
root.geometry('400x400')
add_room_area_var= StringVar(None)
area_lst = []
index_no = 0
def destroy(widget):
widget.destroy()
def add_():
add_room_area = Toplevel(root)
add_room_area.title('Add Room area')
add_room_area.wm_minsize(200, 50)
add_room_area.resizable(False, False)
add_room_area.transient(root)
add_r_area_frame = LabelFrame(add_room_area, text=' Room area ', labelanchor=N)
add_r_area_frame.config(padx=3, pady=3)
add_r_area_frame.pack(fill=X, padx=10, pady=10)
add_r_area_entry = Entry(add_r_area_frame, textvariable=add_room_area_var)
add_r_area_entry.pack(fill=X)
add_r_area_entry.focus_set()
while True:
def ok_():
global index_no
name = add_room_area_var.get()
index_no += 1
entry_frame = Frame(root)
index_lbl = Label(entry_frame, text=index_no)
add_room_lbl = Label(entry_frame, text=name, width=12, bg='gray30', fg='white', pady=5)
close_button = Button(entry_frame, text='X', command=lambda:destroy(entry_frame))
entry_frame.pack(anchor=N, padx=1)
index_lbl.pack(side=LEFT, padx=3)
add_room_lbl.pack(fill=X, side=LEFT)
close_button.pack(side=RIGHT)
area_lst.append(int(name))
add_room_area.destroy()
area_sum = sum(area_lst)
sum_lbl.config(text=area_sum)
break
ok_button = Button(add_room_area, text='Ok', command=ok_)
ok_button.pack()
btn = Button(root, text='Add', command=add_)
btn.pack()
sum_lbl = Label(root, font=25)
sum_lbl.pack(side=BOTTOM, pady=15)
root.mainloop()
Output:
After deleting the 3rd and 4th label the output is:

I would suggest to change area_lst to dictionary using the frame as the key and the two labels as the value for each row.
Then update destroy() to use area_lst to update the total and indexes:
from tkinter import *
root = Tk()
root.geometry('400x400')
add_room_area_var= StringVar(None)
area_lst = {} # dictionary to hold labels of each row using frame as the key
def destroy(frame):
frame.destroy()
del area_lst[frame]
update_total()
# update index of remaining rows
for idx, (lbl, _) in enumerate(area_lst.values(), 1):
lbl['text'] = idx
# function to update the total label
def update_total():
area_sum = sum(int(room['text']) for _, room in area_lst.values())
sum_lbl.config(text=area_sum)
def add_():
add_room_area = Toplevel(root)
add_room_area.title('Add Room area')
add_room_area.wm_minsize(200, 50)
add_room_area.resizable(False, False)
add_room_area.transient(root)
add_r_area_frame = LabelFrame(add_room_area, text=' Room area ', labelanchor=N)
add_r_area_frame.config(padx=3, pady=3)
add_r_area_frame.pack(fill=X, padx=10, pady=10)
add_r_area_entry = Entry(add_r_area_frame, textvariable=add_room_area_var)
add_r_area_entry.pack(fill=X)
add_r_area_entry.focus_set()
def ok_():
name = add_room_area_var.get()
entry_frame = Frame(root)
index_lbl = Label(entry_frame, text=len(area_lst)+1)
add_room_lbl = Label(entry_frame, text=name, width=12, bg='gray30', fg='white', pady=5)
close_button = Button(entry_frame, text='X', command=lambda:destroy(entry_frame))
entry_frame.pack(anchor=N, padx=1)
index_lbl.pack(side=LEFT, padx=3)
add_room_lbl.pack(fill=X, side=LEFT)
close_button.pack(side=RIGHT)
# store current row to area_lst
area_lst[entry_frame] = (index_lbl, add_room_lbl)
add_room_area.destroy()
update_total()
ok_button = Button(add_room_area, text='Ok', command=ok_)
ok_button.pack()
btn = Button(root, text='Add', command=add_)
btn.pack()
sum_lbl = Label(root, font=25)
sum_lbl.pack(side=BOTTOM, pady=15)
root.mainloop()

You can allow buttons to call multiple commands, so for your 'close_button' button, I added two more commands: remove the name from 'area_lst' and update the 'sum_lbl' text with the new sum for 'area_lst'
Like this:
from tkinter import *
root = Tk()
root.geometry('400x400')
add_room_area_var= StringVar(None)
area_lst = []
index_no = 0
def destroy(widget):
widget.destroy()
def add_():
add_room_area = Toplevel(root)
add_room_area.title('Add Room area')
add_room_area.wm_minsize(200, 50)
add_room_area.resizable(False, False)
add_room_area.transient(root)
add_r_area_frame = LabelFrame(add_room_area, text=' Room area ', labelanchor=N)
add_r_area_frame.config(padx=3, pady=3)
add_r_area_frame.pack(fill=X, padx=10, pady=10)
add_r_area_entry = Entry(add_r_area_frame, textvariable=add_room_area_var)
add_r_area_entry.pack(fill=X)
add_r_area_entry.focus_set()
while True:
def ok_():
global index_no
name = add_room_area_var.get()
index_no += 1
entry_frame = Frame(root)
index_lbl = Label(entry_frame, text=index_no)
add_room_lbl = Label(entry_frame, text=name, width=12, bg='gray30', fg='white', pady=5)
close_button = Button(entry_frame, text='X', command=lambda:[destroy(entry_frame), area_lst.remove(int(name)), sum_lbl.config(text=sum(area_lst))])
entry_frame.pack(anchor=N, padx=1)
index_lbl.pack(side=LEFT, padx=3)
add_room_lbl.pack(fill=X, side=LEFT)
close_button.pack(side=RIGHT)
area_lst.append(int(name))
add_room_area.destroy()
area_sum = sum(area_lst)
sum_lbl.config(text=area_sum)
break
ok_button = Button(add_room_area, text='Ok', command=ok_)
ok_button.pack()
btn = Button(root, text='Add', command=add_)
btn.pack()
sum_lbl = Label(root, font=25)
sum_lbl.pack(side=BOTTOM, pady=15)
root.mainloop()

Related

Problem with askopenfilename() sending to converting function and saving file using asksavefile() - Python Tkinter

I wrote a CAD coordinate conversion application that reads a .txt file using filedialok.askopenfilename() using the function read_file_click().
After selecting the appropriate scale in the Combobox, the program converts the file using the convert() function, then saves it to a .txt file after calling the function save_file_click().
The problem is that when I send the returned value from the convert function to the save_file_click() function, I get two notifications about opening the file.
I don't know how to correct this error. I tried using global variables, but it doesn't help, and weak errors appears with the data_list_no_head variable. Thanks for help:)
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
import os
root = Tk()
root.title("Autocad Coordinate Converter")
root.geometry("")
root.geometry("280x320")
root.resizable(False, False)
def combo_sets():
scale_combo.set("")
def ending_message():
messagebox.showinfo("Autocad Coordinate Converter", "End")
def read_file_click():
global data_list_no_head
file_path = filedialog.askopenfilename()
return file_path
def convert():
file_path_new = read_file_click()
data_list = []
with open(file_path_new, encoding='utf-16') as file:
for line in file:
data_list.append(line.split())
data_list_no_head = data_list[4:]
return data_list_no_head
def save_file_click():
new = convert()
scale_get = scale_combo.get()
data = None
event_eng = None
cal = None
x_coordinate = None
y_coordinate = None
output_file = open(output_file_path_name, 'a')
if scale_get == "1:500" or scale_get == "1:1000":
for event in new:
for _ in event:
data = event[1]
event_eng = event[4]
x_coordinate = event[5]
y_coordinate = event[6]
cal = int(event_eng[-1])*2-2
output_file.write(f"_layer u w{data[2:4]}e{event_eng[-1]} _donut 0 {cal} {y_coordinate},"
f"{x_coordinate} \n")
output_file.close()
new_file_name = output_file_path_name[:-4] + ".scr.txt"
os.rename(output_file_path_name, new_file_name)
combo_sets()
ending_message()
elif scale_get == "1:2000":
for event in new:
for _ in event:
data = event[1]
event_eng = event[4]
x_coordinate = event[5]
y_coordinate = event[6]
cal = 2*(int(event_eng[-1])*2-2)
output_file.write(f"_layer u w{data[2:4]}e{event_eng[-1]} _donut 0 {cal} {y_coordinate},"
f"{x_coordinate} \n")
output_file.close()
new_file_name = output_file_path_name[:-4] + ".scr.txt"
os.rename(output_file_path_name, new_file_name)
combo_sets()
ending_message()
elif scale_get == "1:5000":
for event in new:
for _ in event:
data = event[1]
event_eng = event[4]
x_coordinate = event[5]
y_coordinate = event[6]
cal = 5*(int(event_eng[-1])*2-2)
output_file.write(f"_layer u w{data[2:4]}e{event_eng[-1]} _donut 0 {cal} {y_coordinate},"
f"{x_coordinate} \n")
output_file.close()
new_file_name = output_file_path_name[:-4] + ".scr.txt"
os.rename(output_file_path_name, new_file_name)
combo_sets()
ending_message()
elif scale_get == "1:10000":
for event in new:
for _ in event:
data = event[1]
event_eng = event[4]
x_coordinate = event[5]
y_coordinate = event[6]
cal = 20*(int(event_eng[-1])-2)
output_file.write(f"_layer u w{data[2:4]}e{event_eng[-1]} _donut 0 {cal} {y_coordinate},"
f"{x_coordinate} \n")
output_file.close()
new_file_name = output_file_path_name[:-4] + ".scr.txt"
os.rename(output_file_path_name, new_file_name)
combo_sets()
ending_message()
# Frame1
frame1 = LabelFrame(root, padx=15, pady=15, relief=FLAT)
frame1.grid(row=1, column=0)
button_1 = Button(frame1, text="Read .txt file", padx=15, pady=15, width=20, height=1, command=read_file_click)
button_1.grid(row=1, column=0, padx=3, pady=3)
# Frame2
frame2 = LabelFrame(root, padx=15, pady=15, relief=FLAT)
frame2.grid(row=2, column=0)
Label(frame2, text="Select scale:", width=14).grid(row=1, column=1, padx=1, pady=1)
scale_combo = ttk.Combobox(frame2, values=["1:500", "1:1000", "1:2000", "1:5000", "1:10000"], width=9, state='readonly')
scale_combo.current()
scale_combo.grid(row=2, column=1, padx=1, pady=1)
# Frame3
frame3 = LabelFrame(root, padx=50, pady=50, relief=FLAT)
frame3.grid(row=3, column=0)
button_2 = Button(frame3, text="Save file in CAD format", padx=15, pady=15, width=20, height=1,
command=save_file_click)
button_2.grid(row=0, column=0, padx=3, pady=3)
root.mainloop()

How to get Get value of check button in python tkinter library?

I've created a travel form in which a user will submit name, city, gender, phone number etc. Also, I've created a check button so that a user wants a meal he can tick on the check button.
My Question is How to get values of the Check button if the user has ticked the meal query written in the code.
Can anyone explain to me the logic on how to get the value of the Check button if the user has ticked on it?
from tkinter import *
root = Tk()
root.geometry('800x800')
def b():
print('Name is', namevalue.get()),
print('Phone number is', phonevalue.get())
print('Gender is', gendervalue.get()),
print('Extra Phone number is', phone1value.get()),
print('City is', cityvalue.get())
print('Food is required', )
f1 = Frame(root, bg = 'red', borderwidth = 8, relief = SUNKEN)
f1.grid()
Label(f1, text = 'Welcome to travel agency', pady = 5).grid(row = 0, column = 3)
#Making Widgets or we may call headers
name = Label(root, text = 'name')
phone = Label(root, text = 'Phone')
gender = Label(root, text = 'Enter your gender')
phone1 = Label(root, text = 'Extra Number')
city = Label(root, text = 'Your City')
name.grid(row = 1,column = 0)
phone.grid(row = 2,column = 0)
gender.grid(row = 3, column = 0)
phone1.grid(row = 4, column = 0)
city.grid(row = 5, column = 0)
#Assigining the headers a variable type
namevalue = StringVar()
phonevalue = StringVar()
gendervalue = StringVar()
phone1value = StringVar()
cityvalue = StringVar()
foodservicevalue = IntVar()
nameentry = Entry(root, textvariable = namevalue)
phoneentry = Entry(root, textvariable = phonevalue)
genderentry = Entry(root, textvariable = gendervalue)
cityentry = Entry(root, textvariable = cityvalue)
phone1entry = Entry(root, textvariable = phone1value)
nameentry.grid(row = 1, column = 3)
phoneentry.grid(row = 2, column = 3)
genderentry.grid(row = 3, column = 3)
phone1entry.grid(row = 4, column = 3)
cityentry.grid(row = 5, column = 3)
#Creating Check Button checkbutton
foodservicevalue = Checkbutton(text ='Do you wan\'t any meals', variable = foodservicevalue)
foodservicevalue.grid(row = 6, column = 3, padx = 1)
#Button and packing with assiginn
Button(text = 'Submit', command = b).grid(row = 7, column = 3)
root.mainloop()
This code works:
from tkinter import *
root = Tk()
root.geometry('800x800')
def b():
print('Name is', namevalue.get()),
print('Phone number is', phonevalue.get())
print('Gender is', gendervalue.get()),
print('Extra Phone number is', phone1value.get()),
print('City is', cityvalue.get())
if food_required.get() == 1:
print("Food is required.")
elif food_required.get() == 0:
print("Food is not required.")
# When the check button is clicked, then the value is 1 and it can be get using the .get() function.
# Similarly when the check button is not clicked then the value is 0.
f1 = Frame(root, bg='red', borderwidth=8, relief=SUNKEN)
f1.grid()
Label(f1, text='Welcome to travel agency', pady=5).grid(row=0, column=3)
# Making Widgets or we may call headers
name = Label(root, text='name')
phone = Label(root, text='Phone')
gender = Label(root, text='Enter your gender')
phone1 = Label(root, text='Extra Number')
city = Label(root, text='Your City')
name.grid(row=1, column=0)
phone.grid(row=2, column=0)
gender.grid(row=3, column=0)
phone1.grid(row=4, column=0)
city.grid(row=5, column=0)
# Assigining the headers a variable type
namevalue = StringVar()
phonevalue = StringVar()
gendervalue = StringVar()
phone1value = StringVar()
cityvalue = StringVar()
food_required = IntVar()
nameentry = Entry(root, textvariable=namevalue)
phoneentry = Entry(root, textvariable=phonevalue)
genderentry = Entry(root, textvariable=gendervalue)
cityentry = Entry(root, textvariable=cityvalue)
phone1entry = Entry(root, textvariable=phone1value)
nameentry.grid(row=1, column=3)
phoneentry.grid(row=2, column=3)
genderentry.grid(row=3, column=3)
phone1entry.grid(row=4, column=3)
cityentry.grid(row=5, column=3)
# Creating Check Button #cHECKBUTTON
foodservicevalue = Checkbutton(text='Do you wan\'t any meals', variable=food_required)
foodservicevalue.grid(row=6, column=3, padx=1)
# Button and packing with assiginn
Button(text='Submit', command=b).grid(row=7, column=3)
root.mainloop()
When I saw your code, I found that you have used the variable foodservicevalue as an IntVar() and Checkbutton. I have used the if else statements to fix your issue.
This is #AmeyVijeesh's code but I removed the StringVars:
from tkinter import *
def b():
print("Name is", nameentry.get()),
print("Phone number is", phoneentry.get())
print("Gender is", genderentry.get()),
print("Extra Phone number is", phone1entry.get()),
print("City is", cityentry.get())
if food_required.get() == 1:
print("Food is required.")
elif food_required.get() == 0:
print("Food is not required.")
root = Tk()
root.geometry("800x800")
f1 = Frame(root, bg="red", borderwidth=8, relief="sunken")
f1.grid()
label = Label(f1, text="Welcome to travel agency", pady=5)
label.grid(row=0, column=3)
# Making Widgets or we may call headers
name = Label(root, text="Name")
phone = Label(root, text="Phone")
gender = Label(root, text="Enter your gender")
phone1 = Label(root, text="Extra Number")
city = Label(root, text="Your City")
name.grid(row=1, column=0)
phone.grid(row=2, column=0)
gender.grid(row=3, column=0)
phone1.grid(row=4, column=0)
city.grid(row=5, column=0)
# Assigining the headers a variable type
food_required = IntVar()
nameentry = Entry(root)
phoneentry = Entry(root)
genderentry = Entry(root)
cityentry = Entry(root)
phone1entry = Entry(root)
nameentry.grid(row=1, column=3)
phoneentry.grid(row=2, column=3)
genderentry.grid(row=3, column=3)
phone1entry.grid(row=4, column=3)
cityentry.grid(row=5, column=3)
# Creating Check Button #cHECKBUTTON
foodservicevalue = Checkbutton(text="Do you want any meals", variable=food_required)
foodservicevalue.grid(row=6, column=3, padx=1)
# Button and packing with assiginn
button = Button(text="Submit", command=b)
button.grid(row=7, column=3)
root.mainloop()
Using <tkinter.Entry>.get() is much simpler than creating StringVars and assigning them to the <tkinter.Entry>s

Is it possible to grab input from the topview tkinter window and retrieve saved entry field value from within master tk window

The program is made up of classes and I am trying to use a tkinter topview from within a function so that when it's called it is able to retrieve the entryfield value to the master class
from tkinter import
from PIL import Image, ImageTk
Below is the driver code handling the transitioning from one class to another
class SeaofBTCapp(Tk):
def __init__(self, *args, **kwargs):
Tk.__init__(self, *args, **kwargs)
container = Frame(self)
container.pack(side="top", fill="both", expand=True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (
WelcomePage, Register_new_user): # ,PageThree,PageFour):
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(WelcomePage)
# def show_frame(self, cont):
# frame = self.frames[cont]
# frame.tkraise()
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
frame.update()
frame.event_generate("<<show_frame>>")
def get_page(self, cont):
for page in self.frames.values():
if str(page.__class__.__name__) == cont:
return page
return None
class Register_new_user(object):
pass
Below is the entry point of the program and is the first page to be displayed
class WelcomePage(Frame):
def __init__(self, parent, controller):
Frame.__init__(self, parent)
# self.bind("<<show_frame>>", self.main_prog)
def resize_image(event):
global photo
new_width = event.width
new_height = event.height
image = copy_of_image.resize((new_width, new_height))
photo = ImageTk.PhotoImage(image)
label.config(image=photo)
label.image = photo # avoid garbage collection
def pin_input():
top = Toplevel()
top.geometry("180x100")
top.title("toplevel")
l2 = Label(top, text="This is toplevel window")
global entry_1
global password
password = StringVar
entry_1 = None
def cleartxtfield():
global password
new = "3"
password.set(new)
# ############# Function to parse for only numerical input
def validate(input):
if input.isdigit():
return True
elif input == "":
return True
else:
return False
def enternumber(x):
global entry_1
setval = StringVar()
setval = str(x)
# print(setval)
entry_1.insert(END, setval)
entry_1 = Entry(top, textvariable=password, width=64, show='*')
entry_1.place(x=200, y=100)
entry_1.focus()
reg = top.register(validate)
entry_1.config(validate="key", validatecommand=(reg, '%P'))
def getcreds():
# check if four digit entered and is not empty
global passwd
passwd = password.get()
print(f"The Credentials are {passwd}")
def funcbackspace():
length = len(entry_1.get())
entry_1.delete(length - 1, 'end')
def killwindow():
# when the user quits it should clear all the data input fields filled in in the previous steps. and should display information that it is about to quit in a few seconds
command = top.destroy()
# Label(top,text="Goodbye\n (Closing in 2 seconds)")
top.after(2000, top.quit())
cancel = Button(top, width=8, height=3, text="Cancel", bg="red", fg="black", command=killwindow)
cancel.place(x=220, y=150)
backspace = Button(top, width=8, height=3, text="Backspace", bg="red", fg="black", command=funcbackspace)
backspace.place(x=500, y=150)
# ----number Buttons------
def enternumber(x):
global entry_1
setval = StringVar()
setval = str(x)
# print(setval)
entry_1.insert(END, setval)
btn_numbers = []
for i in range(10):
btn_numbers.append(
Button(top, width=8, height=3, text=str(i), bd=6, command=lambda x=i: enternumber(x)))
btn_text = 1
for i in range(0, 3):
for j in range(0, 3):
btn_numbers[btn_text].place(x=220 + j * 140, y=250 + i * 100)
btn_text += 1
btn_zero = Button(top, width=15, height=2, text='0', bd=5, command=lambda x=0: enternumber(x))
btn_zero.place(x=330, y=550)
clear = Button(top, text="Clear", bg="green", fg="white", width=8, height=3, command=cleartxtfield)
clear.place(x=220, y=550)
okbtn = Button(top, text="Enter", bg="green", fg="black", width=8, height=3, command=getcreds)
okbtn.place(x=500, y=550)
val = getcreds()
print("The value to be returned is %s" % val)
return val
password = pin_input()
print("Gotten password is %s" % password)
copy_of_image = Image.open("image.png")
photoimage = ImageTk.PhotoImage(copy_of_image)
label = Label(self, image=photoimage)
label.place(x=0, y=0, relwidth=1, relheight=1)
label.bind('<Configure>', resize_image)
top_left_frame = Frame(self, relief='groove', borderwidth=2)
top_left_frame.place(relx=1, rely=0.1, anchor=NE)
center_frame = Frame(self, relief='raised', borderwidth=2)
center_frame.place(relx=0.5, rely=0.75, anchor=CENTER)
Button(top_left_frame, text='REGISTER', bg='grey', width=14, height=1,
command=lambda: controller.show_frame(Register_new_user)).pack()
Button(center_frame, text='ENTER', fg='white', bg='green', width=13, height=2,
command=lambda: controller.show_frame(Register_new_user)).pack()
if __name__ == '__main__':
app = SeaofBTCapp()
app.title("Password return on topview window")
width = 1000
height = 700
screenwidth = app.winfo_screenwidth()
screenheight = app.winfo_screenheight()
alignstr = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)
app.geometry(alignstr)
# app.resizable(width=False, height=False)
app.resizable(width=True, height=True)
app.mainloop()
If I understand this correctly you want to enter a password in a dialog and then get the password from the dialog when you close it.
Have a look at Dialog Windows at effbot for a discussion about creating dialog windows.
Here is an example of how you can implement a simple dialog:
from tkinter import *
from tkinter import simpledialog
class MyDialog(simpledialog.Dialog):
def body(self, master):
'''create dialog body.
return widget that should have initial focus.
This method should be overridden, and is called
by the __init__ method.'''
Label(master, text='Value:').grid(row=0)
self.e1 = Entry(master)
self.e1.grid(row=0, column=1)
return self.e1 # initial focus
def apply(self):
'''process the data
This method is called automatically to process the data, *after*
the dialog is destroyed. By default, it does nothing.'''
value = self.e1.get()
self.result = value
def validate(self):
'''validate the data
This method is called automatically to validate the data before the
dialog is destroyed. By default, it always validates OK.'''
return 1 # override
def buttonbox(self):
'''add standard button box.
override if you do not want the standard buttons
'''
box = Frame(self)
w = Button(box, text="OK", width=10, command=self.ok, default='active')
w.pack(side='left', padx=5, pady=5)
w = Button(box, text="Cancel", width=10, command=self.cancel)
w.pack(side='left', padx=5, pady=5)
self.bind("<Return>", self.ok)
self.bind("<Escape>", self.cancel)
box.pack()
if __name__ == '__main__':
root = Tk()
root.geometry('200x100+800+50')
def do():
d = MyDialog(root)
print(d.result)
b = Button(root, text='Go!', width=10, command=do)
b.pack(expand=True)
Did that answer your question?

Return value from text entry to some other class

I am trying to get return values from tkinter window where i am entering text values,I want those text values to be returned so that I can capture those and send as input to other class methods.
I am able to print those captured values but not able to return them. I am very new to python
from tkinter import *
class gui_cls:
def __init__(self,*args):
self.master=args[0]
self.delete = StringVar()
self.insert = StringVar()
self.var1 = IntVar()
self.var3 = IntVar()
def vergui(self):
Delete = self.delete.get()
insertversions = self.insert.get()
prog = self.var1.get()
print(Delete)
print(insertversions)
if prog:
print("levels")
else:
pass
label_0 = Label(self.master, text="Adaptive", width=20, font=("bold", 20))
label_0.place(x=40, y=53)
label_1 = Label(self.master, text="Delete Versions", width=20, font=("bold", 10))
label_1.place(x=30, y=130)
entry_1 = Entry(root, textvar=self.delete)
entry_1.place(x=200, y=130)
label_2 = Label(self.master, text="Insert Versions", width=20, font=("bold", 10))
label_2.place(x=30, y=180)
entry_2 = Entry(self.master, textvar=self.insert)
entry_2.place(x=200, y=180)
label_3 = Label(self.master, text="Reload", width=20, font=("bold", 10))
label_3.place(x=30, y=230)
var2 = IntVar()
Checkbutton(self.master, text="Levels", padx=5, variable=self.var1).place(x=190, y=230)
Checkbutton(self.master, text="Accounts", padx=20, variable=var2).place(x=250, y=230)
label_4 = Label(self.master, text="Note: Please seperate versions by comma(,)", fg='red', font=("bold", 13)).place(x=30, y=280)
Button(self.master, text='Finish', width=20, bg='brown', fg='white', command=self.vergui).place(x=200, y=350)
root = Tk()
root.geometry('400x400')
root.title("Adaptive")
gui_cls(root).vergui()
root.mainloop()
Current you created an instance of the class on the fly. You can first define a variable for the instance of the class, and then call the methods separately:
#gui_cls(root).vergui()
gui = gui_cls(root)
gui.vergui()
Then you can access the class attributes anytime.
print (gui.delete.get())
print (gui.var1.get())
...

unable to close the tkinter after using destroy()

Using tkinter window to get some user parameter and stored in dictionary, after the "SAVE" button pressed. But the tkinter is not closing in console..
How to close the tkinter after receiving the data...
import tkinter as tk
riskparams = {}
This is the simplified function with reproduce the issue here
def setriskmgmtparams():
risk = tk.Tk()
risk.title("Risk Management System")
w = 650
h = 450
ws = risk.winfo_screenwidth()
hs = risk.winfo_screenheight()
x = ws - w
y = hs - h
risk.geometry('%dx%d+%d+%d' % (w, h, x, y))
def savedata(*event):
global riskparams
riskparams['MaxQty'] = int(MQ_box.get())
#Setting Price % Range, if any not correct reset to defaults 7%
riskparams['PriceLowRange'] = float(pricerange1.get())/100
riskparams['PriceHighRange'] = float(pricerange2.get())/100
riskparams['MaxOrderVal'] = int(maxorderval.get())
riskparams['Norderpsec'] = int(norderval.get())
riskparams['MaxTurnover'] = int(maxturnover.get())
risk.destroy()
print(" TTAPI | RMS checks has been set ")
return
rows = 0
while rows < 11:
risk.rowconfigure(rows, weight=1)
risk.columnconfigure(rows, weight=1)
rows +=1
orderlevel = tk.Label(risk, text="RMS CHECKS PARAMS by API")
orderlevel.grid(row=0, column=1, sticky='NESW')
MaxQuantity = tk.Label(risk, text="Max Quantity per order:")
MaxQuantity.grid(row=1, column=1, sticky='E')
mqvar = tk.StringVar(risk, value='100000')
MQ_box = tk.Entry(risk, textvariable=mqvar)
MQ_box.bind("<Return>", savedata)
MQ_box.grid(row=1, column=2, sticky='W')
#price range
price1 = tk.Label(risk, text="Price Range % LOW:")
price1.grid(row=2, column=1, sticky='E')
pricevar1 = tk.StringVar(risk, value='-10')
pricerange1 = tk.Entry(risk, textvariable=pricevar1)
pricerange1.bind('<Return>', savedata)
pricerange1.grid(row=2, column=2, sticky='W')
price2 = tk.Label(risk, text="Price Range % HIGH:")
price2.grid(row=3, column=1, sticky='E')
pricevar2 = tk.StringVar(risk, value='10')
pricerange2 = tk.Entry(risk, textvariable=pricevar2)
pricerange2.bind('<Return>', savedata)
pricerange2.grid(row=3, column=2, sticky='W')
ordval = tk.Label(risk, text="Max Order Value per order :")
ordval.grid(row=4, column=1, sticky='E')
mxordval = tk.StringVar(risk, value='2000000')
maxorderval = tk.Entry(risk, textvariable=mxordval)
maxorderval.bind('<Return>', savedata)
maxorderval.grid(row=4, column=2, sticky='W')
norders = tk.Label(risk, text="No Orders allowed per Second/Client :")
norders.grid(row=5, column=1, sticky='E')
nordval = tk.StringVar(risk, value='2')
norderval = tk.Entry(risk, textvariable=nordval)
norderval.bind('<Return>', savedata)
norderval.grid(row=5, column=2, sticky='W')
maxturn = tk.Label(risk, text="Max TurnOver per day/Client :")
maxturn.grid(row=6, column=1, sticky='E')
maxturnval = tk.StringVar(risk, value='10000000')
maxturnover = tk.Entry(risk, textvariable=maxturnval)
maxturnover.bind('<Return>', savedata)
maxturnover.grid(row=6, column=2, sticky='W')
savebtn = tk.Button(risk,
text='SAVE',
bg = "yellow",
command=savedata)
savebtn.bind('<Return>', savedata)
savebtn.grid(row=8, column=2, sticky='NESW')
#Run the app
risk.mainloop()
Calling the function
But the tkinter window closes and loop not closed, how to close the loop
setriskmgmtparams()

Resources