How to get the Values from the Entry box in Tkinter? - python

def in_Vals():
in_win = Tk()
in_win.title("Check In Details")
in_win.geometry("700x700")
in_win.resizable(0,0)
# title
title = Label(in_win,text="Check In Details",font=("Harlow Solid Italic",30,"italic"),fg="black",bg="#fbb08c")
title.pack(anchor="center",pady=5)
#creating label's
_Id_ = Label(in_win,text="Id :",font=("Times New Roman",15,"italic"),fg="black",bg="#fbb08c")
_Name_ = Label(in_win,text="Name :",font=("Times New Roman",15,"italic"),fg="black",bg="#fbb08c")
_Date_ = Label(in_win,text="Date :",font=("Times New Roman",15,"italic"),fg="black",bg="#fbb08c")
_Time_ = Label(in_win,text="Time :",font=("Times New Roman",15,"italic"),fg="black",bg="#fbb08c")
_Number_ = Label(in_win,text="Number :",font=("Times New Roman",15,"italic"),fg="black",bg="#fbb08c")
_Id_.pack(anchor='w',padx=10,pady=20)
_Name_.pack(anchor='w',padx=10,pady=20)
_Date_.pack(anchor='w',padx=10,pady=20)
_Time_.pack(anchor='w',padx=10,pady=20)
_Number_.pack(anchor='w',padx=10,pady=20)
# creating submit function
def submit():
print(f"{in_val_1}\n{in_val_2}\n{in_val_3}\n{in_val_4}\n{in_val_5}")
# creating entries
Id = Entry(in_win,width=25,font=("Courier",15,'bold'))
Name = Entry(in_win,width=25,font=("Courier",15,'bold'))
Date = Entry(in_win,width=25,font=("Courier",15,'bold'))
Time = Entry(in_win,width=25,font=("Courier",15,'bold'))
Number = Entry(in_win,width=25,font=("Courier",15,'bold'))
Id.place(x=100,y=87)
Name.place(x=100,y=157)
Date.place(x=100,y=227)
Time.place(x=100,y=293)
Number.place(x=100,y=360)
#getting values
in_val_1 = Id.get()
in_val_2 = Name.get()
in_val_3 = Date.get()
in_val_4 = Time.get()
in_val_5 = Number.get()
# creating submit button
submit = Button(in_win,text="Submit",font=("Wild Latin",15,"bold"),command=submit)
submit.place(x = 250,y=450)
in_win.config(bg="#fbb08c")
in_win.mainloop()
Here the function in_vals() is a coded to take data from the ID, Name, Date, Time, Number Entries and assign the values of The entries to the variables in_val_1 to in_val_5 ,to get the values from the entry box I have used the .get() Method. but when I try to Print the Variables that I assigned to the .get() method, it prints some white Space's.

The solution for the problem same as mine is
defining the values outside the the button function does not get anything.
here I have defined out side the button function
after defining it inside the button function it gives me the desired output

Related

Difficulty initializing complex session_state for inputs in Streamlit

This is my code and although I initialize the session state, I'm having a conflict with it.
import streamlit as st
if "user_inputs" not in st.session_state:
st.session_state["user_inputs"] = True
# Loop over the 8 questions
for i in range(8):
# Get the question
question = f'Question {i+1}'
# Add it to the page
st.subheader(question)
# Create 3 checkbox options
checkbox1 = st.checkbox('Option 1')
checkbox2 = st.checkbox('Option 2')
checkbox3 = st.checkbox('Option 3')
# Save the checkbox inputs in the session state object
st.session_state.user_inputs[f'{question}_checkbox_1'] = checkbox1
st.session_state.user_inputs[f'{question}_checkbox_2'] = checkbox2
st.session_state.user_inputs[f'{question}_checkbox_3'] = checkbox3
# Create an integer input
integer_input = st.number_input('Integer Input')
# Save the integer input in the session state object
st.session_state.user_inputs[f'{question}_integer_input'] = integer_input
# Create a slider
slider = st.slider('Slider', 0, 100)
# Save the slider value in the session state object
st.session_state.user_inputs['slider'] = slider
# Add a submit button
if st.button('Submit'):
st.success('Form submitted!')
I tried different ways to initialize but they didn't work. When I try something like st.session_state.user_inputs = "test" or st.session_state["user_inputs"] = "test", again I have same error:
The error is:
st.session_state has no attribute "user_inputs". Did you forget to
initialize it? More info:
https://docs.streamlit.io/library/advanced-features/session-state#initialization
I tried to create a kind of form but I received a repetitive error.
The error I get for your main block of code is TypeError: 'bool' object does not support item assignment.
This makes sense, because st.session_state["user_inputs"] = True means you've set up a boolean, not a dictionary, so when you do:
st.session_state.user_inputs[f'{question}_checkbox_1'] = checkbox1
you're basically doing:
True[f'{question}_checkbox_1'] = checkbox1
giving the error. Instead, use:
if "user_inputs" not in st.session_state:
st.session_state["user_inputs"] = {}
Next, you have duplicate keyed inputs. Try adding unique keys to these:
checkbox1 = st.checkbox('Option 1', key=f'{i}-1')
checkbox2 = st.checkbox('Option 2', key=f'{i}-2')
checkbox3 = st.checkbox('Option 3', key=f'{i}-3')
# ...
integer_input = st.number_input('Integer Input', key=i)
Note also that keyed user inputs are automatically added to state, which is a bit surprising, but that's Streamlit for you. If you do prefer to explicitly set them, I'd use actual nested structures like 2d lists or dicts rather than keys with concatenated identifiers.
Finally, you may want to use st.form to group all of your inputs into a collection, avoiding triggering rerenders.

After updating OptionMenu, Optionmenu's function does not work

def kayit_ekle_update(): ##
kayit_listesiVar.set('') # remove default selection only, not the full list
kayit_listesiOM['menu'].delete(0, 'end') # remove full list
kayitlilarOM = os.listdir("allin1/data_records")
for opt in kayitlilarOM:
kayit_listesiOM['menu'].add_command(label=opt, command=tk._setit(kayit_listesiVar, opt))
kayit_listesiVar.set(kayitlilarOM[0]) # default value set
def entri_doldur(se):
## get data from excel and append them to a new list(veri_al_list)
veri_al_list = []
om_deger = "allin1/data_records/" + kayit_listesiVar.get()
wb_kayit = load_workbook(om_deger)
ws_kayit = wb_kayit.active
for column_data in ws_kayit['1']:
veri_al_list.append(column_data.value)
veri_al_list = [' ' if v is None else v for v in veri_al_list] # None elemanı hata verdiriyor. Burada tüm None olanları "" ile değiştiriyoruz.
print(veri_al_list)
## There are Entry widgets created with for loop.
## en in entry_liste ==> Entries
## ne in veri_al_liste ==> data list from excel
for en, ne in zip(entry_liste, veri_al_list):
en.delete(0,END)
en.insert(END, ne)
wb_kayit.close()
kayitlilarOM = os.listdir("allin1/data_records")
kayit_listesiVar = StringVar()
kayit_listesiVar.set("Kayıt seç")
kayit_listesiOM = OptionMenu(ust, kayit_listesiVar, *kayitlilarOM, command=entri_doldur)
I have entry widgets in my code. The user can enter data and save them. Each time this data is saved, a new excel file is created and the data is saved in it.
The name of each saved excel file is displayed in an optionmenu. When we select a record from the Optionmenu, the entri_doldur() function works and the entries are filled according to the record.
I can delete the selected record with the button. When deleted, both the entries are empty and the option menu is updated.
But the problem occurs when I create a new record. Creating a new excel file. The data is saved in it. Option menu is being updated. But after that, when I select a record in the optionmenu, the entri_doldur() function does not work. The information of the selected record does not fill the entries.

Create buttons in loop with different actions - Python

I am working on Dynamo for Revit. My code takes sheet numbers and other info, then creates labels and buttons for each IN element with a for loop. The GUI works fine and I have all the elements in place, but how do I tell each individual button to open a different sheet? See screenshot.
I need to understand the workflow, but here is the code of the loop if it helps:
# Create labels and buttons in loop
y = 50
a = 0
for i in res:
# creates section name label
text = str(res[a][0])
text = text[19:]
text = text[:-1]
labelSectionName = Label(Text = text)
labelSectionName.Parent = self
labelSectionName.Location = Point(gridColSecName,y)
labelSectionName.Width = gridWidthSecName
#labelSectionName.Height = 20
# creates sheet number label
text = str(res[a][2])
labelSectionName = Label(Text = text)
labelSectionName.Parent = self
labelSectionName.Location = Point(gridColSheetNum,y)
labelSectionName.Width = 50
# create button for opening sheet
button = Button()
button.Parent = self
button.Text = "Open Sheet"
button.Location = Point(gridColButtSheet,y)
# Register button event
button.Click += self.?????????????????????????????????????
and this is the code for opening the sheet taken from another script
sheet = UnwrapElement(IN[0])
sheet_action=(IN[1])
output = []
if (str(sheet_action) == "Yes"):
uidoc.RequestViewChange(sheet)
output.append("ActiveView set to: " + sheet.Name)
else:
pass
OUT = sheet_action

Insert data from a SQL query into a tkinter Entry field

I'm trying to put data from a database (SQLite3) into a set of entry fields in Tkinter.
My hope is that the data-snippets that exist in the database query will be put into the entries to show the user what info is in the db and give the choice to update empty fields.
I however have a hard time dealing with the returned None fields from the DB. None cannot be inserted into entries using .insert()
I've tried to sanitize the data first but since the different data are ints and text's I have not find a suitable replacement. I would also prefer the entries to be empty unless there is actual data to place there.
I've also tried to do an if statement before each line in the vendors_to_fields function but that did not work and seemed really messy.
Bonus question:
Is there a better way to insert values from a tuple into the different entries? I've been thinking about making 2 lists and using list comprehension but I could not solve it.
I hope I make sense, this has been a long coding session
Thank you for all input
My code:
def Order_window():
ord_win = Toplevel(root)
ord_win.title('Orders')
ord_win.geometry('800x600')
i = 0
# Functions
def controller():
vendor_list = list(vendors)
if i <= len(vendor_list):
vendor = vendor_list[i]
print(vendor)
data_from_db(vendor)
else:
vendor_name['text'] = 'All orders are done'
def data_from_db(vendor):
vendor_info_tuple = db.execute(
'SELECT * FROM vendors WHERE (vendor_id = ?)', [vendor])
vendor_info_tuple = vendor_info_tuple.fetchone()
connection.commit()
vendor_info = list(vendor_info_tuple)
if vendor_info[0] is None:
vendor_name['text'] == 'Vendor not in DB, better call Sal'
else:
print(vendor_info)
vendor_to_fields(vendor_info)
def vendor_to_fields(vendor_info):
for field in vendor_info:
if field is None:
vendor_info[field] = 0
print(vendor_info)
vendor_name['text'] = vendor_info[1]
vendor_min1.insert(0, vendor_info[5])
vendor_email.insert(0, vendor_info[2])
vendor_cc.insert(0, vendor_info[3])
vendor_message.insert(0, vendor_info[4])
def next_vendor():
pass
def update_db():
pass
# Layout order window
Label(ord_win, text='Vendor').grid(row=0)
Label(ord_win, text='Min order value').grid(row=1)
Label(ord_win, text='Email').grid(row=2)
Label(ord_win, text='CC').grid(row=3)
Label(ord_win, text='Message').grid(row=4)
vendor_name = Label(ord_win).grid(row=0, column=1)
vendor_min1 = Entry(ord_win)
vendor_min1.grid(row=1, column=1)
vendor_email = Entry(ord_win)
vendor_email.grid(row=2, column=1)
vendor_cc = Entry(ord_win)
vendor_cc.grid(row=3, column=1)
vendor_message = Entry(ord_win)
vendor_message.grid(row=4, column=1)
controller()

Python looping for label variables

I am trying to create a loop that will display each title of product for their individual labels (Tkinter module).
With the current loop i can get it to print my 10 "static_webpage_1_titles" in the list, but i am wanting to also increase the variable Label_1 by +1 increment each time.
For example, it should do somthing like this:
Label_1['text'] = static_webpage_1_titles[0]
Label_2['text'] = static_webpage_1_titles[1]
Label_3['text'] = static_webpage_1_titles[2]
Here is my current code:
def Generate_Product_Name_and_Price_1():
if Button_on:
Find_static_webpage_1()
for i in range(len(static_webpage_1_titles)):
Label_1['text'] = static_webpage_1_titles[i]
EDIT:
product_labels = [Label_1['text'], Label_2['text'], Label_3['text'],
Label_4['text'], Label_5['text'], Label_6['text'],
Label_7['text'], Label_8['text'], Label_9['text'],
Label_10['text']]
I have created a list above with each label widget and changed the last line of code in my loop to:
def Generate_Product_Name_and_Price_1():
if Button_on:
Find_static_webpage_1()
for i in range(len(static_webpage_1_titles)):
product_labels[i] = static_webpage_1_titles[i] +': $'+ static_webpage_1_price[i]
When i run this, i do not receive any IDLE error but my label widgets do not get populated with data.
You need to make a list of the Label instances, not the text attributes of Label instances. Like this:
product_labels = [Label_1, Label_2, Label_3,
Label_4, Label_5, Label_6,
Label_7, Label_8, Label_9,
Label_10]
Then you access the attribute like this:
for i in range(len(static_webpage_1_titles)):
product_labels[i]['text'] = static_webpage_1_titles[i] +': $'+ static_webpage_1_price[i]
You could also make this a little neater with zip():
for label, title, price in zip(product_labels, static_webpage_1_titles, static_webpage_1_price):
label['text'] = title +': $'+ price

Categories