Python Tkinter display the name with Hi in front of it - python

Hello I'm a few weeks into python and I'm now starting learning tkinter. The button should have the text Say hello and when the user clicks the button, the bottom label should display the name with Hi in front of it. However I cannot get the label to display "Hi {name}". Could someone help me?
from tkinter import *
from tkinter.ttk import *
def process_name():
"""Do something with the name (in this case just print it)"""
global name_entry
print("Hi {}".format(name.get()))
def main():
"""Set up the GUI and run it"""
global name_entry
window = Tk()
name_label = Label(window, text='Enter name a name below:')
name_label.grid(row=0, column=0)
name_entry = Entry(window)
name_entry.grid(row=1, column=3)
button = Button(window, text='Say hello', command=process_name, padding=10)
button.grid(row=1, column=0, columnspan=2)
window.mainloop()
main()
I've tried using set() but it doesn't display.
Thank you.

This should work for your needs. Make sure to read the code comments to understand what I did properly.
Few points though,
Not recommended to use wildcard import like from tkinter import * . The reason is simple. both tkinter and tkinter.ttk have common classes and functions like Button, Label and more. It becomes ambiguous for interpreter to decide which ones to use.
use .config() or .configure() to update labels, buttons, entries or text widgets in tkinter. Like I did in code below.
Your code modified
from tkinter import *
from tkinter.ttk import *
def process_name():
"""Do something with the name (in this case just print it)"""
global name_entry # this will print hi {name} to terminal.
print("Hi {}".format(name_entry.get()))
global nameLabel # to change'the label with hi{name} text below the button.
nameLabel.configure(text=f'Hi {name_entry.get()}')
def main():
"""Set up the GUI and run it"""
global name_entry, nameLabel
window = Tk()
name_label = Label(window, text='Enter name a name below:')
name_label.grid(row=0, column=0)
name_entry = Entry(window)
name_entry.grid(row=1, column=3)
button = Button(window, text='Say hello', command=process_name, padding=10)
button.grid(row=1, column=0, columnspan=2)
# I defined a label BELOW the button to show how to change
nameLabel = Label(window, text=' ') # an empty text Label
nameLabel.grid(row=2)
window.mainloop()
main()

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:

How to display text on a new window Tkinter?

I've started learning Tkinter on Python few weeks ago and wanted to create a Guess Game. But unfortunately I ran into a problem, with this code the text for the rules ( in the function Rules; text='Here are the rules... ) doesn't appear on the window ( rule_window).
window = Tk()
window.title("Guessing Game")
welcome = Label(window,text="Welcome To The Guessing Game!",background="black",foreground="white")
welcome.grid(row=0,column=0,columnspan=3)
def Rules():
rule_window = Tk()
rule_window = rule_window.title("The Rules")
the_rules = Label(rule_window, text='Here are the rules...', foreground="black")
the_rules.grid(row=0,column=0,columnspan=3)
rule_window.mainloop()
rules = Button(window,text="Rules",command=Rules)
rules.grid(row=1,column=0,columnspan=1)
window.mainloop()
Does anyone know how to solve this problem?
In your code you reset whatever rule_window is to a string (in this line: rule_window = rule_window.title(...))
Try this:
from import tkinter *
window = Tk()
window.title("Guessing Game")
welcome = Label(window, text="Welcome To The Guessing Game!", background="black", foreground="white")
welcome.grid(row=0, column=0, columnspan=3)
def Rules():
rule_window = Toplevel(window)
rule_window.title("The Rules")
the_rules = Label(rule_window, text="Here are the rules...", foreground="black")
the_rules.grid(row=0, column=0, columnspan=3)
rules = Button(window, text="Rules", command=Rules)
rules.grid(row=1, column=0, columnspan=1)
window.mainloop()
When you want to have 2 windows that are responsive at the same time you can use tkinter.Toplevel().
In your code, you have initialized the new instances of the Tkinter frame so, instead of you can create a top-level Window. What TopLevel Window does, generally creates a popup window kind of thing in the application. You can also trigger the Tkinter button to open the new window.
from tkinter import *
from tkinter import ttk
#Create an instance of tkinter window
root= Tk()
root.geometry("600x450")
#Define a function
def open_new():
#Create a TopLevel window
new_win= Toplevel(root)
new_win.title("My New Window")
#Set the geometry
new_win.geometry("600x250")
Label(new_win, text="Hello There!",font=('Georgia 15 bold')).pack(pady=30)
#Create a Button in main Window
btn= ttk.Button(root, text="New Window",command=open_new)
btn.pack()
root.mainloop()

how to add text instead of replacing them while using tkinter

I’m working on a project that uses tkinter and the buttons. So lets say my window has a text 'hi' and a button that displays 'bye' when I click it. When I click it 'hi' is replaced with 'bye', but I want to append 'bye'. How do I stop it from replacing my existing text?
This is my code:
from tkinter import *
window = Tk()
window.title("Welcome ")
window.geometry('1000x200')
lbl = Label(window, text="Hi")
lbl.grid(column=0, row=0)
def click():
lbl.configure(text="bye")
btn = Button(window, text="click here", command=click)
btn.grid(column=1, row=0)
window.mainloop()
You can use cget to get the content, then update it as you wish; for instance:
def click():
lbl.configure(text=lbl.cget('text')+" bye")

Entry data manipulation difficulties [duplicate]

I'm trying to use an Entry field to get manual input, and then work with that data.
All sources I've found claim I should use the get() function, but I haven't found a simple working mini example yet, and I can't get it to work.
I hope someone can tel me what I'm doing wrong. Here's a mini file:
from tkinter import *
master = Tk()
Label(master, text="Input: ").grid(row=0, sticky=W)
entry = Entry(master)
entry.grid(row=0, column=1)
content = entry.get()
print(content) # does not work
mainloop()
This gives me an Entry field I can type in, but I can't do anything with the data once it's typed in.
I suspect my code doesn't work because initially, entry is empty. But then how do I access input data once it has been typed in?
It looks like you may be confused as to when commands are run. In your example, you are calling the get method before the GUI has a chance to be displayed on the screen (which happens after you call mainloop.
Try adding a button that calls the get method. This is much easier if you write your application as a class. For example:
import tkinter as tk
class SampleApp(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.entry = tk.Entry(self)
self.button = tk.Button(self, text="Get", command=self.on_button)
self.button.pack()
self.entry.pack()
def on_button(self):
print(self.entry.get())
app = SampleApp()
app.mainloop()
Run the program, type into the entry widget, then click on the button.
You could also use a StringVar variable, even if it's not strictly necessary:
v = StringVar()
e = Entry(master, textvariable=v)
e.pack()
v.set("a default value")
s = v.get()
For more information, see this page on effbot.org.
A simple example without classes:
from tkinter import *
master = Tk()
# Create this method before you create the entry
def return_entry(en):
"""Gets and prints the content of the entry"""
content = entry.get()
print(content)
Label(master, text="Input: ").grid(row=0, sticky=W)
entry = Entry(master)
entry.grid(row=0, column=1)
# Connect the entry with the return button
entry.bind('<Return>', return_entry)
mainloop()
*
master = Tk()
entryb1 = StringVar
Label(master, text="Input: ").grid(row=0, sticky=W)
Entry(master, textvariable=entryb1).grid(row=1, column=1)
b1 = Button(master, text="continue", command=print_content)
b1.grid(row=2, column=1)
def print_content():
global entryb1
content = entryb1.get()
print(content)
master.mainloop()
What you did wrong was not put it inside a Define function then you hadn't used the .get function with the textvariable you had set.
you need to put a textvariable in it, so you can use set() and get() method :
var=StringVar()
x= Entry (root,textvariable=var)
Most of the answers I found only showed how to do it with tkinter as tk. This was a problem for me as my program was 300 lines long with tons of other labels and buttons, and I would have had to change a lot of it.
Here's a way to do it without importing tkinter as tk or using StringVars. I modified the original mini program by:
making it a class
adding a button and an extra method.
This program opens up a tkinter window with an entry box and an "Enter" button. Clicking the Enter button prints whatever is in the entry box.
from tkinter import *
class mini():
def __init__(self):
master = Tk()
Label(master, text="Input: ").grid(row=0, sticky=W)
Button(master, text='Enter', command=self.get_content).grid(row=1)
self.entry = Entry(master)
self.entry.grid(row=0, column=1)
master.mainloop()
def get_content(self):
content = self.entry.get()
print(content)
m = mini()

.get() not giving a value [duplicate]

I'm trying to use an Entry field to get manual input, and then work with that data.
All sources I've found claim I should use the get() function, but I haven't found a simple working mini example yet, and I can't get it to work.
I hope someone can tel me what I'm doing wrong. Here's a mini file:
from tkinter import *
master = Tk()
Label(master, text="Input: ").grid(row=0, sticky=W)
entry = Entry(master)
entry.grid(row=0, column=1)
content = entry.get()
print(content) # does not work
mainloop()
This gives me an Entry field I can type in, but I can't do anything with the data once it's typed in.
I suspect my code doesn't work because initially, entry is empty. But then how do I access input data once it has been typed in?
It looks like you may be confused as to when commands are run. In your example, you are calling the get method before the GUI has a chance to be displayed on the screen (which happens after you call mainloop.
Try adding a button that calls the get method. This is much easier if you write your application as a class. For example:
import tkinter as tk
class SampleApp(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.entry = tk.Entry(self)
self.button = tk.Button(self, text="Get", command=self.on_button)
self.button.pack()
self.entry.pack()
def on_button(self):
print(self.entry.get())
app = SampleApp()
app.mainloop()
Run the program, type into the entry widget, then click on the button.
You could also use a StringVar variable, even if it's not strictly necessary:
v = StringVar()
e = Entry(master, textvariable=v)
e.pack()
v.set("a default value")
s = v.get()
For more information, see this page on effbot.org.
A simple example without classes:
from tkinter import *
master = Tk()
# Create this method before you create the entry
def return_entry(en):
"""Gets and prints the content of the entry"""
content = entry.get()
print(content)
Label(master, text="Input: ").grid(row=0, sticky=W)
entry = Entry(master)
entry.grid(row=0, column=1)
# Connect the entry with the return button
entry.bind('<Return>', return_entry)
mainloop()
*
master = Tk()
entryb1 = StringVar
Label(master, text="Input: ").grid(row=0, sticky=W)
Entry(master, textvariable=entryb1).grid(row=1, column=1)
b1 = Button(master, text="continue", command=print_content)
b1.grid(row=2, column=1)
def print_content():
global entryb1
content = entryb1.get()
print(content)
master.mainloop()
What you did wrong was not put it inside a Define function then you hadn't used the .get function with the textvariable you had set.
you need to put a textvariable in it, so you can use set() and get() method :
var=StringVar()
x= Entry (root,textvariable=var)
Most of the answers I found only showed how to do it with tkinter as tk. This was a problem for me as my program was 300 lines long with tons of other labels and buttons, and I would have had to change a lot of it.
Here's a way to do it without importing tkinter as tk or using StringVars. I modified the original mini program by:
making it a class
adding a button and an extra method.
This program opens up a tkinter window with an entry box and an "Enter" button. Clicking the Enter button prints whatever is in the entry box.
from tkinter import *
class mini():
def __init__(self):
master = Tk()
Label(master, text="Input: ").grid(row=0, sticky=W)
Button(master, text='Enter', command=self.get_content).grid(row=1)
self.entry = Entry(master)
self.entry.grid(row=0, column=1)
master.mainloop()
def get_content(self):
content = self.entry.get()
print(content)
m = mini()

Categories