Inserting "Entry" boxes based on user input in TKinter - python

Newbie here, I am working on a small Python project and it requires to accept a numerical input from user and upon a button click it should insert that number of rows - entry boxes - for further input collection. Is it possible to do it in a loop and how? I tried it in a loop but is inserting only first row.
label_6.place(x=0,y=320)
total_participants = tk.Entry(root, width="5", textvariable=StringVar())
total_participants.place(x=150,y=320)
def action():
num_participants = int(total_participants.get())
coordinate = 400
first_name_label = Label(root, text="First Name",width=20,font=("bold", 11))
first_name_label.place(x=0,y=coordinate)
second_name_label = Label(root, text="Second Name",width=20,font=("bold", 11))
second_name_label.place(x=150,y=coordinate)
email_label = Label(root, text="Email ID",width=20,font=("bold", 11))
email_label.place(x=300, y =coordinate )
first_name = []
second_name = []
email_id = []
for i in range(1, num_participants + 1):
fn[i] = Entry(root, width="15").place(x=40,y=coordinate + 40)
sn[i] = Entry(root, width="15").place(x=190,y=coordinate + 40)
em[i] = Entry(root, width="40").place(x=340,y=coordinate + 40)
label_8 = Button(root, text="Participants Details",font=("bold", 13), command = participant_details)
label_8.place(x=30,y=360)

Related

Tkinter - Wait for several inputs before calculating the results

I am new to tkinter and python in general. I am trying to create a window that allows the user to input information (based on Entry and dropdown menus) and based on their choices, some new input will show up which will then be used to calculate the results. I've tried making a minimum reproducible snippet of code, as the original code is quite long.
The problem is that in the buttons I don't understand which command to include so that the program waits for all input before executing the rest of the code. Now it seems that no matter what I include it goes directly to the result part of the code.
I've tried having a function that saves the input and calculates the result as the command for the button, but it still does not wait.
The wait_variable as far as I understood only works for one variable?
import tkinter as tk
root = tk.Tk()
root.geometry("1500x800")
Intro_Label = tk.Label(root, text = "Welcome")
Intro_Label.grid(row=0, column=0)
entry_1 = tk.Entry()
entry_1.insert(0, 2.5) #default value
Label_1 = tk.Label(root, text="Input 1")
Label_1.grid(row=2, column=0)
entry_1.grid(row=2, column=1)
Label_2 = tk.Label(root, text="Input 2 ")
#Options for dropdown menu for transport method
I2_clicked = tk.StringVar()
I2_clicked.set("Choose from dropdown menu")
input2_opt = ["a", "b"]
input2 = tk.OptionMenu( root , I2_clicked , *input2_opt )
Label_3 = tk.Label(root, text="Input 2 ")
#Options for dropdown menu for transport method
I3_clicked = tk.StringVar()
I3_clicked.set("Choose from dropdown menu")
input3_opt = ["x", "y"]
input3 = tk.OptionMenu( root , I3_clicked , *input3_opt )
Label_2.grid(row=3, column=0)
input2.grid(row=3, column=1)
Label_3.grid(row=3, column =3)
input3.grid(row=3, column = 4)
def input_calculations():
first_input = entry_1.get()
if I2_clicked.get() == "a":
if I3_clicked.get() == "x":
entry_4 = tk.Entry()
Label_4 = tk.Label(root, text="Input for x|a")
entry_4.insert(0, 5) #dummy default value
entry_4.grid(row = 4, column = 1 )
Label_4.grid(row = 4, column = 0)
entry_5 = tk.Entry()
Label_5 = tk.Label(root, text="Second input for x|a")
entry_5.insert(0, 4) #dummy default value
entry_5.grid(row = 4, column = 4)
Label_5.grid(row = 4, column = 3)
#wait for both inputs before executing the calculations
save_button = tk.Button(root, text ="Calculate results", command= )
save_button.grid(row = 5, column = 6)
#calculate some results
result = float(entry_4.get())* float(entry_5.get())
elif I3_clicked.get() == "y":
entry_6 = tk.Entry()
Label_6 = tk.Label(root, text="Input for y|a")
entry_6.insert(0, 6) #dummy default value
entry_6.grid(row = 4, column = 1 )
Label_6.grid(row = 4, column = 0)
entry_7 = tk.Entry()
Label_7 = tk.Label(root, text="Second input for y|a")
entry_7.insert(0, 7) #dummy default value
entry_7.grid(row = 4, column = 4)
Label_7.grid(row = 4, column = 3)
entry_8 = tk.Entry()
Label_8 = tk.Label(root, text="Third input for y|a")
entry_8.insert(0, 8) #dummy default value
entry_8.grid(row = 4, column = 6)
Label_8.grid(row = 4, column = 5)
save_button = tk.Button(root, text ="Calculate results", command= )
save_button.grid(row = 5, column = 6)
#wait for input before executing the next lines - what to insert here ??
result = float(entry_6.get()) / float(entry_7.get()) * float(entry_8.get())
#continues for all combinations (b and y, b and x) - different inputs, different calculations for each combo
return result
btn = tk.Button(root, text="Confirm", width=15,command=input_calculations)
btn.grid(row= 10, column= 5)
root.mainloop()
You could link the buttons to functions that do the calculations.
Example function:
def button_pressed():
result = float(entry_6.get()) / float(entry_7.get()) * float(entry_8.get())
You could either pass the entries as arguments in a lambda, or make the whole program inside of a class. This way every method can access all of the widgets.
For your save button you would then need to add the function to the command parameter:
save_button = tk.Button(root, text ="Calculate results", command=button_pressed)
You could make multiple functions / methods if you use a class to do the steps you need.

How to insert values created by a loop function to tkinter text boxes which are also created automatically with a loop function

Hi I'm trying to write a code that calculates the net present values of the installments. The code runs perfect up to a point where I can't insert the calculated values in to the tkinter text boxes individually.
For example the code is asking the yearly interest rate and the input can be 15. The list price of an house can be 1000000 and the down payment can be 0.2 which is %20 of the list price. And we can input 12 as the number of installments.
Down payment will be calculated by multiplying 1000000 with 0.2 and gives 200000. And the execution will be inserted to the first tkinter text box. But when the calculation done for the net present values of the installments, all of them appear inside last tkinter text box rather than appearing individually.
Here is the code;
# This program is to create a payment schedule for the customers and check whether
# the payment plan is suitable for the seller in terms of net present value.
from tkinter import *
window=Tk()
# This part asks the number of installments and creates the desired amount of text boxes.
def create():
for y in range(number_of_installments.get()):
t11 = Label(window,text= '%s.Installment'%(y+1),foreground="green")
t11.grid(row = y+2,column=0)
for y in range(number_of_installments.get()):
ttt = Text(window, height=1, width=20, foreground="red")
ttt.grid(row = y+2,column=1)
#Net present values of the installments are calculated in this part.
def NPV_calculation():
interest_rate = [pow(1+0.0125,i) for i in range(1,int(number_of_installments.get())+1)]
installment_amount = (float(list_price.get())-(float(list_price.get())*float(downpayment_percentage.get())))/(float(number_of_installments.get()))
calculation = [installment_amount/i for i in interest_rate]
ttt.insert(END,calculation)
downpayment_calculation()
NPV_calculation()
#Downpayment calculated by entering a value between 0 to 1. For example if 0.2 is typed in the textbox it will multiply the list price by %20.
def downpayment_calculation():
Downpayment = float(list_price.get())*float(downpayment_percentage.get())
t0.insert(END,Downpayment)
#Entry boxes
number_of_installments = IntVar(value="")
installment = Entry(window, textvariable=number_of_installments)
installment.grid(row=3,column=3)
interest_value = StringVar()
interest = Entry(window, textvariable=interest_value)
interest.grid(row=0,column=3)
list_price = StringVar()
list = Entry(window, textvariable=list_price)
list.grid(row=1,column=3)
downpayment_percentage = StringVar()
downpayment = Entry(window, textvariable=downpayment_percentage)
downpayment.grid(row=2,column=3)
#Create button for creating number of grids based on the number of installments.
b1 = Button(window, text="Create", command=create)
b1.grid(row=0,column=4)
#Labels for the enrty boxes
n_installments = Label(window,text="Number Of Installments",foreground="blue")
n_installments.grid(row=3,column=2)
yearly_interest = Label(window,text="Yearly Interest",foreground="blue")
yearly_interest.grid(row=0,column=2)
price_list = Label(window,text="List Price",foreground="blue")
price_list.grid(row=1,column=2)
per_downpayment = Label(window,text="Downpayment Percentage",foreground="blue")
per_downpayment.grid(row=2,column=2)
#Label and text box for the downpayment
t0 = Label(window,text="Downpayment",foreground="green")
t0.grid(row=1,column=0)
t0 = Text(window, height=1, width=20, foreground="red")
t0.grid(row=1,column=1)
window.mainloop()
When you call the NPV_calculation function, ttt is the last text widget.
# This part asks the number of installments and creates the desired amount of text boxes.
def create():
for y in range(number_of_installments.get()):
t11 = Label(window,text= '%s.Installment'%(y+1),foreground="green")
t11.grid(row = y+2,column=0)
for y in range(number_of_installments.get()):
ttt = Text(window, height=1, width=20, foreground="red")
ttt.grid(row = y+2,column=1)
print("the object named ttt in this loop iteration is:", ttt)
#Net present values of the installments are calculated in this part.
def NPV_calculation():
interest_rate = [pow(1+0.0125,i) for i in range(1,int(number_of_installments.get())+1)]
installment_amount = (float(list_price.get())-(float(list_price.get())*float(downpayment_percentage.get())))/(float(number_of_installments.get()))
calculation = [installment_amount/i for i in interest_rate]
ttt.insert(END,calculation)
print("the object named ttt is:", ttt)
downpayment_calculation()
NPV_calculation() # <- when you call this function, ttt is the last Text widget
Output for number_of_installments = 3:
the object named ttt in this loop iteration is: .!text2
the object named ttt in this loop iteration is: .!text3
the object named ttt in this loop iteration is: .!text4
the object named ttt is: .!text4
You need to insert values when creating a text widget in a loop. It is better to move the NPV_calculation function out of the loop.
This is a simplified example for the part where the values are generated automatically.
import tkinter as tk
window = tk.Tk()
def do_n_calculation(n):
calculation = [x+1 for x in range(n)]
return calculation
def create():
# get new values
n = number_of_installments.get()
calculation_list = do_n_calculation(n)
# clear previous values
for i in installment_frame.winfo_children():
i.destroy()
# insert new values
for y in range(n):
t11 = tk.Label(installment_frame, text= '%s.Installment'%(y+1), foreground="green")
t11.grid(row=y, column=0)
for y in range(n):
ttt = tk.Text(installment_frame, height=1, width=20, foreground="red")
ttt.grid(row=y, column=1)
ttt.insert(tk.END, calculation_list[y])
label = tk.Label(window, text="Number Of Installments")
label.grid(row=0, column=0)
number_of_installments = tk.IntVar(value="")
entry = tk.Entry(window, textvariable=number_of_installments)
entry.grid(row=0, column=1)
button = tk.Button(window, text="Create", command=create)
button.grid(row=0, column=2)
installment_frame = tk.Frame(window)
installment_frame.grid(row=1, column=0)
window.mainloop()
Complete example using the class.
import tkinter as tk
class Application(tk.Frame):
"""
| column 0 | column 1 |
-----------------------------------------
row 0 | downpayment_frame | form_frame |
-----------------------------------------
row 1 | installment_frame | |
-----------------------------------------
"""
def __init__(self, master):
super().__init__(master)
# data attributes
self.downpayment_value = None
self.calculation_list = None
# left side
# Label and text box for the downpayment
self.downpayment_frame = tk.Frame(self)
self.downpayment_frame.grid(row=0, column=0, padx=5, pady=5)
self.downpayment_label = tk.Label(self.downpayment_frame, text="Downpayment", foreground="green")
self.downpayment_label.grid(row=0, column=0)
self.downpayment_text = tk.Text(self.downpayment_frame, height=1, width=20, foreground="red")
self.downpayment_text.grid(row=0, column=1)
self.installment_frame = tk.Frame(self)
self.installment_frame.grid(row=1, column=0, padx=5, pady=5)
# right side
self.form_frame = tk.Frame(self)
self.form_frame.grid(row=0, column=1, padx=5, pady=5)
# Labels for the enrty boxes
self.yearly_interest = tk.Label(self.form_frame, text="Yearly Interest", foreground="blue")
self.yearly_interest.grid(row=0, column=0)
self.price_list = tk.Label(self.form_frame, text="List Price", foreground="blue")
self.price_list.grid(row=1, column=0)
self.per_downpayment = tk.Label(self.form_frame, text="Downpayment Percentage", foreground="blue")
self.per_downpayment.grid(row=2, column=0)
self.n_installments = tk.Label(self.form_frame, text="Number Of Installments", foreground="blue")
self.n_installments.grid(row=3, column=0)
# Entry boxes
self.interest_value = tk.StringVar()
self.interest = tk.Entry(self.form_frame, textvariable=self.interest_value)
self.interest.grid(row=0, column=1)
self.list_price = tk.StringVar()
self.price = tk.Entry(self.form_frame, textvariable=self.list_price)
self.price.grid(row=1, column=1)
self.downpayment_percentage = tk.StringVar()
self.downpayment = tk.Entry(self.form_frame, textvariable=self.downpayment_percentage)
self.downpayment.grid(row=2, column=1)
self.number_of_installments = tk.IntVar(value="")
self.installment = tk.Entry(self.form_frame, textvariable=self.number_of_installments)
self.installment.grid(row=3, column=1)
# Create button for creating number of grids based on the number of installments.
self.create_button = tk.Button(self.form_frame, text="Create", command=self.create)
self.create_button.grid(row=0, column=2, rowspan=4, padx=[5, 0])
# Net present values of the installments are calculated in this part.
def NPV_calculation(self, number, list_price, percentage):
interest_rate = [pow(1+0.0125,i) for i in range(1,int(number)+1)]
installment_amount = (float(list_price)-(float(list_price)*float(percentage)))/(float(number))
calculation = [installment_amount/i for i in interest_rate]
return calculation
def downpayment_calculation(self, list_price, percentage):
downpayment = float(list_price)*float(percentage)
return downpayment
def create(self):
number = self.number_of_installments.get()
list_price = self.list_price.get()
percentage = self.downpayment_percentage.get()
# get new values and set data attributes
self.downpayment_value = self.downpayment_calculation(list_price, percentage)
self.calculation_list = self.NPV_calculation(number, list_price, percentage)
# clear previous values
self.downpayment_text.delete("1.0", tk.END)
for i in self.installment_frame.winfo_children():
i.destroy()
# insert new values
self.downpayment_text.insert(tk.END, self.downpayment_value)
for y in range(number):
label = tk.Label(self.installment_frame,text= '%s.Installment'%(y+1), foreground="green")
label.grid(row=y, column=0)
for y in range(number):
text = tk.Text(self.installment_frame, height=1, width=20, foreground="red")
text.grid(row=y, column=1)
text.insert(tk.END, self.calculation_list[y])
self.get_calculation()
def get_calculation(self):
print(self.downpayment_value)
print(self.calculation_list)
root = tk.Tk()
app = Application(master=root)
app.pack()
app.mainloop()

How do I get a output into a tkinter Entry field

Im making my own cypher encryption and I want to put the result into the entry field called output. Now im just using print() so I could test if I got a result. But that was only for testing. This is one of the first times I used Python so if there are some other things I could have done better please let me know :)
this is what I have so far.
from tkinter import *
#Make frame
root = Tk()
root.geometry("500x300")
root.title("Encryption Tool")
top_frame = Frame(root)
bottom_frame = Frame(root)
top_frame.pack()
bottom_frame.pack()
#Text
headline = Label(top_frame, text="Encryption Tool", fg='black')
headline.config(font=('Courier', 27))
headline.grid(padx=10, pady=10)
Key = Label(bottom_frame, text="Key:", fg='black')
Key.config(font=('Courier', 20))
Key.grid(row=1)
Text_entry = Label(bottom_frame, text="Text:", fg='black')
Text_entry.config(font=('Courier', 20))
Text_entry.grid(row=2)
Output_text = Label(bottom_frame, text="Output:", fg='black')
Output_text.config(font=('Courier', 20))
Output_text.grid(row=3)
Key_entry = Entry(bottom_frame)
Key_entry.grid(row=1, column=1)
Text_entry = Entry(bottom_frame)
Text_entry.grid(row=2, column=1)
Output_text = Entry(bottom_frame)
Output_text.grid(row=3, column=1)
#Encryption_button
def encrypt():
result = ''
text = ''
key = Key_entry.get()
text = Text_entry.get()
formule = int(key)
for i in range(0, len(text)):
result = result + chr(ord(text[i]) + formule + i * i)
result = ''
Encryption_button = Button(bottom_frame, text="Encrypt", fg='black')
Encryption_button.config(height = 2, width = 15)
Encryption_button.grid(row = 4, column = 0, sticky = S)
Encryption_button['command'] = encrypt
#Decryption_button
def decrypt():
result = ''
text = ''
key = Key_entry.get()
text = Text_entry.get()
formule = int(key)
for i in range(0, len(text)):
result = result + chr(ord(text[i]) - formule - i * i)
print(result)
result = ''
Decryption_button = Button(bottom_frame, text="Decrypt", fg="black")
Decryption_button.config(height = 2, width = 15)
Decryption_button.grid(row = 5, column = 0, sticky = S)
Decryption_button['command'] = decrypt
#Quit_button
def end():
exit()
Quit_button = Button(bottom_frame, text="Quit", fg='black')
Quit_button.config(height = 2, width = 15)
Quit_button.grid(row = 6, column = 0, sticky = S)
Quit_button['command'] = end
root.mainloop()
The most common way to do this with tkinter would be with a StringVar() object you can connect to the Entry object (Some documentation here).
output_entry_value = StringVar()
Output_text = Entry(bottom_frame, textvariable=output_entry_value)
Output_text.grid(row=3, column=1)
then you can .set() the result in the stringvar, and it will update in the entries you connected it to:
output_entry_value.set(result)

Creating Tkinter Text boxes and inserting into a dictionary

I have a long chunk of code. I do not want to paste it all here, so let me explain what I am trying to accomplish here. Based on a number provided by the user I want to create that many text boxes and then get what is entered into that text box and insert that into the dictionary. I have tried this a few ways and just cannot get it to work correctly. The list is either empty or it only contains the last text box as the value for each key.
def multiple_choice():
def add():
top.destroy()
top = Tk()
top.title("Add Question")
w = 800
h = 800
ws = top.winfo_screenwidth()
hs = top.winfo_screenheight()
x = (ws/2) - (w/2)
y = (hs/2) - (h/2)
top.geometry('%dx%d+%d+%d' % (w, h, x, y))
question = Label(top, text="Question to be asked?", font = "Times 14 bold", fg = "blue")
question.grid(row = 2, column = 4)
questionText = Text(top, borderwidth = 5, width=50,height=5, wrap=WORD, background = 'grey')
questionText.grid(row = 3, column = 4)
numQuestions = Label(top, text = "Number of answer choices?", font = "Times 14 bold", fg = "blue")
numQuestions.grid(row = 4, column=4)
num = Entry(top, bd = 5)
num.grid(row=5, column = 4)
answerList = {}
def multiple():
def preview():
preview = Tk()
top.title("Question Preview")
w = 500
h = 500
ws = top.winfo_screenwidth()
hs = top.winfo_screenheight()
x = (ws/2) - (w/2)
y = (hs/2) - (h/2)
top.geometry('%dx%d+%d+%d' % (w, h, x, y))
title = Label(preview, text = "Short Answer Question Preview", font = "Times 18 bold", fg = "blue" )
title.grid(row = 0, column = 2)
qtext = "Question text will read: "
ques = Label(preview, text = qtext)
ques.grid(row=1, column = 2)
ques2 = Label( preview, text = questionText.get("1.0",END))
let = 'A'
i = 1
for word in answerList:
prev = let + ": " + word
ans = Label(preview, text = prev)
ans.grid(row=1+i, column = 2)
let = chr(ord(let) + 1)
answerCor = "The correct answer(s): "
a = Label(preview, text = answerCor)
a.grid(row=4, column = 2)
b = Label(preview, text = cor.get)
b.grid(row=5, column = 2)
if num.get().isdigit():
number = int(num.get())
AnswerChoices = Label(top, text = "Answer Choices?", font = "Times 14 bold", fg = "blue")
AnswerChoices.grid(row = 6, column=4)
i = 0
let = 'A'
while i < number:
letter = Label(top, text = let)
letter.grid(row = 8+(i*4), column = 3)
answer = Text(top, borderwidth = 5, width=50, height=3, wrap=WORD, background = 'grey')
answer.grid(row = 8+(i*4), column = 4)
answerList[let] = answer.get("1.0",END)
i = i+1
let = chr(ord(let) + 1)
print answerList
correct = Label(top, text = "Correct Answer(s) (seperated by commas)",
font = "Times 14 bold", fg = "blue")
correct.grid(row =99 , column=4)
cor = Text(top, borderwidth = 5, width=50, height=3, wrap=WORD, background = 'grey')
cor.grid(row=100, column = 4)
else:
error = Tk()
w = 500
h = 100
ws = top.winfo_screenwidth()
hs = top.winfo_screenheight()
x = (ws/2) - (w/2)
y = (hs/2) - (h/2)
error.geometry('%dx%d+%d+%d' % (w, h, x, y))
text = "ERROR: You must enter an integer number"
Label(error,text = text, fg = "red", font = "Times 16 bold").pack()
MyButton5 = Button(top, text="Preview Question", width=20, command = preview, anchor=S)
MyButton5.grid(row=102, column=5)
MyButton4 = Button(top, text="Finish and Add Question", width=20, command = add, anchor=S)
MyButton4.grid(row=102, column=2)
but = Button(top, text="Submit", width=10, command = multiple)
but.grid(row=6, column = 4)
top.mainloop()
def button():
MyButton21 = Button(quiz, text="Short Answer Question", width=20, command = short_answer)
MyButton21.grid(row=8, column=2)
MyButton22 = Button(quiz, text="True/False Question", width=20, command = true_false)
MyButton22.grid(row=8, column=4)
MyButton23 = Button(quiz, text="Multiple Choice Question", width=20, command = multiple_choice)
MyButton23.grid(row=9, column=2)
#MyButton24 = Button(quiz, text="Matching Question", width=20, command = matching)
#MyButton24.grid(row=9, column=4)
MyButton25 = Button(quiz, text="Ordering Question", width=20, command =order)
MyButton25.grid(row=10, column=2)
MyButton26 = Button(quiz, text="Fill in the Blank Question", width=20, command = fill_blank)
MyButton26.grid(row=10, column=4)
MyButton3 = Button(quiz, text="Finsh Quiz", width=10, command = quiz)
MyButton3.grid(row=12, column=3)
quiz = Tk()
w = 700
h = 300
ws = quiz.winfo_screenwidth()
hs = quiz.winfo_screenheight()
x = 0
y = 0
quiz.geometry('%dx%d+%d+%d' % (w, h, x, y))
quiz.title("eCampus Quiz Developer")
L1 = Label(quiz, text="Quiz Title?")
L1.grid(row=0, column=0)
E1 = Entry(quiz, bd = 5)
E1.grid(row=0, column=3)
name_file = E1.get()
name_file = name_file.replace(" ", "")
name_file = name_file + ".txt"
with open(name_file,"w") as data:
MyButton1 = Button(quiz, text="Submit", width=10, command = button)
MyButton1.grid(row=1, column=3)
quiz.mainloop()
I am trying to create the dictionary using this chunk of code:
i = 0
let = 'A'
while i < number:
letter = Label(top, text = let)
letter.grid(row = 8+(i*4), column = 3)
answer = Text(top, borderwidth = 5, width=50, height=3, wrap=WORD, background = 'grey')
answer.grid(row = 8+(i*4), column = 4)
answerList[let] = answer.get("1.0",END)
i = i+1
let = chr(ord(let) + 1)
I have even tried putting a loop in the preview function but that is when the last box was the only value contained in the dictionary. Any ideas would be appreciated
Please see my commeneted snippet below which demonstrates this:
from tkinter import *
class App:
def __init__(self, root):
self.root = root
self.entry = Entry(self.root) #entry to input number of entries later
self.button = Button(self.root, text="ok", command=self.command) #calls command to draw the entry boxes
self.frame = Frame(self.root)
self.entry.pack()
self.button.pack()
self.frame.pack()
def command(self):
self.frame.destroy() #destroys frame and contents
self.frame = Frame(self.root) #recreates frame
self.text = [] #empty array to store entry boxes
for i in range(int(self.entry.get())):
self.text.append(Entry(self.frame, text="Question "+str(i))) #creates entry boxes
self.text[i].pack()
self.done = Button(self.frame, text="Done", command=self.dict) #button to call dictionary entry and print
self.done.pack()
self.frame.pack()
def dict(self):
self.dict = {}
for i in range(len(self.text)):
self.dict.update({self.text[i].cget("text"): self.text[i].get()})
#the above line adds a new dict entry with the text value of the respective entry as the key and the value of the entry as the value
print(self.dict) #prints the dict
root = Tk()
App(root)
root.mainloop()
The above asks the user how many entry widgets they want to create, fills a frame with those entry widgets and then iterates through the list which contains them on the press of a button, adding a new dictionary entry for each entry widget, where the key of the dict is the attribute text for each entry and the value of the dict is the value of each entry.

Using validation on text entry box

I am trying to set up validation on text entry boxes. Three of the boxes need to only accept integers and one text as a postcode. I am not sure whether to do this in a function previously defined or when the entry boxes are created. Also how would i make the values from the text entry boxes be accessable in the function QuoteCreation. All my code is below.
from tkinter import *
class quote():
def __init__(self, master):
self.master=master
self.master.title("Quote Screen")
self.master.geometry("2100x1400")
self.master.configure(background = "white")
self.Borras = PhotoImage(file = "Borras.Logo.2.gif") #sets up image
self.Borras.image = self.Borras
self.BorrasLabel = Label(self.master, image = self.Borras, bg = "white")#puts image onto label
self.BorrasLabel.place(anchor=NW)
self.Title = Label(self.master, text = "New Quote", font = ("calibri", 20), bg = "White")
self.Title.place(x=650, y = 10)
self.SubmitButton = PhotoImage(file = "Submit.Button.gif") #sets up image
self.SubmitButton.image = self.SubmitButton
self.SubmitButtonLabel = Button(self.master, image = self.SubmitButton, bg = "white", command= self.QuoteCreation)#puts image onto a button
self.SubmitButtonLabel.place(x=900, y=290)
PostCodeVar = StringVar()
PostCodeEntry = Entry(master,width=50, font=20, textvariable=PostCodeVar)
PostCodeEntry.place(x = 20, y = 150)
PostCodeVar.set("Please enter the Post Code")
PostCodeValue = PostCodeVar.get()
HeightVar = StringVar()
HeightEntry = Entry(master, width=50, font=20, textvariable=HeightVar)
HeightEntry.place(x = 20, y = 220)
HeightVar.set("Please enter the Height")
HeightValue = HeightVar.get()
LengthVar = StringVar()
LengthEntry = Entry(master, width=50, font=20, textvariable=LengthVar)
LengthEntry.place(x = 20, y = 290)
LengthVar.set("Please enter the Length")
LengthValue = LengthVar.get()
PitchVar = StringVar()
PitchEntry = Entry(master, width=50, font=20, textvariable=PitchVar)
PitchEntry.place(x = 20, y = 360)
PitchVar.set("Please enter the Pitch")
PitchValue = PitchVar.get()
RiseVar = StringVar()
RiseEntry = Entry(master, width=50, font=20, textvariable=RiseVar)
RiseEntry.place(x = 20, y = 430)
RiseVar.set("Please enter the Rise")
RiseValue = RiseVar.get()
self.SubmitButton = PhotoImage(file = "Submit.Button.gif")
self.SubmitButton.image = self.SubmitButton
self.SubmitButtonLabel = Button(self.master, image = self.SubmitButton, bg = "white", command= self.QuoteCreation)#puts image onto a button
self.SubmitButtonLabel.place(x=900, y=290)
def on_button(self):
print(self.entry.get())
def QuoteCreation(self):
print(' ')
def quitWindow(self):
self.master.destroy()
def backToWelcome(self):
self.master.destroy()
You would set up separate functions to deal with the validation, when the submit button is pressed.
So, as an example, your submit button may look a bit like this:
submitButton = Button(master, text="Submit", command=validation)
The validation, in your case would then want to carry out these checks:
def validation():
postcode = PostCodeVar.get()
length = LengthVar.get()
pitch = PitchVar.get()
rise = RiseVar.get()
if postcodeCheck(postcode) == True and length.isdigit() == True and pitch.isdigit() == True and rise.isdigit() == True:
#carry out chosen process
In your case, you can try setting the postcode, length, pitch and height variables before calling the function, and setting them as global. The postcode should be created, and if it is okay, the function should then:
return True
...so it matches the outcome of the if statement.
I hope this is what you were looking for, and can adapt the example to your specific problem!

Categories