How to get Get value of check button in python tkinter library? - python-3.x

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

Related

Column span not working properly in Tkinter

I'm a python beginner and as the part of my course I am supposed to code a password generator. But I am facing some issues regarding columnspan.
Here is the code:
from tkinter import *
window = Tk()
window.title("Password Generator...")
window.config(padx=50, pady=50)
logo_path = "logo.png"
image_holder = Canvas(width=200, height=200)
logo_image = PhotoImage(file=logo_path)
image_holder.create_image(100, 100, image=logo_image)
image_holder.grid(column=1, row=0)
# labels
website = Label(text="Website :")
website.grid(row=1, column=0)
email = Label(text="Email/username :")
email.grid(row=2, column=0)
password = Label(text="Password :")
password.grid(row=3, column=0)
# entry
website_entry = Entry(width=45)
website_entry.grid(row=1, column=1,columnspan=2)
email_entry = Entry(width=45)
email_entry.grid(row=2, column=1,columnspan=2)
password_entry = Entry(width=21)
password_entry.grid(row=3,column=1,sticky="ew")
#buttons
genrate_password = Button(text="Generate Password")
genrate_password.grid(row=3, column=2,sticky="ew")
add_button = Button(text="Add",width=40)
add_button.grid(row=4, column=1,columnspan=2)
window.mainloop()
and here is how it is supposed to look like :
here is my result :
How can I move the entry next to password label a little bit right so that it can match the positioning of above two entries.
Thank You...
You can add sticky="ew" to all the entry boxes and buttons to get the desired output. Also I would suggest to put the logo at column 0 with columnspan=3, so it does put it at the center.
from tkinter import *
window = Tk()
window.title("Password Generator...")
window.config(padx=50, pady=50)
logo_path = "images/mypass.png"
image_holder = Canvas(width=200, height=200)
logo_image = PhotoImage(file=logo_path)
image_holder.create_image(100, 100, image=logo_image)
# put at column 0 with columnspan=3 instead
image_holder.grid(column=0, row=0, columnspan=3)
# labels
website = Label(text="Website :")
website.grid(row=1, column=0)
email = Label(text="Email/username :")
email.grid(row=2, column=0)
password = Label(text="Password :")
password.grid(row=3, column=0)
# entry
website_entry = Entry(width=45)
website_entry.grid(row=1, column=1,columnspan=2,sticky="ew") # added sticky
email_entry = Entry(width=45)
email_entry.grid(row=2, column=1,columnspan=2,sticky="ew") # added sticky
password_entry = Entry(width=21)
password_entry.grid(row=3,column=1,sticky="ew") # added sticky
#buttons
genrate_password = Button(text="Generate Password")
genrate_password.grid(row=3, column=2,sticky="ew") # added sticky
add_button = Button(text="Add",width=40)
add_button.grid(row=4, column=1,columnspan=2,sticky="ew") # added sticky
window.mainloop()
Result:
If you want some paddings between those widgets, you can add padx and pady options as well:
from tkinter import *
window = Tk()
window.title("Password Generator...")
window.config(padx=50, pady=50)
logo_path = "images/mypass.png"
image_holder = Canvas(width=200, height=200)
logo_image = PhotoImage(file=logo_path)
image_holder.create_image(100, 100, image=logo_image)
image_holder.grid(column=0, row=0, columnspan=3)
# labels
website = Label(text="Website :")
website.grid(row=1, column=0)
email = Label(text="Email/username :")
email.grid(row=2, column=0)
password = Label(text="Password :")
password.grid(row=3, column=0)
# entry
website_entry = Entry(width=45)
website_entry.grid(row=1, column=1,columnspan=2,sticky="ew",padx=5,pady=3) # added padx and pady
email_entry = Entry(width=45)
email_entry.grid(row=2, column=1,columnspan=2,sticky="ew",padx=5,pady=3) # added padx and pady
password_entry = Entry(width=21)
password_entry.grid(row=3,column=1,sticky="ew",padx=5,pady=3) # added padx and pady
#buttons
genrate_password = Button(text="Generate Password")
genrate_password.grid(row=3, column=2,sticky="ew",padx=5,pady=3) # added padx and pady
add_button = Button(text="Add",width=40)
add_button.grid(row=4, column=1,columnspan=2,sticky="ew",padx=5,pady=3) # added padx and pady
window.mainloop()
Result:

how to delete a specific item in the list after a button is clicked in tkinter python

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()

Scrollbar for Dynamically Created Widgets - Python Tkinter [duplicate]

This question already has answers here:
Adding a scrollbar to a group of widgets in Tkinter
(3 answers)
Closed 3 years ago.
I have a GUI that dynamically generates widgets based on the user selected number of systems:
GUI
These widgets are generated using a Callback function like the below sample of code:
class Window():
def __init__(self, master):
master.title('Production Analysis Tool')
# callback function to create entry boxes based on number of systems
self.L0 = Label(root, text="Equipment Parameters:", font = ('TKDefaultFont', 9, 'bold'))
self.L0.grid(row=3,column=0, sticky=W)
inverter_file = r'F:\CORP\PROJECTS\07599-A_Solar Development\Screening\_Production Analysis Tool\User Inputs\Inverter_Data.csv'
module_file = r'F:\CORP\PROJECTS\07599-A_Solar Development\Screening\_Production Analysis Tool\User Inputs\Module_Data.csv'
def update_scroll_region(event):
canvas.configure(scrollregion=canvas.bbox("all"))
def callback(*args):
dynamic_widgets = Frame(canvas)
canvas.create_window(0,0, anchor='nw', window = dynamic_widgets)
self.system_size = int(self.system_size_raw.get())
# Inverter Type
self.Lblank = Label(dynamic_widgets, text = "").grid(row=8, column=1, sticky=W)
self.L3 = Label(dynamic_widgets, text = "Inverter Type")
self.L3.grid(row=9, column=1, sticky=W)
global inverter_types # declare array as global parameter so it can be accessed outside function
inverter_types = []
for i in range(self.system_size):
inverter_list = get_inverter_list(inverter_file)
inverter_list = ["Select"] + inverter_list
self.inverter_types_raw = StringVar()
self.L3a = Label(dynamic_widgets, text = "System {}".format(i+1), font = ('Calibri', 10,'italic'))
self.L3a.grid(row=10+i, column=1, sticky=E)
self.widget = OptionMenu(dynamic_widgets, self.inverter_types_raw, *inverter_list, command = get_values_0)
self.widget.grid(row=10+i, column=2,sticky=EW)
inverter_types.append(self.widget)
dynamic_widgets.bind("<Configure>", update_scroll_region)
global inv_type
inv_type = []
def get_values_0(value):
inv_type.append(value)
button = tk.Button(root, text = "Store Values", font=('Calibri', 10,'italic'), bg = "SlateGray3",command = lambda:[gget_values_0()])
button.grid(row = 61, column = 2, columnspan=8, sticky = 'nesw')
# System Type
self.L1 = Label(root, text = "System Type")
self.L1.grid(row=4, column=1, sticky=W)
self.sys_type_raw = StringVar(root)
types = ['Select', 'Central Inverter', 'String Inverters']
self.popupMenu6 = OptionMenu(root, self.sys_type_raw, *types)
self.popupMenu6.grid(row=4, column=2, sticky=EW)
# Number of Systems
self.L2 = Label(root, text = "Number of Systems")
self.L2.grid(row=6, column=1, sticky=W)
self.system_size_raw = IntVar(root)
choices = list(range(1,50))
self.popupMenu2 = OptionMenu(root, self.system_size_raw, *choices)
self.popupMenu2.grid(row=6, column=2, sticky=EW)
self.system_size_raw.trace("w", callback)
vsb = Scrollbar(root, orient="vertical")
vsb.grid(row=8, column=6, sticky = 'ns')
canvas = Canvas(root, width = 600, height = 200)
vsb.config(command = canvas.yview)
canvas.configure(yscrollcommand=vsb.set)
canvas.grid(row=8,column=0)
# SITE ORIENTATION
self.L12 = Label(root, text="Site Orientation:", font = ('TKDefaultFont', 9, 'bold'))
self.L12.grid(row=66, column=0, sticky=W)
self.L13 = Label(root, text = "Module Tilt Angle (degrees)")
self.L13.grid(row=67, column=1, sticky=W)
self.modtilt_raw = Entry(master)
self.modtilt_raw.grid(row=67, column=2, sticky=EW)
self.L14 = Label(root, text = "Array Azimuth (degrees)")
self.L14.grid(row=68, column=1, sticky=W)
self.arraytilt_raw = Entry(master)
self.arraytilt_raw.grid(row=68, column=2, sticky=EW)
# SUBMIT INFORMATION
self.L27 = Label(root, text=" ").grid(row=84,column=1) # Add row of space
self.cbutton = tk.Button(root, text="SUBMIT",command = self.store_user_inputs, bg = "SlateGray3")
self.cbutton.grid(row=85, column = 0, columnspan=8, sticky = 'ew')
# STORE USER INPUT
def store_user_inputs(self):
self.system_size = np.float(self.system_size_raw.get())
# save all inputs as global parameters so they can be accessed as variables outside of GUI
global params
params = [self.system_type]
root = Tk()
root.configure()
window = Window(root)
root.mainloop()
I would like to place the dynamically generated widgets (Inverter Type, Modules per String, Strings per Inverter, Inverters per System, Module Type, and Max Current per System) into a scrollable frame.
I can post more code if needed.
A scrollable frame can be created by creating a Frame widget on a Canvas. An example is as follows:
vsb = Scrollbar(root, orient = VERTICAL)
vsb.pack(fill=Y, side = RIGHT, expand = FALSE)
canvas = Canvas(root, yscrollcommand=vsb.set)
canvas.pack(side=LEFT, fill=BOTH, expand=TRUE)
vsb.config(command = canvas.yview)
canvas.config(scrollregion = canvas.bbox("all"))
InverterType = Frame(canvas)
canvas.create_window(0, 0, anchor = NW, window = InverterType)
Now make sure to add all the widgets created in the callback function to this InverterType frame.
(TIP - replace root with InverterType)

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()

How to edit information in tkinter

I'm trying to write a code to get the name, salary, and age and show it in a list. I want this code have the feature of deleteing and editing the information.
But in this step I don't know how delete or edit a particular information.
from tkinter import *
from tkinter import messagebox
from tkinter.ttk import *
i = 2
table_row = []
def getting():
global i
i = i + 1
data = []
var = IntVar()
c = Checkbutton(window, variable=var)
c.val = var
data.append(c)
c.grid(row=i, column=0)
value1=e11.get()
data.append(value1)
value2 = e22.get()
data.append(value2)
value3 = e33.get()
data.append(value3)
lblq = Label(window, text=data[1:])
lblq.grid(row=i, column=1)
table_row.append(data)
# print(table_row)
def delete_row():
for Noo, row in reversed(list(enumerate(table_row))):
if row[0].val.get() == 1:
for i in row:
i.destroy()
table_row(Noo)
window = Tk()
window.title("Table with add, edit and delete")
window.geometry('600x600')
def Closing():
res = messagebox.askokcancel("warning", "Are You sure!!!!!")
if res == True:
sys.exit()
############################################### #menu inside winodow
menu = Menu(window)
new_item = Menu(menu)
new_item.add_command(label="Exit", command=Closing)
menu.add_cascade(label='File', menu=new_item)
window.config(menu=menu)
###############################################
lblname =Label(window, text="Name")
lblname.place(x = 440,y = 130)
e11 = Entry(window, width=20)
e11.place(x = 440,y = 150)
lblsurname =Label(window, text="Salary")
lblsurname.place(x = 440,y = 180)
e22 = Entry(window, width=20)
e22.place(x = 440,y = 200)
lblage =Label(window, text="Age")
lblage.place(x = 440,y = 240)
e33 = Entry(window, width=20)
e33.place(x = 440,y = 260)
dl = Button(window, text='Delete',command=delete_row)
dl.place(x = 440,y = 10)
dl = Button(window, text='Edit')
dl.place(x = 440,y = 50)
B2 = Button(window, text="+ add emplyoee", command=getting)
B2.place(x = 440,y = 90)
v0 = StringVar()
e0 = Entry(window, textvariable=v0, state='readonly')
v0.set('Select')
e0.grid(row=1, column=0)
v1 = StringVar()
e1 = Entry(window, textvariable=v1, state='readonly')
v1.set('Information')
e1.grid(row=1, column=1)
window.mainloop()
Maybe I should use Class in my code, but I is difficult for me to use Class and tkinter simultaneously
You could use dictionary to keep single row - it would be more readable
When I add row I create dictionary with widgets and text from Entry, I add to list of rows and clear Entry.
If there is selected row in table then I don't create new row but replace text in selected row.
The same way I search selected row to copy text from row to Entry.
The same way I search selected row to remove row - destroy widgets and delete row on the list.
It is more easier to do it because I use dictionary to keep row and it is more readable.
from tkinter import *
from tkinter import messagebox
from tkinter.ttk import *
# --- functions ---
def closing():
res = messagebox.askokcancel("warning", "Are You sure!!!!!")
if res == True:
sys.exit()
def add_row():
global row_number
# check if there is selected row to update
update = None
for row in table_row:
if row['var'].get() == 1:
update = row
break # dont search next selected row
if update:
row['data'] = [e11.get(), e22.get(), e33.get()]
row['label']['text'] = row['data']
else:
row_number += 1
row = dict()
row['row_number'] = row_number
row['var'] = IntVar()
row['checkbutton'] = Checkbutton(window, variable=row['var'])
row['checkbutton'].grid(row=row_number, column=0)
row['data'] = [e11.get(), e22.get(), e33.get()]
row['label'] = Label(window, text=row['data'])
row['label'].grid(row=row_number, column=1)
table_row.append(row)
# clear entry
e11.delete('0', 'end')
e22.delete('0', 'end')
e33.delete('0', 'end')
lblnumber["text"] = "Row number: -"
def delete_row():
for row in reversed(table_row):
if row['var'].get() == 1:
# remove widgets
row['checkbutton'].destroy()
row['label'].destroy()
# remove row from list
del row
def edit_row():
for row in table_row:
if row['var'].get() == 1:
# remove all text
e11.delete('0', 'end')
e22.delete('0', 'end')
e33.delete('0', 'end')
# put text from row
e11.insert('end', row['data'][0])
e22.insert('end', row['data'][1])
e33.insert('end', row['data'][2])
lblnumber["text"] = "Row number: {}".format(row['row_number'])
break # dont search next selected row
# --- main ---
row_number = 2
table_row = []
window = Tk()
window.title("Table with add, edit and delete")
window.geometry('600x600')
menu = Menu(window)
new_item = Menu(menu)
new_item.add_command(label="Exit", command=closing)
menu.add_cascade(label='File', menu=new_item)
window.config(menu=menu)
lblnumber = Label(window, text="Row Number: -")
lblnumber.place(x=440, y=330)
e00 = Label(window, width=20)
e00.place(x=440, y=150)
lblname = Label(window, text="Name")
lblname.place(x=440, y=130)
e11 = Entry(window, width=20)
e11.place(x=440, y=150)
lblsurname = Label(window, text="Salary")
lblsurname.place(x=440, y=180)
e22 = Entry(window, width=20)
e22.place(x=440, y=200)
lblage = Label(window, text="Age")
lblage.place(x=440, y=240)
e33 = Entry(window, width=20)
e33.place(x=440, y=260)
dl = Button(window, text='Delete', command=delete_row)
dl.place(x=440, y=10)
dl = Button(window, text='Edit', command=edit_row)
dl.place(x=440, y=50)
B2 = Button(window, text="+ add emplyoee", command=add_row)
B2.place(x=440, y=90)
v0 = StringVar()
e0 = Entry(window, textvariable=v0, state='readonly')
v0.set('Select')
e0.grid(row=1, column=0)
v1 = StringVar()
e1 = Entry(window, textvariable=v1, state='readonly')
v1.set('Information')
e1.grid(row=1, column=1)
window.mainloop()

Resources