Label does not update when textvariable changes (Tkinter) - python

I'm completely new to Tkinter and I can't seem to make it work, even when copy/pasting codes from tutorials. More specifically, the following code for instance
Mafenetre = Tk()
Button(Mafenetre, text = 'quit.', command = Mafenetre.destroy).pack()
v = StringVar()
v.set("New Text!")
Label(Mafenetre, relief='solid', textvariable=v).pack()
Mafenetre.mainloop()
does not show New Text (but does show the 'quit' button). More generally, any use I've made (even copy/pasted code) of the textvariable attribute does not produce any text. What am I not understanding ?
Thank you in advance

Tkinter variables need a tk instance. So use:
v=StringVar(Mafenetre)

Related

Python - Printing to GUI instead of terminal

Very new to Python here, and I'm trying to create a GUI app that returns a random recipe. Currently the print happens at the terminal, and I'd like it to print in the GUI instead.
from tkinter import *
import os
import random
root = tk.Tk()
def printRecipes():
recipes = [
"Tom Yum Soup",
"Carnitas",
"General Tso's Chicken"
]
print(random.choice(recipes))
canvas = tk.Canvas(root, height=600, width=700, bg="#A8D1BB")
canvas.pack()
magic = tk.Button(root, text="Print", padx=10, pady=5, fg="white", bg="black", command=printRecipes)
magic.pack()
root.mainloop()
This doesn't work, as most of you already know. I've read that I need to use a label or text for it, but the example I've found all involved static print statements like
label = Label(root,text="Recipe")
label.pack
To "print" a value to a GUI Window, a Label is used. .config() is a useful function. It is used to configure the provided widget.
Below magic.pack(), add this code. Notice that there is no text parameter. We will use that later.
label1=Label(root,pady=10,font=("arial",15))
label1.pack()
Next, in the function, where you had print(random.choice(recipes)), we will add:
label1.config(text=random.choice(recipes))
Notice that we used .config() and the text parameter. We configured the label, and added some text to it.
You need a tk.StringVar for this, i.e. a variable which you can change and the label can read from:
label_str = tk.StringVar(value="Some text")
label = tk.Label(root, textvariable=label_str)
Then, to update the value of this label and show it on the GUI:
label_str.set("New text")
label.update()

Remove tkinter widget called using .place

I am working on an app using Tkinter and I have a small question.
For example, I have a label placed like this:
Label = Label(root, text="Hello").place(x=5, y=5)
Is there any way to hide the label when a button is pressed or when a function is called?
Any help will be appreciated
Thanks!
You should simply never chain .place() or any other geometry manager to the widget creator. It returns None.
lbl_name = Label(root, text="Hello")
lbl_name.place(x=5, y=5)
Now you can handle lbl_name as a label object. To hide it you can use:
lbl_name.place_forget()
Unfortunately, now its gone. Therefore, first save the place properties:
lbl_name = Label(root, text="Hello")
lbl_name.place(x=5, y=5)
lbl_name.saved = lbl_name.place_info()
You can now show it again with:
lbl_name.place(lbl_name.saved)
Note: You can print lbl_name.saved. It is a dictionary with all place-properties of the lbl_name Label object.

Tkinter Entry returns float values regardless of input

I have some pretty simple code right now that I am having issues with.
root = Tk()
label1 = Label(root, text ="Enter String:")
userInputString = Entry(root)
label1.pack()
userInputString.pack()
submit = Button(root,text = "Submit", command = root.destroy)
submit.pack(side =BOTTOM)
root.mainloop()
print(userInputString)
When I run the code everything operates as I would expect except
print(userInputString)
for an input asdf in the Entry print will return something like 0.9355325
But it will never be the same value back to back always random.
I am using python 3.5 and Eclipse Neon on a Windows 7 Machine.
Ultimately the goal is to accept a string from the user in the box that pops up and then be able to use that value as string later on. For example, it might be a file path that needs to be modified or opened.
Is Entry not the correct widget I should be using for this? Is there something inherently wrong with the code here? I am new to python and don't have a lot of strong programming experience so I am not even certain that this is set up right to receive a string.
Thanks in advance if anyone has any ideas.
There are two things wrong with your print statement. First, you print the widget, not the text in the widget. print(widget) prints str(widget), which is the tk pathname of the widget. The '.' represents the root window. The integer that follows is a number that tkinter assigned as the name of the widget. In current 3.6, it would instead be 'entry', so you would see ".entry".
Second, you try to print the widget text after you destroy the widget. After root.destroy, the python tkinter wrapper still exists, but the tk widget that it wrapped is gone. The following works on 3.6, Win10.
import tkinter as tk
root = tk.Tk()
label = tk.Label(root, text="Enter String:")
entry = tk.Entry(root)
def print_entry(event=None):
print(entry.get())
entry.bind('<Key-Return>', print_entry)
entry.focus_set()
submit = tk.Button(root, text="Submit", command=print_entry)
label.pack()
entry.pack()
submit.pack()
root.mainloop()
Bonus 1: I set the focus to the entry box so one can start typing without tabbing to the box or clicking on it.
Bonus 2: I bound the key to the submit function so one can submit without using the mouse. Note that the command then requires an 'event' parameter, but it must default to None to use it with the button.
The NMT Reference, which I use constantly, is fairly complete and mostly correct.

Get TkInter to display user input?

I am fairly new to TkInter and GUI in python (but I have experience with python in general). I was working on a GUI in TkInter and want to have users enter their name and have TkInter display there name when they click the button. Here is my code so far:
from Tkinter import *
master = Tk()
e = Entry(master)
e.pack()
e.focus_set()
def callback():
print e.get()
b = Button(master, text="get", width=10, command=callback)
b.pack()
separator = Frame(height=2, bd=1, relief=SUNKEN)
separator.pack(fill=X, padx=5, pady=5)
Label(text=callback).pack()
mainloop()
Users will enter their name in the Entry (or e) and I want to display e in the label widget. Any ideas on how I can do this? Thanks.
At the top (below the imports), define name as a StringVar:
name = StringVar()
In the function callback change the content to be:
def callback():
name.set(e.get())
And finally, change your Label widget to:
Label(master, textvariable=name)
So what I have done is created a special object with which when we change its value, the value of all references to it will change also. We can then set our function to change the value to update it globally- and we finish by utilizing this capability by putting this variable as the text attribute in our Label.
Note: I also added the parent argument to your Label. Without it, it wouldn't show up at all.

python tkinter popup window with selectable text

I want to make popup window using Tkinter.
I can do it so:
import Tkinter
a="some data that use should be able to copy-paste"
tkMessageBox.showwarning("done","message")
But there is one problem that user need to be able to select, copy and paste shown text.
It's not possible to do in such way.
Are there any ways to do it with Tkinter? (or another tools that is supplied with python by default)
Thanks in advance for any tips
From here, it seems a workaround using Entry in Tkinter is doable. Here is the code:
import Tkinter as Tk
root = Tk.Tk()
ent = Tk.Entry(root, state='readonly')
var = Tk.StringVar()
var.set('Some text')
ent.config(textvariable=var, relief='flat')
ent.pack()
root.mainloop()
EDIT: To respond to your comment, I found a way to insert multi-line text, using the Text widget.
Here is a draft of a solution:
from Tkinter import *
root = Tk()
T = Text(root, height=2, width=30, bg='lightgrey', relief='flat')
T.insert(END, "Just a text Widget\nin two lines\n")
T.config(state=DISABLED) # forbid text edition
T.pack()
mainloop()
I'm (still) interested in any better solution :)
You can use buttons for copy and paste. First you need to select. In a text widget it is easily done by
selection=nameoftextwidget.get(SEL_FIRST,SEL_LAST)
Then you can use this for copying easily by the use of selection. If you want to copy/paste it in that same text widget, you can use:
nameoftextwidget.insert(END,"\n"+selection)

Categories

Resources