how to solve this: how to clear the tkinter label with button - python

I'm using tkinter.
I have a button to create a label with text in it. I want to clear that label with another button.
How can i do that?
I'm pretty new on tkinter. ıs there somebody to lead me

Here are a few options
Option 1
import tkinter as tk
root = tk.Tk()
label = tk.Label(root, text='Clear Me!')
label.pack()
# define a function to set the label text to an empty string
def clear_label_text():
label.config(text='')
# set up a button to call the above function
btn_clear = tk.Button(
root,
text='Click to Clear Label',
command=clear_label_text # note the lack of '()' here!
)
btn_clear.pack()
if __name__ == '__main__':
root.mainloop() # start the app
Option 2
This is a similar approach, but instead of defining a function to clear the label, we'll use a lambda (an anonymous function)
import tkinter as tk
root = tk.Tk()
label = tk.Label(root, text='Clear Me!')
label.pack()
# set up a button to clear the label
btn_clear = tk.Button(
root,
text='Click to Clear Label',
# lambdas make for clean code, but don't go crazy!
command=lambda: label.config(text='')
)
btn_clear.pack()
if __name__ == '__main__':
root.mainloop() # start the app
Neither of these methods will outright destroy the label, so you can set it's text again at any time a la label.config(text='New and improved text!')

from tkinter import *
root = Tk()
lab1 = Label(root, text = "Hello World")
lab1.pack()
but1 = Button(root, text = "clear", command=lab1.destroy)
but1.pack()
root.mainloop()

Related

How to have Tkinter Label text change when after certain amount of time?

I'm setting up a GUI Application, and I am having an issue with text changing on a Tkinter Label on a time.sleep() timer.
I have tried something like
label_text = Label(main_window, text="hello world")
time.sleep(3)
label_text = Label(main_window, text="hello world")
(take note that I have the grid system and tkinter window setup, I am just not going to show all code inside of this)
# Currently this is not working how I would like it to, but here is the code
main_window = tkinter.Tk()
label_text = Label(main_window, text="hello world")
time.sleep(3)
label_text = Label(main_window, text="hello")
label_text.grid(column=1, row=1)
main_window.mainloop()
and this
main_window = tkinter.Tk()
main_window.resizable(False, False)
main_window.geometry("500x900")
text = StringVar()
text.set("hello")
label = Label(main_window, text=text)
label.grid(column=1, row=1)
time.sleep(3)
text.set("anoefn")
main_window.update()
main_window.mainloop()
Thank you!
I think this does what you want. You need to use tk_obj.after to get the timedelay.
In the code in the question sleep delays the calling of mainloop by 3 seconds.
main_window = tk.Tk()
label_text = tk.Label(main_window, text="hello world")
def on_after():
label_text.configure( text="hello")
label_text.grid(column=1, row=1)
label_text.after(3000, on_after) # after 3000 ms call on_after
main_window.mainloop()
As the comments say you could use StringVar, linked to the label. Then on_after would need to change StringVar instead of configuring the label.
Edit: For completeness a version with StringVar
main_window = tk.Tk()
var=tk.StringVar()
var.set("Hello World")
label_text = tk.Label(main_window, textvariable=var)
def on_after():
var.set("Hello ") # set the StringVar instead of configuring the label.
label_text.grid(column=1, row=1)
label_text.after(3000, on_after)
main_window.mainloop()
Try using the StringVar() datatype
mytext = StringVar()
label_text = Label(main_window, text=mytext)
mytext.set("hello")
#after sometime change the text as required
mytext.set("new text")
hopefully, this will work.

How do I use a tkinter entry as a parameter for a function

I would like a text box to ask for input in a tkinter window, then use that input as a parameter to call a function that draws a Sierpinski triangle. My buttons work but my input box does not. I keep trying to fix my code but it is not working, any help would be appreciated.
import tkinter as tk
from tkinter import *
root = tk.Tk()
frame = tk.Frame(root)
frame.pack()
root.title('Fractals') #titles the button box
top_frame = tk.Frame()
mid_frame = tk.Frame()
prompt_label = tk.Label(top_frame, \
text='Enter a number of iterations (more is better):')
iterations = tk.Entry(root,bd=1)
itr=iterations.get()
itr=int(itr)
button = tk.Button(frame,
text="QUIT",
fg="red",
command=quit)
button.pack(side=tk.LEFT)
sTriangle = tk.Button(frame,
text="Triangle",
command=lambda: sierpinski(fred, (-500,-500), (500,-500),
(0,500),itr))
sTriangle.pack(side=tk.LEFT)
fsquare = tk.Button(frame,
text="Square",
command=fractalsquare(fred,(-500,-500),(500,-500),
(500,500),(-500,500),itr))
fsquare.pack(side=tk.LEFT)
root.mainloop()
There are several issues:
1) Choose one way to import tkinter or confusion will result
2) You should provide a master for your Frames and then pack them. Pay attention on where the frames appear and what they contain.
3) It's usual to assign a textvariable to the Entry which will contain what you enter into it. The textvariable should be a tk.StringVar.
4) If a Button has a callback function, it must be defined before you create the button.
5) The variable fred is not defined.
Example of how you can write it:
import tkinter as tk
root = tk.Tk()
root.title('Fractals') #titles the button box
# Create the Label at the top
top_frame = tk.Frame(root) # Top Frame for
top_frame.pack()
prompt_label = tk.Label(top_frame,
text='Enter a number of iterations (more is better):')
prompt_label.pack()
# Create the Entry in the middle
mid_frame = tk.Frame(root)
mid_frame.pack()
itr_string = tk.StringVar()
iterations = tk.Entry(mid_frame,textvariable=itr_string)
iterations.pack()
fred=None # Was not defined...
# Create Buttons at the bottom
bot_frame = tk.Frame(root)
bot_frame.pack()
button = tk.Button(bot_frame, text="QUIT", fg="red", command=quit)
button.pack(side=tk.LEFT)
def sierpinski(*args): # sTriangle button callback function
itr = int(itr_string.get()) # How to get text from Entry
# if Entry does not contain an integer this will throw an exception
sTriangle = tk.Button(bot_frame, text="Triangle",
command=lambda: sierpinski(fred, (-500,-500), (500,-500),(0,500),itr_string))
sTriangle.pack(side=tk.LEFT)
def fractalsquare(*args): pass # fsquare button callback function
fsquare = tk.Button(bot_frame, text="Square", command=fractalsquare(fred,
(-500,-500),(500,-500),(500,500),(-500,500),itr_string))
fsquare.pack(side=tk.LEFT)
root.mainloop()
You should seriously study a basic tkinter tutorial. Try this one: An Introduction To Tkinter

Print output in GUI interface Tkinter Python

from Tkinter import *
def printSomething():
print "Hey whatsup bro, i am doing something very interresting."
root = Tk()
button = Button(root, text="Print Me", command=printSomething)
button.pack()
root.mainloop()
The output is coming in the terminal from where i am running the code
I need the output in GUI interface.
Using print only prints to the terminal or a fp. You can create a new Label to "print" to the GUI.
from Tkinter import *
def printSomething():
# if you want the button to disappear:
# button.destroy() or button.pack_forget()
label = Label(root, text= "Hey whatsup bro, i am doing something very interresting.")
#this creates a new label to the GUI
label.pack()
root = Tk()
button = Button(root, text="Print Me", command=printSomething)
button.pack()
root.mainloop()
AN EXAMPLE FOR YOUR COMMENT
from Tkinter import *
def printSomething():
# if you want the button to disappear:
# button.destroy() or button.pack_forget()
for x in range(9): # 0 is unnecessary
label = Label(root, text= str(x))
# this creates x as a new label to the GUI
label.pack()
root = Tk()
button = Button(root, text="Print Me", command=printSomething)
button.pack()
root.mainloop()
I think you have nothing to put your "Hey whatsup bro, i am doing something very interresting." in. In tkinter you need something like a Label to put text out, or you create a new def and define there what the button have to do, if someone click on it.

How to make a Label appear then disappear after a certain amount of time in python tkinter

I would like for a cant afford label to appear then after a second disappear when i push a button to buy something. It seems like the time.sleep(1) is making it not work properly. This is done on python tkinter.
def buttonpressed():
Label.place(x = 500, y = 500 #where i want the label to appear
time.sleep(1)
Label.place(x = 10000, y = 10000) #moving it away where i wont be able to see it
You can't use sleep because it stops mainloop
You can use root.after(time_in_milliseconds, function_name) to run function
Example
import tkinter as tk
def button_pressed():
# put text
label['text'] = "Hello World!"
# run clear_label after 2000ms (2s)
root.after(2000, clear_label)
def clear_label():
# remove text
label['text'] = ""
root = tk.Tk()
label = tk.Label(root) # empty label for text
label.pack()
button = tk.Button(root, text="Press Button", command=button_pressed)
button.pack()
root.mainloop()
If you have to create and remove label then use label.destroy()
import tkinter as tk
def button_pressed():
label = tk.Label(root, text="Hello World!")
label.pack()
root.after(2000, destroy_widget, label) # label as argument for destroy_widget
def destroy_widget(widget):
widget.destroy()
root = tk.Tk()
button = tk.Button(root, text="Press Button", command=button_pressed)
button.pack()
root.mainloop()
And shorter version without destroy_widget
import tkinter as tk
def button_pressed():
label = tk.Label(root, text="Hello World!")
label.pack()
root.after(2000, label.destroy)
root = tk.Tk()
button = tk.Button(root, text="Press Button", command=button_pressed)
button.pack()
root.mainloop()
Press button many times to see many labels which disappear after 2s.
You can use after() to set up a callback after a specified interval. In the callback function clear the label with pack_forget() (or grid_forget() if you're using grid). This is better than setting the label's text attribute to an empty string because that causes widgets to be resized, which might not be what you want. Here's an example:
import Tkinter as tk
class App():
def __init__(self):
self.root = tk.Tk()
self.label = tk.Label(text='I am a label')
self.label.place(x=0, y=0)
self.label.after(1000, self.clear_label) # 1000ms
self.root.mainloop()
def clear_label(self):
print "clear_label"
self.label.place_forget()
app=App()
Another option is to use self.label.destroy() to destroy the widget, however, pack_forget() allows you to display the label again by calling pack() on the widget again.
# I made it through calling 2 functions:
from tkinter import *
root = Tk()
root.geometry('400x200') # width by height
def one_text():
label['text'] = "Look around"
root.after(1000, another_text)
def another_text():
label['text'] = "and smile"
root.after(1000, one_text)
label= Label(root ,font=('Helvetica', 14), fg='black', bg='white')
label.pack()
one_text()
root.mainloop()

New windows in tkinter

I have a bit of difficulty with the code below. Basically, I want the code to, when I press the Enter button, to open the window2 but also close window1 simultaneously so that there is only one window and not two of them.
The code is...
from tkinter import *
def window1():
window = Tk()
window.title("Welcome")
f = Frame()
f.pack()
label1 = Label(window, text = "Welcome to the random window")
label1.pack()
button1 = Button(window, text = "Enter...", command = window2)
button1.pack()
def window2():
screen = Tk()
screen.title("Pop-Up!")
fr = Frame()
fr.pack()
label2 = Label(screen, text = "This is a pop-up screen!")
label2.pack()
button2 = Button(screen, text = "Return", command = window1)
button2.pack()
window1()
This is "Bad" because you're using two instances of Tk. Try instead using TopLevels.
import tkinter as tk
def window1():
window = tk.Toplevel(root)
window.title("Welcome")
# etc etc ...
tk.Button(window,text="Enter...",command=lambda: window2(window)).pack()
def window2(old_window):
old_window.destroy()
# window2 stuff
root = tk.Tk()
root.iconify() # to minimize it, since we're just using Toplevels on top of it
window1()
root.mainloop()
When you are using the Tk() function, you are creating a new instance of the Tcl/tkinter interpreter. Instead use Toplevel() which will make a new window in the current interpreter.

Categories

Resources