Copy a label on tkinter and change the text on button click? - python

I have some program of this kind of type:
from tkinter import *
def apply_text(lbl_control):
lbl_control['text'] = "This is some test!"
master = Tk()
lbl = Label(master)
btn = Button(master, text="apply", command=lambda: apply_text(lbl))
lbl.pack()
btn.pack()
mainloop()
My aim now is to copy the text of the label lbl itself without any ability to change it. I tried the following way to solve the problem:
from tkinter import *
def apply_text(lbl_control):
lbl_control.insert(0, "This is some test!")
master = Tk()
lbl = Entry(master, state="readonly")
btn = Button(master, text="apply", command=lambda: apply_text(lbl))
lbl.pack()
btn.pack()
mainloop()
because of state = "readonly" it is not possible to change the text insert of lbl anymore. For that reason nothing happens if I click on the button apply. How can I change it?

There is a simple way to do that simple first change the state of entry to normal, Then insert the text, and then change the state back to readonly.
from tkinter import *
def apply_text(lbl_control):
lbl_control['state'] = 'normal'
lbl_control.delete(0,'end')
lbl_control.insert(0, "This is some test!")
lbl_control['state'] = 'readonly'
master = Tk()
lbl = Entry(master, state="readonly")
btn = Button(master, text="apply", command=lambda: apply_text(lbl))
lbl.pack()
btn.pack()
mainloop()
There is another way to do this using textvariable.
Code:(Suggested)
from tkinter import *
def apply_text(lbl_control):
eText.set("This is some test.")
master = Tk()
eText = StringVar()
lbl = Entry(master, state="readonly",textvariable=eText)
btn = Button(master, text="apply", command=lambda: apply_text(lbl))
lbl.pack()
btn.pack()
mainloop()

Related

How to open a link with an specific button? Tkinter

Basically, when I want to open a specific link with a specific button it won't work. When you click the second button, it opens all the links inside the function.
from tkinter import *
import webbrowser
root = Tk()
root.title("links")
root.geometry("700x500")
root.config(bg="#3062C7")
def links_unit1():
global vid_1, vid_2
bg_v1 = Canvas(root, bg="#3062C7", width=700, height=500)
bg_v1.place(x=0, y=0)
vid_1 = Button(root, text="Virtual memory", command=all_vids1)
vid_1.place(x=20, y=20)
vid_2 = Button(root, text="lossy, lossless", command=all_vids1)
vid_2.place(x=30, y=50)
def all_vids1():
if vid_1:
webbrowser.open("https://youtu.be/AMj4A1EBTTY")
elif vid_2:
webbrowser.open("https://youtu.be/v1u-vY6NEmM")
vid_unit1 = Button(root, text="Unit 1", command=links_unit1)
vid_unit1.place(x=10, y=10)
root.mainloop()
You can't do it by checking the values of vid_1 and vid_2 because they will always be truthy. Instead you can create to anonymous function "on-the-fly" by using a lambda expression for the command= option of the Button as shown below:
from tkinter import *
import webbrowser
root = Tk()
root.title("links")
root.geometry("700x500")
root.config(bg="#3062C7")
def links_unit1():
bg_v1 = Canvas(root, bg="#3062C7", width=700, height=500)
bg_v1.place(x=0, y=0)
vid_1 = Button(root, text="Virtual memory",
command=lambda: webbrowser.open("https://youtu.be/AMj4A1EBTTY"))
vid_1.place(x=20, y=20)
vid_2 = Button(root, text="Lossy, Lossless",
command=lambda: webbrowser.open("https://youtu.be/v1u-vY6NEmM"))
vid_2.place(x=30, y=50)
vid_unit1 = Button(root, text="Unit 1", command=links_unit1)
vid_unit1.place(x=10, y=10)
root.mainloop()

How do I make my button know what`s in the entry box and then print that value in a new window?

I want after you write something in the entry box and then you press the button a new window to pop up and
the number that was written in the entry box to be printed in the new window as " Your height is: "value" but after many tries I still don`t understand how to do it.
my code:
import tkinter as tk
root = tk.Tk()
root.geometry("250x130")
root.resizable(False, False)
lbl = tk.Label(root, text="Input your height", font="Segoe, 11").place(x=8, y=52)
entry = tk.Entry(root,width=15).place(x=130, y=55)
btn1 = tk.Button(root, text="Enter", width=12, height=1).place(x=130, y=85) #command=entrytxt1
root.mainloop()
This is what I got:
import tkinter as tk
root = tk.Tk()
root.resizable(False, False)
def callback():
# Create a new window
new_window = tk.Toplevel()
new_window.resizable(False, False)
# `entry.get()` gets the user input
new_window_lbl = tk.Label(new_window, text="You chose: "+entry.get())
new_window_lbl.pack()
# `new_window.destroy` destroys the new window
new_window_btn = tk.Button(new_window, text="Close", command=new_window.destroy)
new_window_btn.pack()
lbl = tk.Label(root, text="Input your height", font="Segoe, 11")
lbl.grid(row=1, column=1)
entry = tk.Entry(root, width=15)
entry.grid(row=1, column=2)
btn1 = tk.Button(root, text="Enter", command=callback)
btn1.grid(row=1, column=3)
root.mainloop()
Basically when the button is clicked it calls the function named callback. It creates a new window, gets the user's input (entry.get()) and puts it in a label.

What is a good way to stop 2 labels in the same row and column from covering each other in tkinter?

When button 1 is pressed I want this program to say word 'hi' and when button 2 is pressed I want it to say 'goodbye' in the same spot as it says hi and override what button 1 produced. However, it doesn't override it just merges the 2 labels together. What is a good way to prevent this from happening while making sure both labels appear in the same spot?
from tkinter import *
root = Tk()
def press():
word = Label(root, text='hi')
word.grid(row=0, column=1)
def press_2():
word_2 = Label(root, text='goodbye')
word_2.grid(row=0, column=1)
button_1 = Button(root, text=1, command=press)
button_2 = Button(root, text=2, command=press_2)
button_1.grid(row=0, column=0)
button_2.grid(row=1, column=0)
root.mainloop()
You just need to use one Label and keep changing its text. We can do this efficiently by using a lambda for the widget command. As stated by #Bryan Oakley, using a StringVar adds unnecessary overhead. This is a slightly modified version from my original. In this version we use the config method of the widget to set the text. As a bonus the code is formatted with a class structure. Using a procedural style with tkinter eventually turns into a big mess. Considering the required imports are minimal, we import them directly and do not need to prefix every widget.
from tkinter import Tk, Button, Label
class Application(Tk):
def __init__(self, *args, **kwargs):
Tk.__init__(self, *args, **kwargs)
lbl = Label(self, text='hi')
lbl.grid(row=0, column=1)
btn1 = Button(self, text='1',)
btn1.config(command=lambda m='hi': lbl.config(text=m))
btn1.grid(row=0, column=0)
btn2 = Button(self, text='2')
btn2.config(command=lambda m='goodbye': lbl.config(text=m))
btn2.grid(row=1, column=0)
if __name__ == "__main__":
app = Application()
app.minsize(100, 50)
app.title("My Application")
app.mainloop()
from tkinter import *
root = Tk()
def press():
label['text'] = "hi"
def press_2():
label['text'] = "goodbye"
label = Label(root)
label.grid(row=0, column=1)
button_1 = Button(root, text=1, command=press)
button_2 = Button(root, text=2, command=press_2)
button_1.grid(row=0, column=0)
button_2.grid(row=1, column=0)
root.mainloop()
Put it on the windows firstly,Then change the text config.
A better way to do so would be by using config() method of widgets. But here i dont know if its gonna help out much. But give it a try
from tkinter import *
root = Tk()
def press():
word.config(text='hi')
def press_2():
word.config(text='goodbye')
button_1 = Button(root, text=1, command=press)
button_2 = Button(root, text=2, command=press_2)
button_1.grid(row=0, column=0)
button_2.grid(row=1, column=0)
word = Label(root, text='') #creating a blank label to edit later on in functions
word.grid(row=0, column=1)
root.mainloop()

Python Tkinter doesn't show the label when I press the button

I have one Input and one button. I want the value of the input (Entry) to when I press the button. When I type print(mtext) it works well, but when I put it in a Label it doesn't work.
Here is the code:
from tkinter import *
root = Tk()
root.title("Mohamed Atef")
root.geometry("900x600")
var = StringVar()
var.set("Please write something")
label = Label(root, textvariable=var, padx=10, pady=10)
#input
text = StringVar()
entry = Entry(root, textvariable=text)
def mohamed():
mtext = text.get()
mohamed = Label(root, textvariable=mtext)
mohamed.pack()
#button
buttonText = StringVar()
buttonText.set("Click me !")
button = Button(root, textvariable=buttonText, command=mohamed)
label.pack()
entry.pack()
button.pack()
root.mainloop()
Same as Flilp, your finished product would look like this
from tkinter import *
root = Tk()
root.title("Mohamed Atef")
root.geometry("900x600")
var = StringVar()
var.set("Please write something")
label = Label(root, textvariable=var, padx=10, pady=10)
#input
text = StringVar()
entry = Entry(root, textvariable=text)
def mohamed() :
mtext = text.get()
mohamed = Label(root, text=mtext)
mohamed.pack()
#button
buttonText = StringVar()
buttonText.set("Click me !")
button = Button(root, textvariable=buttonText, command=mohamed)
label.pack()
entry.pack()
button.pack()
root.mainloop()
If you just want text that's in your Entry to appear under your labels you could do:
def mohamed():
mohamed = Label(root, textvariable=text)
mohamed.pack()
Your code didn't work because value passed as textvariable should be tkinter StringVar() not string.
If you don't want the text to be constantly updated when you change your Entry you should do:
def mohamed():
mtext = text.get()
mohamed = Label(root, text=mtext)
mohamed.pack()

Tkinter new window

I'm relatively new to Tkinter and I need help.
I have created a new window when a button is clicked from the parent window. The new window is the def new_Window. But I can't seem to get the information in the window as coded below:
from tkinter import *
from tkinter import ttk
#User Interface Code
root = Tk() #Creates the window
root.title("Quiz Game")
def new_window():
newWindow = Toplevel(root)
display = Label(newWindow, width=200, height=50)
message = Label(root, text="Welcome")
display.pack()
message.pack()
display2 = Label(root, width=100, height=30)
button1 = Button(root, text ="Continue", command=new_window, width=16,
bg="red")
message_label = Label(root, text="Click 'Continue' to begin.",
wraplength=250)
username = StringVar() #Stores the username in text
user_entry = Entry(root, textvariable=username) #Creates an entry for the
username
user_entry.pack()
display2.pack()
button1.pack()
message_label.pack()
root.mainloop()#Runs the main window loop
Thanks for your help.
You did not pack the hello label into the new window. A tip is also to use background colors to visualize labels when developing. Here is a functioning code for you. I only changed 2 lines, added foreground and background.
from tkinter import *
from tkinter import ttk
# User Interface Code
root = Tk() # Creates the window
root.title("Quiz Game")
def new_window():
newWindow = Toplevel(root)
display = Label(newWindow, width=200, height=50,bg='RED')
message = Label(newWindow, text="HEEEY",fg='BLACK',bg='GREEN')
message.pack()
display.pack()
display2 = Label(root, width=100, height=30)
button1 = Button(root, text ="Continue", command=new_window, width=16,
bg="red")
message_label = Label(root, text="Click 'Continue' to begin.",
wraplength=250)
username = StringVar() # Stores the username in text
user_entry = Entry(root, textvariable=username) # Creates an entry for the
username
user_entry.pack()
display2.pack()
button1.pack()
message_label.pack()
root.mainloop() # Runs the main window loop

Categories