I want to add a clear button in tkinter which clears the text I have entered already and the output. How can I do that?
Here is my code which gets input and provide output using Label.
from tkinter import *
root = Tk()
def myFunction():
k = myInput.get()
labl = Label(root,text=k)
labl.pack()
myInput = Entry(root,width=50, bg="#d2ebd5",borderwidth=5)
myInput.pack()
myButton = Button(root,text="Click me!",command=myFunction)
myButton.pack()
root.mainloop()
Use myInput.set("") to clear Entry var, move labl from function to main level, create another function to clear Entry var and labl text and button to run it.
Related
I'm trying to make a button that saves your username but then goes away after you set it.
this is my code:
def printValue():
User = Name.player_name.get()
label.config(text=f'Hi, {User}')
Name.button.destroy()
Name.player_name.destroy()
def Name():
label.config(text="What's your name?")
Name.player_name = Entry(root)
Name.player_name.pack(pady=15)
Name.button = Button(text="Change", command=printValue)
Name.button.pack()
The code below, with some minor changes like enabling change with [Return] and some layout cosmetics works OK (also with un-commented lines in printValue) . If you want the [Change] button and the entry area to go away un-comment the two lines turned into comments in the printValue function:
# https://stackoverflow.com/questions/72671126/tkinter-destroying-an-object-in-a-different-function-isnt-working
from tkinter import Tk, mainloop, Entry, Button, Label
root = Tk()
label = Label(root, font=('',12), padx=15, pady=5)
label.pack()
def Name():
label.config(text="What's your name?")
Name.player_name = Entry(root, font=('',12))
Name.player_name.pack(padx=15, pady=15)
Name.player_name.focus()
Name.button = Button(text="Change", command=printValue)
Name.button.pack()
def printValue(event=None):
User = Name.player_name.get()
# Name.player_name.destroy()
# Name.button.destroy()
label.config(text=f'Hi, {User}')
Name()
root.bind("<Return>", printValue)
mainloop()
By the way: The in the question provided code demonstrates an interesting approach of making names of variables global by setting function attributes in the function itself. This way it is possible to assign values in one function and retrieve them in another without passing return values or declaring variables global. I am not aware of already having seen such approach used in Python code here on stackoverflow. How does it come you use such code?
I am trying to get my code to display text from a print statement onto the Tkinter GUI - does anyone know how to do this?
Use this:
import tkinter as tk
# This function acts just like the `print` function:
def print_on_gui(*args, sep=" ", end="\n"):
text = sep.join(args) + end
# Set the Text widget's state to normal so that we can edit its text
text_widget.config(state="normal")
# Insert the text at the end
text_widget.insert("end", text)
# Set the Text widget's state to disabled to disallow the user changing the text
text_widget.config(state="disabled")
# Create a new tkinter window
root = tk.Tk()
# Create a new `Text` widget
text_widget = tk.Text(root, state="disabled")
# Show the widget on the screen
text_widget.pack(fill="both", expand=True)
# Your code should go here
print_on_gui("Hello world!")
print_on_gui("Hello", "world!")
# Go inside tkinter's mainloop
root.mainloop()
The problem with this approach is that if your program runs for too long, it can make the window unresponsive. To avoid that you can use threading but that will complicate things a lot more. If you want to, I can write a solution that uses threading.
Python Checkbutton reads value only once
I've looked in StackOverflow for any similar problems, but the only one that looked similar was this here. It suggested that in this case the variable should be set global but I don't think that's a good solution. So I'm asking you guys for a better one.
I want to use Checkbutton() in Python and my code looks (simplified) like this...
#!/usr/bin/env
from Tkinter import *
Fenster = Tk()
Fenster.title ("Sensors")
Number = IntVar()
Button = Checkbutton(Fenster, text = "Check me", variable = Number, onvalue = 1, offvalue = 0)
print Number.get()
Button.pack()
mainloop()
When i run this code, the window opens and i see the Checkbox. So far so good. But when I want to check or uncheck it, the value of "Number" somehow doesn't change. It only displays "1", probably from the first frame, and never changes.
Could you give me some advice how to improve this?
You need to check the value of number; you can do this by assigning a command to print number, when the button is clicked:
import tkinter as tk # <-- avoid star imports
def f():
print(number.get())
fenster = tk.Tk()
fenster.title ("Sensors")
number = tk.IntVar()
button = tk.Checkbutton(fenster, text="Check me", variable=number, command=f)
button.pack()
fenster.mainloop() # call mainloop on your root window
I am a new python user. I'm used to programing on matlab.
I've trying to make a simple GUI with Tkinter pack, but I'm having some problems with that. I had already read and searched what i want but I couldn't develop it.
What I'm trying to do is to make a listbox and when I choose one (or more) options the index be returned (and stored) as a variable (array or vector) that could be used to indexing another array.
The best result I got was a listbox where the index were printed, but not stored as a variable (at least it hasn't been shows in the variables list)
I'm using spyder (anaconda).
I tryied a lot of codes and I don't have this anymore.
Sorry for the dumb question. I guess I still thinking in a Matlab way to write
To keep this application simple, your best option is to get the listbox selection when you want to do something with it:
from tkinter import Tk, Listbox, MULTIPLE, END, Button
def doStuff():
selected = lb.curselection()
if selected: # only do stuff if user made a selection
print(selected)
for index in selected:
print(lb.get(index)) # how you get the value of the selection from a listbox
def clear(lb):
lb.select_clear(0, END) # unselect all
root = Tk()
lb = Listbox(root, selectmode=MULTIPLE) # create Listbox
for n in range(5): lb.insert(END, n) # put nums 0-4 in listbox
lb.pack() # put listbox on window
# notice no parentheses on the function name doStuff
doStuffBtn = Button(root, text='Do Stuff', command=doStuff)
doStuffBtn.pack()
# if you need to add parameters to a function call in the button, use lambda like this
clearBtn = Button(root, text='Clear', command=lambda: clear(lb))
clearBtn.pack()
root.mainloop()
I've also added a button to clear the listbox selection because you cannot unselect items by default.
First, import tkinter, then, create the listbox. Then, you can use curselection to get the contents of the listbox.
import tkinter as tk
root = tk.Tk() #creates the window
myListbox = tk.Listbox(root, select=multiple) #allows you to select multiple things
contentsOfMyListbox = myListbox.curselection(myListbox) #stores selected stuff in tuple
See the documentation here.
I am trying to create a simple popup text entry for the user in which a user enters a text and hits submit (a button). Upon clicking submit, I want the popup entry box to close off and continue on with the rest of the code. Following is a sample code for display that I borrowed from an old post here:
from Tkinter import *
root = Tk()
nameLabel = Label(root, text="Name")
ent = Entry(root, bd=5)
def getName():
print ent.get()
submit = Button(root, text ="Submit", command = getName)
nameLabel.pack()
ent.pack()
submit.pack(side = BOTTOM)
root.mainloop()
print "Rest of the code goes here"
I don't have much experience with Tkinter so I am not sure where and how exactly to call the appropriate functions for closing the entry box after the user hits 'Submit'. My guess is it would have to be inside the getName() function?
If I understand you correctly, then all you need to do is call the root window's destroy method at the end of the getName function:
def getName():
print ent.get()
root.destroy()
Doing so is equivalent to manually clicking the X button in the corner of the window.
Alternate method:
since there isn't much to your popup you could also eliminate several lines of code in your GUI, save some CPU and get pretty much the same output with this:
submitvariablename=raw_input('Please enter a Name')
same functionality and much faster, cleaner.
Just a thought.