Unable to get selected value from Combobox in Tkinter - python

I'm running a simple piece of code wherein whenever a value is selected from the combobox, it needs to be printed in the terminal. But whenever I select a value, after pressing the Quit Button, it's not getting printed on the terminal.
Any nudge would be appreciated.
Thank you for the help
from tkinter import *
from tkinter import ttk
win = Tk()
win.geometry("200x100")
vals = ('A','B','C','CD','E','FG')
current_var= StringVar()
cb= ttk.Combobox(win, textvariable = current_var)
cb['values']= vals
cb['state']= 'readonly'
cb.pack(fill='x',padx= 5, pady=5)
IP = current_var.get()
Button(win, text="Quit", command=win.destroy).pack()
win.mainloop()
print(IP)

If you want the quit button to print the value then change it to something like this.
from tkinter import *
from tkinter import ttk
def get_value():
IP = current_var.get()
print(IP)
win.destroy()
win = Tk()
win.geometry("200x100")
vals = ('A','B','C','CD','E','FG')
current_var= StringVar()
cb= ttk.Combobox(win, textvariable = current_var)
cb['values']= vals
cb['state']= 'readonly'
cb.pack(fill='x',padx= 5, pady=5)
IP = current_var.get()
Button(win, text="Quit", command= get_value).pack()
win.mainloop()
print(IP)

#Rory's answer isn't quite right because the final print(IP) is simply printing a newline (which he probably didn't notice). To fix that the get_value() callback function should declare global IP so IP is no longer a variable local to the function and its value can be accessed outside the function.
The code below illustrates this and also follows the PEP 8 - Style Guide for Python Code guidelines more closely than what's in your question.
import tkinter as tk # PEP 8 advises avoiding `import *`
import tkinter.ttk as ttk
def get_value():
global IP
IP = current_var.get()
win.destroy()
win = tk.Tk()
win.geometry("200x100")
vals = 'A','B','C','CD','E','FG'
current_var = tk.StringVar(win)
cb = ttk.Combobox(win, textvariable=current_var, values=vals, state='readonly')
cb.pack(fill='x', padx= 5, pady=5)
tk.Button(win, text="Quit", command=get_value).pack()
win.mainloop()
print(IP)

You get the value just after cb is created and the value should be empty string because there is no item is selected at that time. You need to get the value after an item is selected.
One of the way is to move the line IP = current_var.get() after win.mainloop():
from tkinter import *
from tkinter import ttk
win = Tk()
win.geometry("200x100")
vals = ('A','B','C','CD','E','FG')
current_var = StringVar()
cb= ttk.Combobox(win, textvariable=current_var)
cb['values'] = vals
cb['state'] = 'readonly'
cb.pack(fill='x', padx=5, pady=5)
Button(win, text="Quit", command=win.destroy).pack()
win.mainloop()
IP = current_var.get()
print(IP)

Related

How to update and show in real time on label 2 what user write in ENTRY label1?

If i have this ENTRY label1 on pos1, how can i update and show "in real time" the text i write on other label 2 in position2?
label1 = Entry(root, font=('aria label', 15), fg='black')
label1.insert(0, 'enter your text here')
label1_window = my_canvas.create_window(10, 40, window=entry)
label2 = how to update and show in real time what user write on label1
If the entry and label use the same StringVar For the textvariable option, the label will automatically show whatever is in the entry. This will happen no matter whether the entry is typed in, or you programmatically modify the entry.
import tkinter as tk
root = tk.Tk()
var = tk.StringVar()
canvas = tk.Canvas(root, width=400, height=200, background="bisque")
entry = tk.Entry(root, textvariable=var)
label = tk.Label(root, textvariable=var)
canvas.pack(side="top", fill="both", expand=True)
label.pack(side="bottom", fill="x")
canvas.create_window(10, 40, window=entry, anchor="w")
root.mainloop()
Issues in your attempt: The variable names are not clear as you are creating an Entry component and then assigning it to a variable named label1 which can be confusing.
Hints: You can do one of the following to tie the label to the entry so that changing the text in the entry causes the text in the label to change:
Use a shared variable
Implement a suitable callback function. You can, for example, update the label each time the KeyRelease event occurs.
Solution 1 - Shared variable: Below is a sample solution using a shared variable:
import tkinter as tk
from tkinter import *
root = tk.Tk()
root.title('Example')
root.geometry("300x200+10+10")
user_var = StringVar(value='Enter text here')
user_entry = Entry(root, textvariable=user_var, font=('aria label', 15), fg='black')
user_entry.pack()
echo_label = Label(root, textvariable=user_var)
echo_label.pack()
root.mainloop()
Solution 2 - Callback function: Below is a sample solution using a suitable callback function. This is useful if you wish to do something more:
import tkinter as tk
from tkinter import *
root = tk.Tk()
root.title('Example')
root.geometry("300x200+10+10")
def user_entry_changed(e):
echo_label.config({'text': user_entry.get()})
user_entry = Entry(root, font=('aria label', 15), fg='black')
user_entry.insert(0, 'Enter your text here')
user_entry.bind("<KeyRelease>", user_entry_changed)
user_entry.pack()
echo_label = Label(root, text='<Will echo here>')
echo_label.pack()
root.mainloop()
Output: Here is the resulting output after entering 'abc' in the entry field:

Why is it different between entry val and str(same)?

from tkinter import *
import tkinter.ttk as ttk
root = Tk()
root.title("TEST ")
lab_pro_val4=Label(root)
lab_pro_val4=Label(root, text="Anything input", width=30, height=1 )
lab_pro_val4.pack()
ent_pro_val4 = Entry(root)
ent_pro_val4.pack()
def btncmd4_add():
tru = (ent_pro_val4=='TEST123')
print(tru)
btn4_ppid = Button(root, text="Check ", command= btncmd4_add,bg = "white")
btn4_ppid.pack()
root.mainloop()
I used Tkinter but I had some trouble.
My question : why is it diff from entry to str(same)
I type the 'TEST123' in entry box.
But it's False... Why is it different?
Please let me know.
ent_pro_val4 is Entry widget, you need to get value of said widget, which can be done using .get(), that is replace
tru = (ent_pro_val4=='TEST123')
using
tru = (ent_pro_val4.get()=='TEST123')

tkinter, save the input as variable

I want to use the input value as variable and this is my code.
from tkinter import *
from tkinter import messagebox
window = Tk()
Label(window, text='Cavity number').grid(row=0)
CavNum = StringVar()
for i in range(1,8) :
globals()['L{}_CavNum'.format(i)] = StringVar()
globals()['L{}_CavNum'.format(i)] = Entry(window, textvariable=globals()['L{}_CavNum'.format(i)])
globals()['L{}_CavNum'.format(i)].grid(row=0, column=i)
window.geometry("1200x150")
window.mainloop()
everytime I do print(L1_CavNum), it says "<tkinter.Entry object .!entry>". please tell me what is the problem
You are re-using the same name for the entry widget as you use for StringVar. You could simply change globals()['L{}_CavNum'.format(i)] = StringVar() to globals()['L{}_CavNumSV'.format(i)] = StringVar() and print(L1_CavNum) to print(L1_CavNumSV.get()). However the .get() function will execute when your code runs so you will have to have a button or another event to callback the function.
I would do it like this.
from tkinter import *
def print_vars():
for x in range(len(cavity_string_vars)):
print(cavity_string_vars[x].get())
window = Tk()
Label(window, text='Cavity number').grid(row=0)
cavity_string_vars = []
cavity_entries = []
for i in range(7):
cavity_string_vars.append(StringVar())
cavity_entries.append(Entry(window, textvariable=cavity_string_vars[i]))
cavity_entries[i].grid(row=0, column=i)
print_button = Button(window, text="Print", command=print_vars)
print_button.grid(row=1, column=0)
window.geometry("1200x150")
window.mainloop()
To me associated arrays are much easier than naming each variable even when you program it as you have. Perhaps that is needed for your case.

How to use textfield key press event using python

if i write some thing on the textfield and press enter key on the keyboard.what i entered on the textfield display messagebox. this point get error if(format(k=event.char(13)))) : if i set the enter key code. i added full code below.
from tkinter import *
root = Tk()
root.geometry("800x800")
global e1
def callback(event):
if(format(k=event.char(13)))):
msg = e1.get()
print(msg)
Label(root, text="Student Name").place(x=140, y=40)
e1 = Entry(root)
e1.place(x=140, y=10)
e1.bind('<Key>',callback)
root.mainloop()
Try this out
from tkinter import *
root = Tk()
root.geometry("800x800")
def callback(event):
msg = e1.get()
print(msg)
Label(root, text="Student Name").place(x=140, y=40)
e1 = Entry(root)
e1.place(x=140, y=10)
e1.bind('<Return>',callback) #<Return> is equivalent to your Enter key
root.mainloop()
When you click on Enter key, on the entry widget, then the function gets called and the output will be printed out. I also removed the global as it makes no sense to use it in outside functions.
Hope it helped you out.
Cheers

In Tkinter, How I disable Entry?

How I disable Entry in Tkinter.
def com():
....
entryy=Entry()
entryy.pack()
button=Button(text="Enter!", command=com, font=(24))
button.pack(expand="yes", anchor="center")
As I said How I disable Entry in com function?
Set state to 'disabled'.
For example:
from tkinter import *
root = Tk()
entry = Entry(root, state='disabled')
entry.pack()
root.mainloop()
or
from tkinter import *
root = Tk()
entry = Entry(root)
entry.config(state='disabled') # OR entry['state'] = 'disabled'
entry.pack()
root.mainloop()
See Tkinter.Entry.config
So the com function should read as:
def com():
entry.config(state='disabled')
if we want to change again and again data in entry box we will have to first convert into Normal state after changing data we will convert in to disable state
import tkinter as tk
count = 0
def func(en):
en.configure(state=tk.NORMAL)
global count
count += 1
count=str(count)
en.delete(0, tk.END)
text = str(count)
en.insert(0, text)
en.configure(state=tk.DISABLED)
count=int(count)
root = tk.Tk()
e = tk.Entry(root)
e.pack()
b = tk.Button(root, text='Click', command=lambda: func(e))
b.pack()
root.mainloop()

Categories