Linking Tkinter label based on Entry value - python

Is there a way to make a Tkinter label that automatically updates to reflect changes in the text of an Entry field? For example, if the Entry has the text "1", the label should say "T1", but if the user changes the text in entry to "x" then the label should say "Tx", without having to press a button.

Yes, this is possible. The easiest way I can think of is using the .trace method of a StringVar, which calls a function if the value of the StringVar() changes. Here's an example:
def change_label(*args):
label.config(text='') # clear label
label.config(text='T' + var.get()) # set new label text
root = Tk()
var = StringVar() # make the StringVar()
label = Label(root)
entry = Entry(root, textvariable=var) # set the textvariable to var
var.trace('w', change_label) # trace var to monitor for changes, calling function on change
label.pack()
entry.pack()
root.mainloop()
More on trace: http://effbot.org/tkinterbook/variable.htm

Related

how to destroy previews label when the function call again in tkinter python

def entering(a):
value=entry1.get() #entry1.get()is used to get values which entered in entry box
label1=Label(root, text =value, height=10)
label1.pack()
entry1.delete(0, END) # used to clear entry box
root.bind('<Return>',entering)
how do I remove the widget that I created in the function call entering?
I know about the destroy function. I don't want to destroy it after a particular time.
I want to destroy it or overwrite it into the widget when I call the function again
I think this is what you expect:
import tkinter as tk
root = tk.Tk()
myentry = tk.Entry(root)
myentry.pack()
var = tk.StringVar(root)
mylabel = tk.Label(root, textvariable= var)
mylabel.pack()
def entering(event):
text = myentry.get()
var.set(text)
myentry.bind('<Return>', entering)
root.mainloop()

Automatically updating a value through a OptionMenu tkinter object

I would like to write a tkinter app that will automatically update a value based on the current state of the OptionMenu object. Here's what I have so far
from tkinter import *
root = Tk()
def show():
myLabel=Label(root,text=clicked.get()).pack()
clicked=StringVar()
clicked.set("1")
drop = OptionMenu(root,clicked,"1","2","3")
drop.pack()
myButton = Button(root,text="show selection",command=show)
root.mainloop()
In this version, the text can only be updated by clicking a button. How can I make the text update automatically, without this "middle man"?
You can simply assign clicked to the textvariable of the Label, then whenever an option is selected, the label will be updated:
import tkinter as tk
root = tk.Tk()
clicked = tk.StringVar(value="1")
drop = tk.OptionMenu(root, clicked, "1", "2", "3")
drop.pack()
tk.Label(root, textvariable=clicked).pack()
root.mainloop()
After changing some things, i got it working.
It is better to use the config() function to change item's attributes, and another important thing is to not pack() the objects (the Label, in this case) in the same line that the variable declaration.
Like so, you'll be able to change the text. Here is your code updated!
from tkinter import *
def show():
myLabel.config(text = clicked.get())
root = Tk()
clicked=StringVar( value="1")
myLabel=Label(root, text="click the button at the bottom to see this label text changed")
myLabel.pack()
drop = OptionMenu(root, clicked, "1","2","3")
drop.pack()
myButton = Button(root, text="show selection", command=show)
myButton.pack()
root.mainloop()

Python/Tkinter - clear the graphical interface screen

i am developing an application to calculate some taxes and show the result in the graphical interface. The code itself works perfectly, but if i use numbers with bigger squares, the result overlaps over the previous one. My question is, is it possible to clear the previous result and calculate the new one?
Follow the complete code below:
from tkinter import *
root = Tk()
l_vlrRec = Label(root, text='Receita')
l_vlrRec.place(x=10, y=10)
e_vlrRec = Entry(root)
e_vlrRec.place(x=75, y=10, width=75)
def calcular():
receita = float(e_vlrRec.get())
l_result = Label(root, text='{:.2f}'.format(receita))
l_result.place(x=10, y=150)
e_vlrRec.delete(0, END)
bt = Button(root, text='Calcular', command=calcular)
bt.place(x=10, y=50)
root.mainloop()
You can use the label's textvariable and also you don't have to instantiate a new Label every time the button is pressed:
v_result = DoubleVar()
l_result = Label(root, textvariable=v_result)
l_result.place(x=10, y=150)
def calcular():
v_result.set(round(float(e_vlrRec.get()),2))
You can do the same for your Entry object e_vlrRec so you don't have to cast the string you get by calling e_vlrRec.get() but use the variable's get() instead
Without using textvariable you can also reconfigure the label's text parameter:
l_result.configure(text='{:.2f}'.format(receita))
or
l_result['text'] = '{:.2f}'.format(receita)

Radio button values in Python Tkinter

I am trying to create a dialog box in Python using Tkinter. The goal is to have a dialog box with two radio buttons and an "OK" button. Radio button one selects the option "default". Radio button two selects the option "user defined." The "OK" button closes the window.
Question 1: How do I save the value from the radio button? That is, how do I pass the selected radio button to the rest of my script?
Question 2: How can I have the second radio button include user text input (along the lines of tkSimpleDialog.askstring)? I would like that button to show a radiobutton, a prompt ("Enter value:"), and a space for the user to enter text -- all on one line as a single radiobutton option.
So the whole dialog should have the top radio button be a normal radio button, and the second button specify user input and include a space for that user input (and the OK button).
So far I have a dialog open with two options, but the value doesn't get passed to anything I can see; selection is returned as 0 even before I select a radiobutton.
Any help on either question would be greatly appreciated, thank you.
Here's my script so far:
from Tkinter import*
master = Tk()
var = IntVar()
Label(master, text = "Select OCR language").grid(row=0, sticky=W)
Radiobutton(master, text = "default", variable = var, value = 1).grid(row=1, sticky=W)
Radiobutton(master, text = "user-defined", variable = var, value = 2).grid(row=2, sticky=W)
Button(master, text = "OK", command = master.quit).grid(row=3, sticky=W)
selection = var.get()
print "Selection:", selection
mainloop()
#If selection == 0 do one thing
#If selection == 1 do something else...
A bit late to the party, but I stumbled upon this question while trying to find something on Tkinter radiobuttons.
Question 1:
I changed three things:
1) I immediately set the value of var to 1 after you've defined it. This is done by doing var.set(1) and will make sure your first radio button is selected (which has a value of 1, as you defined it later on in the code).
2) I've replaced your master.quit command with a function called quit_loop. In this function:
The var value is printed through a print and get statement. The get will 'get' the current value of var, which depends on which radio button is selected.
I create a global variable within this function, which will then get the current value of var.
I added parentheses to master.quit() because this is no longer in the command of a radio button. Note that if you plan on using IDLE, master.destroy() might be a more suitable alternative.
3) Due to the creation of the selection variable in the function we now have your wanted value stored in a variable. There is one final if-statement at the end of the code to show it's working.
from Tkinter import *
master = Tk()
var = IntVar()
var.set(1)
def quit_loop():
print "Selection:",var.get()
global selection
selection = var.get()
master.quit()
Label(master, text = "Select OCR language").grid(row=0, sticky=W)
Radiobutton(master, text = "default", variable=var, value = 1).grid(row=1, sticky=W)
Radiobutton(master, text = "user-defined", variable=var, value = 2).grid(row=2, sticky=W)
Button(master, text = "OK", command=quit_loop).grid(row=3, sticky=W)
master.mainloop()
if selection == 1:
print "My Value is equal to one."
elif selection == 2:
print "My value is equal to two."
Question 2:
I would keep it simple and just add a label and an entry box right after your radio button. This means that we also have to work with columns as you didn't have any defined in your previous code, which makes everything default to column 0. We want your second radio button to be 'radio, label, entry' which takes three columns.
1) The previous label containing "Select OCR language" will be spanned over three columns with columnspan=3 added to the grid arguments. The same goes for your first radio button.
2) I added a Label and an Entry after your second radio button. Note that the columns go from 0 to 2, defining our three columns. The label has a simple "Enter value:" text, whereas the entry has the variable textvariable=entry_text. I added this variable entry_text to the beginning of your code and immediately set its value to ###. Note that this is a string (hence, textvariable) so adding checks for integer numbers only is up to you.
3) Of course, this is not linked to the second radio button. It still has a value of 2 if we select it, not the value of the Entry widget. That's why, in the previously created quit_loop function, I added a small if statement that assigns the value of the entry to selection if the second radio button was selected.
from Tkinter import *
master = Tk()
var = IntVar()
var.set(1)
entry_text = StringVar()
entry_text.set("###")
def quit_loop():
print "Selection:",var.get()
global selection
selection = var.get()
if selection == 2:
selection = entry_text.get()
master.quit()
# Add columnspan to these widgets
Label(master, text = "Select OCR language").grid(row=0, sticky=W, columnspan=3)
Radiobutton(master, text = "default", variable=var, value = 1).grid(row=1, sticky=W, columnspan=3)
# Order these widgets in their appropriate columns
Radiobutton(master, variable=var, value = 2).grid(row=2, sticky=W, column=0)
Label(master, text="Enter value:").grid(row=2, sticky=W, column=1)
Entry(master, textvariable=entry_text).grid(row=2, sticky=W, column=2)
# Example of what happens without columnspan
Button(master, text = "OK", command=quit_loop).grid(row=3, sticky=W)
master.mainloop()
print selection
Tip
If this simple GUI remains this small, it's ok to write code in this manner. However, expanding a lot on this further I would suggest taking an object oriented approach as it really improves readability a lot, especially when functions are being defined. That way they don't have to be necessarily defined beforehand.
Instead of directly using master.quit in the Button's command, define a function that finishes up the program then calls master.quit():
def end_program(event=None):#event will let it be used as .bind callbacks too if you need it.
selection = var.get()
if selection:
NotImplemented
else:
NotImplemented
master.quit()
...
Button(master, text = "OK", command = end_program).grid(row=3, sticky=W)
one the master is closed some of the data from the widgets is cleaned up so master.quit() needs to be called only after you are done accessing the widgets.
As set the selection value will be set before the window appears (selection = 0).
If you want to run tests after mainloop(), selection = var.get() should also be after mainloop() with tests.
If you do not want to close the master window before tests, use command=function:
from Tkinter import *
def function():
selection = var.get()
if selection == 1:
# Default
elif selection == 2:
# User-defined
else:#selection==0
#No choice
master.quit()
master = Tk()
var = IntVar()
Label(master, text = "Select OCR language").grid(row=0, sticky=W)
Radiobutton(master, text = "default", variable = var, value = 1).grid(row=1, sticky=W)
Radiobutton(master, text = "user-defined", variable = var, value = 2).grid(row=2, sticky=W)
Button(master, text = "OK", command = function).grid(row=3, sticky=W)
mainloop()

Entry string not being added to listbox

Could anyone help me debug this? The listbox isn't updating, and I'm not sure if the entry text (ment) is even transferring to the method.
def NewTask():
ment = StringVar()
top = Toplevel()
top.title("Add New Task")
top.minsize(300,300)
top.maxsize(300,300)
label_newtask = Label(top, text = "Entry New Task:", font = ("Purisa",20))
label_newtask.pack()
button_newtask = Button(top, text="Enter", command= NewTaskCount)
button_newtask.pack()
entry_newtask = Entry(top, textvariable=ment)
entry_newtask.pack()
def NewTaskCount():
ment = StringVar()
mtext = ment.get()
listbox.insert(END, mtext)
return
Your problem is that your stringvar ment is a local variable that is only visible within the scope of NewTask. In NewTaskCount, you are creating a new StringVar -- which is initially blank -- and immediately getting the value of that new variable. You need to make it a global variable, or use an object-oriented approach so that you can use an instance variable.

Categories

Resources