unable to close the tkinter after using destroy() - python-3.x

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

Related

Python/tkinter - change entry status via checkbox

I want to activate the second entry when the checkbox is checked...but the it works the other way around. What am I doing wrong? Based on another question I have posted it seems the event "<ButtonRelease>" occurs before the bonding. Why is that? Can I use "command" in the checkbox instaed?
import tkinter as tk
def set_entry_status(event, var, widg):
print(var.get())
if var.get():
widg[-1]['state'] = 'normal'
else:
widg[-1]['state'] = 'disabled'
def CustomWidget(frame, name, unit, ):
var_e = []
widget_e = []
var_c = tk.IntVar(master=frame, value=0)
widget_c = tk.Checkbutton(master=frame, text='', variable=var_c)
widget_c.grid(row=0, column=0, columnspan=1, padx=5, pady=5, sticky="ns")
label_l = name + " (" + unit + ")" # nome + unità di misura in parentesi per GUI
widget_l = tk.Label(frame, text=label_l, padx=1, pady=1)
widget_l.grid(row=0, column=1, columnspan=1, padx=5, pady=5, sticky="wns")
var_e.append(tk.StringVar(master=frame, value='A'))
widget_e.append(tk.Entry(frame, textvariable=var_e[-1], width=10, state="normal"))
widget_e[-1].grid(row=0, column=2, columnspan=1, padx=5, pady=5, sticky="ns")
var_e.append(tk.StringVar(master=frame, value='B'))
widget_e.append(tk.Entry(frame, textvariable=var_e[-1], width=10, state="normal"))
widget_e[-1].grid(row=0, column=3, columnspan=1, padx=5, pady=5, sticky="ns")
# set initial entry state
if var_c.get():
widget_e[-1]['state'] = 'normal'
else:
widget_e[-1]['state'] = 'disabled'
# checkbox - binding
widget_c.bind("<ButtonRelease>", lambda event: set_entry_status(event, var_c, widget_e))
root = tk.Tk()
root.title('My Window')
CustomWidget(root, 'name', 'unit')
root.mainloop()
Indeed you can use command kwarg like I suggested in my other answer. In that case event must be removed from the arguments of your callback function:
import tkinter as tk
def set_entry_status(var, widg):
print(var.get())
if var.get():
widg[-1]['state'] = 'normal'
else:
widg[-1]['state'] = 'disabled'
def CustomWidget(frame, name, unit, ):
var_e = []
widget_e = []
var_c = tk.IntVar(master=frame, value=0)
widget_c = tk.Checkbutton(master=frame, text='', variable=var_c, command=lambda: set_entry_status(var_c, widget_e))
widget_c.grid(row=0, column=0, columnspan=1, padx=5, pady=5, sticky="ns")
label_l = name + " (" + unit + ")" # nome + unità di misura in parentesi per GUI
widget_l = tk.Label(frame, text=label_l, padx=1, pady=1)
widget_l.grid(row=0, column=1, columnspan=1, padx=5, pady=5, sticky="wns")
var_e.append(tk.StringVar(master=frame, value='A'))
widget_e.append(tk.Entry(frame, textvariable=var_e[-1], width=10, state="normal"))
widget_e[-1].grid(row=0, column=2, columnspan=1, padx=5, pady=5, sticky="ns")
var_e.append(tk.StringVar(master=frame, value='B'))
widget_e.append(tk.Entry(frame, textvariable=var_e[-1], width=10, state="normal"))
widget_e[-1].grid(row=0, column=3, columnspan=1, padx=5, pady=5, sticky="ns")
# set initial entry state
if var_c.get():
widget_e[-1]['state'] = 'normal'
else:
widget_e[-1]['state'] = 'disabled'
root = tk.Tk()
root.title('My Window')
CustomWidget(root, 'name', 'unit')
root.mainloop()

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

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

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)

How Can I write Python code for Temperature Convert to C orF using Frames, Entry Box and Label?

from tkinter import*
def convert2c():
try:
f = float(tempIN.get())
c = (f-32)*5.0/9.0
tempOUTc.set(c)
except ValueError:
pass
def convert2f():
try:
c = float(tempIN.get())
f = c*9.0/5.0 + 32
tempOUTf.set(f)
except ValueError:
pass
root = Tk()
f = root
root.title("Temperature Converter")
root.geometry('{}x{}'.format(500,200))
topFrm = Frame(root, width=500, height=80, bg="#e01111")
midFrm = Frame(root, width=500, height=150, bg="#795fb5")
btmFrm = Frame(root, width=500, height=100)
btmL = Frame(btmFrm, width=250, height=100, bg="#4117a5")
btmR = Frame(btmFrm, width=250, height=100, bg="#3f454f")
topFrm.grid(row=0, sticky="W")
midFrm.grid(row=1)
btmFrm.grid(row=3)
btmL.grid(row=2, column=0)
btmR.grid(row=2, column=2)
tempIN = StringVar()
tempOUTc = StringVar()
tempOUTf = StringVar()
Label(f, text="Temperature Converter\n A number in temperature degree is converted into another as one of the button is clicked").grid(column=0, row=0)
Label(f, text="Enter a Temperature").grid(column=0, row=1)
Entry(f, textvariable=tempIN, width=10) .grid(column=0, rowspan=1, row=1, sticky=W)
Button(f, text=" to Celsius", command=convert2c) .grid(column=0, row=3, sticky=W)
Button(f, text=" to Fahrenheit", command=convert2f) .grid(column=1, row=3, sticky=W)
Label(f, textvariable=tempOUTc) .grid(column=2, row=1, sticky=W)
Label(f, textvariable=tempOUTf) .grid(column=2, row=2, sticky=W)
root.mainloop()

Resources