How do I destroy a tkinter frame? - python

I am trying to make a tkinter frame that will contain an entry field and a submit button. When the submit button is pressed, I want to pass the entry string to the program and destroy the frame. After many experiments, I came up with this script:
from tkinter import *
from tkinter import ttk
import time
root = Tk()
entryframe = ttk.Frame(root)
entryframe.pack()
par = StringVar('')
entrypar = ttk.Entry(entryframe, textvariable=par)
entrypar.pack()
submit = ttk.Button(entryframe, text='Submit', command=entryframe.quit)
submit.pack()
entryframe.mainloop()
entryframe.destroy()
parval = par.get()
print(parval)
time.sleep(3)
root.mainloop()
When the "Submit" button is pressed, the parameter value is passed correctly to the script and printed. However, the entry frame is destroyed only after 3 seconds (set by the time.sleep function).
I want to destroy the entry frame immediately.
I have a slightly different version of the script in which the entry frame does get destroyed immediately (although the button itself is not destroyed), but the value of par is not printed:
from tkinter import *
from tkinter import ttk
import time
root = Tk()
entryframe = ttk.Frame(root)
entryframe.pack()
par = StringVar('')
entrypar = ttk.Entry(entryframe, textvariable=par)
entrypar.pack()
submit = ttk.Button(root, text='Submit', command=entryframe.destroy)
submit.pack()
entryframe.mainloop()
# entryframe.destroy()
parval = par.get()
print(parval)
time.sleep(3)
root.mainloop()
How can I get both actions, namely the entry frame destroyed immediately and the value of par printed?

Note 100% sure what you are trying to do but look at this code:
from tkinter import *
from tkinter import ttk
def print_results():
global user_input # If you want to access the user's input from outside the function
# Handle the user's input
user_input = entrypar.get()
print(user_input)
# Destroy whatever you want here:
entrypar.destroy()
submit.destroy()
# If you want you can also destroy the window: root.destroy()
# I will create a new `Label` with the user's input:
label = Label(root, text=user_input)
label.pack()
# Create a tkitner window
root = Tk()
# Create the entry
entrypar = ttk.Entry(root)
entrypar.pack()
# Create the button and tell tkinter to call `print_results` whenever
# the button is pressed
submit = ttk.Button(root, text="Submit", command=print_results)
submit.pack()
# Run tkinter's main loop
# It will stop only when all tkinter windows are closed
root.mainloop()
# Because of the `global user_input` now we can use:
print("Again, user_input =", user_input)
I defined a function which will destroy the entry and the button. It also creates a new label that displays the user's input.

I was able to accomplish what I wanted using the wait_window method. Here is the correct script:
from tkinter import *
from tkinter import ttk
root = Tk()
entryframe = ttk.Frame(root)
entryframe.pack()
entrypar = ttk.Entry(entryframe)
entrypar.pack()
submit = ttk.Button(entryframe, text='Submit', command=entryframe.destroy)
submit.pack()
entrypar.wait_window()
parval = entrypar.get()
print(parval)
close_button = ttk.Button(root, text='Close', command=root.destroy)
close_button.pack()
root.mainloop()
My intention was not fully apparent in my original question, and I apologize for that. Anyway, the answers did put me on the right track, and I am immensely thankful.

Related

how to cancel to call the function in python tkinter?

I am creating a reminder application in python using the Tkinter module. I need to cancel to call the function when the user clicks on the cancel remind button. I tried to assign the time (time variable that contains the time in milliseconds when the function will call) variable to 0, but it does not work.
sorry,for late respond i was creating small example this is the smallest example i can create.
code:
# example:
from tkinter import Tk, mainloop, TOP
from tkinter.ttk import Button
time=10000
# creating tkinter window
root = Tk()
def function_to_cancel():
global time
time=0 # not works
button = Button(root, text = 'Remind Me! after 10 seconds')
button.pack(side = TOP, pady = 5)
cancel=Button(root,text='Cancel Remind',command=function_to_cancel)#this button will cancel the remind
cancel.pack()
print('Running...')
root.after(time, root.destroy)
mainloop()
If you understand the question, please answer.
You need to save the task ID returned by .after() and then use the ID with .after_cancel() to cancel the scheduled task:
from tkinter import Tk, mainloop, TOP
from tkinter.ttk import Button
time=10000
# creating tkinter window
root = Tk()
def function_to_cancel():
#global time
#time=0 # not works
root.after_cancel(after_id)
button = Button(root, text = 'Remind Me! after 10 seconds')
button.pack(side = TOP, pady = 5)
cancel=Button(root,text='Cancel',command=function_to_cancel)#this button will cancel the remind
cancel.pack()
print('Running...')
# save the ID returned by after()
after_id = root.after(time, root.destroy)
mainloop()

How to close other window by python Tkinter?

I have following python code in Tkinter.
import tkinter as tk
def main_gui(login, s):
login.quit() # close login window
win = tk.Tk()
win.geometry('300x150')
name = tk.Label(win, text='Hello' + s.get()) # Hello David
name.pack()
win.mainloop()
# initial Tkinter frame
login = tk.Tk()
login.title('Login')
login.geometry('300x150')
# input user name
user_name_var = tk.StringVar()
user_name_var.set('David')
tk.Label(login, text='User name').place(x=10, y=50)
user_name = tk.Entry(login, textvariable=user_name_var)
user_name.place(x=100, y=50)
input_ok = tk.Button(win_login, command=lambda: main_gui(login, user_name), text='OK', width=15)
input_ok.place(x=100, y=90)
win_login.mainloop()
I want to close login window, but my code can not close it. How to solve it.
You are almost there - only two details you have to adapt:
The method to remove a widget in Tkinter is destroy, so login.quit() should be login.destroy().
Once login is destroyed, the user_name Entry will also be destroyed, and you will not be able to get the name from it anymore. You should get the name earlier, e.g., directly in the lambda:
... lambda: main_gui(login, user_name.get()), ...
you can use the
root.withdraw()
function, this will close the window without completely destroying all of the root.after functions

Trouble With Tkinter in Python [duplicate]

I'm trying to make a simple outline for a gui, and I'm getting the warning
"variable" May be undefined or defined from star imports: tkinter for all of my variables.
Here is my code:
from tkinter import *
class myApp :
def __init__(self, gui,) :
self.root = gui
self.bframe = Frame(self.root) # Create a container Frame at bottom
self.bframe.pack(side=BOTTOM)
self.xlabel = Label(self.root, text="Item ID") # Create the Label
self.xlabel.pack(side=LEFT)
self.xentry = Entry(self.root, bd=5) # Create the Entry box
self.xentry.pack(side=LEFT)
self.xentry.bind('<Return>', self.showStockItem)
self.xentry.focus_set() # Set focus in the Entry box
self.xopen = Button(self.root, text="Show", command=self.showStockItem) # Create the open Button
self.xopen.pack(side=LEFT)
self.xquit = Button(self.bframe, text="Quit", command=self.quitit) # Create the quit Button
self.xquit.pack(side=BOTTOM)
return
gui = Tk()
gui.title("Travel")
app = myApp(gui)
gui.mainloop()
from tkinter import *
In this line, you import everything from tkinter. This is not recommended, so linter will warn you. But if you really want to do this, it's OK, just ignore it.
To be better, you should explicitly import what you need. For example:
from tkinter import Tk, Label, Frame, Entry, Button
Consider using:
import tkinter as tk
and then, prefix all your calls like:
root = tk.Tk()
or,
variableName.pack(side = tk.LEFT)
and so on...

How To Let Your Main Window Appear after succesful login in Tkinter(PYTHON 3.6

This is ui which comes with default user name and password but after successful login the main UI needs to appear
Challenge
when you correctly input the user name and password the main window doesn't open but rather when you click cancel or close button then it opens
Finding solution
Main window should appear after successfully login with the default password and user name
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
def try_login(): # this my login function
if name_entry.get()==default_name and password_entry.get() ==
default_password:
messagebox.showinfo("LOGIN SUCCESSFULLY","WELCOME")
else:
messagebox.showwarning("login failed","Please try again" )
def cancel_login(): # exit function
log.destroy()
default_name=("user") #DEFAULT LOGIN ENTRY
default_password=("py36")
log=Tk() #this login ui
log.title("ADMIN-LOGIN")
log.geometry("400x400+400+200")
log.resizable (width=FALSE,height=FALSE)
LABEL_1 = Label(log,text="USER NAME")
LABEL_1.place(x=50,y=100)
LABEL_2 = Label(log,text="PASSWORD")
LABEL_2.place(x=50,y=150)
BUTTON_1=ttk. Button(text="login",command=try_login)
BUTTON_1.place(x=50,y=200)
BUTTON_1=ttk. Button(text="cancel",command=cancel_login)
BUTTON_1.place(x=200,y=200)
name_entry=Entry(log,width=30)
name_entry.place(x=150,y=100)
password_entry=ttk. Entry(log,width=30,show="*")
password_entry.place(x=150,y=150)
log. mainloop()
MAIN_WINDOW=Tk() #after successful this main ui should appear
MAIN_WINDOW.geometry("600x500+300+100")
MENU_1 = Menu(MAIN_WINDOW)
MAIN_WINDOW.config(menu=MENU_1)
SETTINGS_1 = Menu(MENU_1,tearoff=0)
MENU_1.add_cascade(label="SETTINGS",menu=SETTINGS_1,underline=0)
SETTINGS_1.add_command(label="Change Password")
MAIN_WINDOW. mainloop()
I would appreciate if the answers comes in functions as am newbie in python and programming in general
The below code can be used for the desired effect and is commented to show what is happening each step of the way:
from tkinter import * #Imports Tkinter
import sys #Imports sys, used to end the program later
root=Tk() #Declares root as the tkinter main window
top = Toplevel() #Creates the toplevel window
entry1 = Entry(top) #Username entry
entry2 = Entry(top) #Password entry
button1 = Button(top, text="Login", command=lambda:command1()) #Login button
button2 = Button(top, text="Cancel", command=lambda:command2()) #Cancel button
label1 = Label(root, text="This is your main window and you can input anything you want here")
def command1():
if entry1.get() == "user" and entry2.get() == "password": #Checks whether username and password are correct
root.deiconify() #Unhides the root window
top.destroy() #Removes the toplevel window
def command2():
top.destroy() #Removes the toplevel window
root.destroy() #Removes the hidden root window
sys.exit() #Ends the script
entry1.pack() #These pack the elements, this includes the items for the main window
entry2.pack()
button1.pack()
button2.pack()
label1.pack()
root.withdraw() #This hides the main window, it's still present it just can't be seen or interacted with
root.mainloop() #Starts the event loop for the main window
This makes use of the Toplevel widget in order to create a window which asks for the users details and then directs them to the main window which you can setup as you please.
You are also still able to use the pop up messages you have used in your example and if required you can also change the size of the Toplevel widget.
Please be advised however that this is not a particularly secure way of managing passwords and logins. As such I would suggest that you look up the proper etiquette for handling sensitive information in programming.

Refreshing a window in Tkinter

I am trying to make a GUI in Tkinter and am wondering how to refresh a window, namely if I fill in a rectangle, I want the GUI to delete it a specified time later. How would I go about doing this? Documentation on Tkinter seems to be thin...
Each Tkinter widget has a after method, which you can use to call your rectangle delete function e.g. in the example below first I change a msg using after, and then destruct the window using after
from Tkinter import *
def changeMsg():
label.configure(text="I will self destruct in 2 secs")
label.after(2000, root.destroy)
root = Tk()
mainContainer = Frame(root)
label = Label(mainContainer, text="")
label.configure(text="msg will change in 3 secs")
label.pack(side=LEFT, ipadx=5, ipady=5)
mainContainer.pack()
label.after(3000, changeMsg)
root.title("Timed event")
root.mainloop()

Categories

Resources