Tkinter: how to get a string from a top-level entry? [closed] - python

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
In tkinter, how can I .get() the entry from a top level window?
def logika(event):
a=e.get()
def pocetak(event):
igra=Toplevel(glavni)
igra.geometry("500x500+710+290")
e=Entry(igra)
e.pack()
GumbIgra=Button(igra,text="Unos")
GumbIgra.bind("<Button>",func=logika)
GumbIgra.pack()
return
glavni=Tk()
glavni.geometry("600x600")
glavni.resizable(True,True)
glavniGumb=Button(glavni,text="Za početak stisni me!",pady=10,padx=15)
glavniGumb.config(font=("Arial",10))
glavniGumb.bind("<Button>",func=pocetak)
glavniGumb.pack()

It seems more like the logika(event) function is unable to figure out what is e. You will have to pass the object.
So something like this (untested):
from tkinter import *
#Creating main window
root = Tk()
def Input_Box():
# creating a top window
master_2 = Toplevel(root)
#Textboxes
user_name = Entry(master_2)
user_name.grid(row = 1, column = 2)
pwd = Entry(master_2)
pwd.grid(row = 2, column = 2)
label_un = ttk.Label(master_2, text = "Username")
label_un.grid(row = 1, column = 1)
label_pwd = ttk.Label(master_2, text = "Password")
label_pwd.grid(row = 2, column = 1)
get_button = Button(master_2, text = "Confirm", command = lambda: getname(user_name))
get_button.grid(row=3, column = 1)
master_2.mainloop()
def getname(user_name):
input = user_name.get()
print(input)
call_button = Button(root, text='Enter Usrnm and pwd', command = Input_Box)
call_button.pack()
root.mainloop()
The command = lambda: getname(user_name) passes the user_name object that refers to the textbox.
Hope this helps!
Please give us the exact error.
PS: This was for something else but I think this should help.

Related

Get python radio button value [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 days ago.
Improve this question
import tkinter as tk
I want to print the sr variable outside the function name, but it doesn't work. What should I do? help
import tkinter as tk
win = tk.Tk()
win.title('Test')
rpm_frame = tk.LabelFrame(win, text='샘플링 주파수')
rpm_frame.pack()
def get_sample():
if sample_var.get() == 1:
sr = 48000
ts = 1 / sr
print(sr)
if sample_var.get() == 2:
sr = 2000
ts = 1 / sr
print(sr)
sample_var = tk.IntVar()
sample_48000 = tk.Radiobutton(rpm_frame, text='48000', value=1, variable=sample_var, command=get_sample)
sample_2000 = tk.Radiobutton(rpm_frame, text='2000', value=2, variable=sample_var, command=get_sample)
sample_48000.pack()
sample_2000.pack()
win.mainloop()

I am building a GUI for my app but get errors. Why? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am trying to make a GUI to my app using tkinter but it doesn't work. why? The program needs to take 2 inputs from user and save them in variables also I marked where I got errors in the code below
import tkinter as tk
# making the window
root = tk.Tk()
root.title("AutoWhatsUp")
root.geometry('500x500')
# getting phone number from user
enter_number = tk.Label(root, text = "enter below the phone number you want to message")
enter_number.pack()
filed = tk.Entry(root)
filed.pack()
def get_number():
phone_num = filed.get()
done_procces_phone = tk.Label(root, text = 'Phone number procced!').pack() # getting error here
confirm_number = tk.Button(root, text = 'procces number', command = get_number).pack() #getting error here
# getting the message
enter_mess = tk.Label(root, text = 'enter below the message').pack() #getting error here
enter_mess_here = tk.Entry(root).pack() #getting error here
def getting_message():
message_here = enter_mess_here.get()
print(message_here)
done_procces_mess = tk.Label(root, text = "done!").pack() #getting error here
get_mess = tk.Button(root, text = "procces message", command = getting_message).pack() #getting error here
root.mainloop()
Your problem is you put None in your variable enter_mess_here here:
enter_mess_here = tk.Entry(root).pack() #getting error here
and in your function when you want to get the value it's not getting value from Entry it's getting from Nothing. So it raises an error.
First assign your Entry to a variable then use pack, so this will work:
enter_mess_here = tk.Entry(root)
enter_mess_here.pack()

Python program not responding [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
Have been trying to run my program for several times, the icon and window is there but it's not responding. This actually might have something to do with looping but I'm not sure how to solve this. Is anyone able to help me out with this? Many thanks.
Looping is needed for combobox list.
Here is the code:
No errors found in the shell
from tkinter import *
from tkinter.ttk import *
from tkinter import ttk
import tkinter as tk
import pandas as pd
def CurSelet(evt):
global sel
temp=list()
for i in lbox.curselection():
temp.append(lbox.get(i))
allitems=list()
#for i in range(lbox.size()):
#allitems.append(lbox.get(i))
for i in sel:
if i in allitems:
if i not in temp:
sel.remove(i)
for x in lbox.curselection():
if lbox.get(x) not in sel:
sel.append(lbox.get(x))
def update_list():
global sel
global l
search_term = search_var.get()
# Just a generic list to populate the listbox
lbox_list = Device
lbox.delete(0, END)
for item in lbox_list:
if search_term.lower() in item.lower():
lbox.insert(END, item)
allitems=list()
for i in sel:
if i in allitems:
lbox.select_set(lbox.get(0, "end").index(i))
#search box
search_var = StringVar()
search_var.trace("w", lambda name, index, mode: update_list())
searchbox = tk.Entry(window, width=20, textvariable=search_var)
searchbox.place(x = 90, y =60)
lbox = Combobox(window, width=30, height=4)
lbox.place(x=90,y=90)
lbox.bind('<<ComboboxSelected>>',CurSelet)
update_list()
Add break to this line and stop the looping
for item in lbox_list:
if search_term.lower() in item.lower():
lbox.insert(END, item)
break

Tkinter: how to have a button trigger such that it affects another button [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I am creating a GUI that is meant to emulate an online shop of some sort.
One part of the task is to have a button that will generate a HTML document with images of the user's chosen product category.
Below I have provided my four radio buttons along with their IntVar and commands.
Each of the RadioButton commands do the same thing but extract information from different websites, so for brevity I have only provided the command for the slipper category.
home_hobbies = Tk()
status = IntVar()
def show_slippers():
#open downloaded file to extract info
slipperfile = open('slippers.html','r',encoding = 'utf-8').read()
prices = findall("<span.*value'>(.*)</span>", slipperfile) #regex prices
titles = findall('<h3.*body ">\n\s*(.*)', slipperfile) #regex titles
select_categ.config(state=NORMAL) #make the text box edit-able
select_categ.delete(1.0, END) #delete any text already in the text box
#for loop to find first five items and print them
for i in range(5):
title = titles[i]
price = prices[i]
result = str(i+1) + ". " + title + ' - $' + price + "\n"
select_categ.insert(END, result) #write list of products
select_categ.config(state=DISABLED) #make sure the user can't edit the text box
slippers = Radiobutton(home_hobbies, command = show_slippers, indicator = 'off', variable = status, value = 1, text = 'Winter Slippers')
diy = Radiobutton(home_hobbies, command = show_diy, indicator = 'off', variable = status, value = 2, text = "DIY Supplies")
#newstock radiobuttons
sports = Radiobutton(home_hobbies, command = show_sports, indicator = 'off', variable = status, value = 3, text = "Pool Toys")
novelties = Radiobutton(home_hobbies, command = show_novelties, indicator = 'off', variable = status, value = 4, text = "Novelty Items")
select_categ = Text(home_hobbies, wrap = WORD, font = content_font, bg = widgetbg, fg = fontcolour, width = 40)
Above, I also provided the line of code that generates the Text widget as it may help in answering my question (I don't have a very deep understanding of this widget despite reading the effbot page about 20 times over).
I now have a different button whose task is to generate a HTML doc with it's own command, "show_img":
htmlshow = Button(home_hobbies, text = "View Product Images", command = show_img)
I am trying to make the show_img() command work such that I have a preamble of HTML coding, and then, depending on which radibutton has been chosen, the function will replace sections of the code with the corresponding information:
def show_img():
#in this section I write my HTML code which includes replaceable sections such as "image1" and source_url
if slipper_trig:
table = table.replace("source_url", ' Etsy - Shop Unique Gifts for Everyone')
imgfile = open('slippers.html', 'r', encoding = 'utf-8').read()
images = findall('<img\n*.*image\n*\s*src="(.*)"', imgfile)
for i in range(5):
image = images[i]
table = table.replace("image"+str(i+1), image)
I tried to add BooleanVar into the commands for my Radio Buttons like this:
slipper_trig = False
diy_trig = False
pool_trig = False
novelty_trig = False
#Function for the product category buttons
#
def show_slippers():
#make selected category true and change all others to false
slipper_trig = True
diy_trig = False
pool_trig = False
novelty_trig = False
As a way to distinguish between the categories but the GUI clearly doesn't remember the value of "slipper_trig" after its been defined as true in the "show_slippers" function.
Maybe I need to try and integrate the "show_img" command into my original functions that define the RadioButtons? Maybe I should be figuring out how to determine the category chosen by what's shown in the text box?
Any advice would be appreciated.
Thanks!
You didn't show minimal working code with your problem so I can only show some minimal example with Button and RadioButton to show how to use these widgets.
I don't know if you used command=function_name in Button.
BTW: it has to be function's name without ()
I don't know if you used .get() to get value from StringVar/Intvar/BooleanVar assigned to RadioButtons.
EDIT I added Checkbutton because probably you may need it instead of Radiobutton
import tkinter as tk
# --- functions ---
def on_click():
selected = result_var.get()
print('selected:', selected)
if selected == 'hello':
print("add HELLO to html")
elif selected == 'bye':
print("add BYE to html")
else:
print("???")
print('option1:', option1_var.get()) # 1 or 0 if you use IntVar
print('option2:', option2_var.get()) # 1 or 0 if you use IntVar
if option1_var.get() == 1:
print("add OPTION 1 to html")
if option2_var.get() == 1:
print("add OPTION 2 to html")
# --- main ---
root = tk.Tk()
result_var = tk.StringVar(root, value='hello')
rb1 = tk.Radiobutton(root, text="Hello World", variable=result_var, value='hello')
rb1.pack()
rb2 = tk.Radiobutton(root, text="Good Bye", variable=result_var, value='bye')
rb2.pack()
option1_var = tk.IntVar(root, value=0)
opt1 = tk.Checkbutton(root, text='Option 1', variable=option1_var)
opt1.pack()
option2_var = tk.IntVar(root, value=0)
opt2 = tk.Checkbutton(root, text='Option 2', variable=option2_var)
opt2.pack()
button = tk.Button(root, text='OK', command=on_click)
button.pack()
root.mainloop()
Doc on effbot.org: Button, Radiobutton, Checkbutton

How to add presence check validation to an entry box in TKinter?

Firstly, I am aware that this question has already been asked. However, none of the answers for it actually answer the question.
I am creating a program that allows details to be stored in a database. These details can also be searched for using specific data (in this case, the First Name, Surname, House number and Postcode). Therefore, in order for the details to be searched for, this data needs to be present.
I have entry boxes that allow for saving data entered to a Database, but I would like it so that it won't add the details unless the aforementioned data is entered.
In pseudocode, I would like the program to function similarly to:
if Firstname or Surname or House or Postcode is not present:
output "Please enter required information"
Currently, this is my code for the entry boxes:
Label(frame1, text = "Postcode: ", font = ("arial 11"), fg = "#b83dba").grid(row = 7, column = 0, sticky = W)
pcVar = StringVar()
pc = Entry(frame1, textvariable = pcVar, bg = "silver")
pc.grid(row = 7, column = 1, sticky = W)
I would preferably like it so that, when the details required are not entered, I can use the code: messagebox.showerror("Error","Required fields are missing")
Any help would be greatly appreciated.
Never mind I just found it out so I'll post how I did it in case anyone else wants to know.
If using entryvar = Entry(frame1, textvariable = testVar) as an example, in the code for actually saving the details you would include:
Q = entryvar.get() #Returns the entry's current text as a string.
if Q == "":
messagebox.showerror("Error","Missing required fields") #Opens a messagebox informing the user that the details were not saved and that the data needs to be entered
else:
conn.execute('''INSERT INTO TABLE (DATA)
VALUES(?)''', (dataNew);
conn.commit()
messagebox.showinfo("Success","Details Saved") #Opens a messagebox informing the user that the details have saved
Apologies for my SQL as I am not very confident in that language.

Categories

Resources