Python getting User input with Tkinter - python

In my Python program somehwere in between i pop-up a Tkinter GUI to get user Input. User selects option from a Tkinter.ttk Combobox. From here once the user closes the Tkinter window i want the selection made by user to be used further in the code. But upon close unable to get the user selection back into the code.
Please help.

One way is to create a StringVar() in the root window and then associate it with the Combobox() in the Toplevel() window. The combobox will change the value of the StringVar() and you can read it affter popup window is closed.
from tkinter import *
from tkinter import ttk
root = Tk()
combotext = StringVar()
def get_input():
popup = Toplevel()
box = ttk.Combobox(popup, textvariable=combotext, state='readonly')
box['values'] = ("Camembert", "Brie", "Tilsit", "Stilton")
combotext.set('Choose')
box.pack(padx=20, pady=20)
Button(root, text='Get input', command=get_input).pack(padx=90, pady=10)
Label(root, textvariable=combotext).pack(pady=(0,10))
root.mainloop()

Related

My browse window in tkinter goes under the toplevel tkinter window where topmost enabled

I will try to simplify my question here. My problem is like, on my first window of tkinter I have a button that opens another tkinter window. You can say it a second window to keep it on top I use win2.attributes('-topmost', True). Then I have a browse button to import file from the computer but when I click it goes under the window 2.
Following is my code.
from tkinter import *
from tkinter.filedialog import askopenfilename
root = Tk()
root.title("Base Window")
root.geometry("300x300")
def browse():
file_to_open = askopenfilename()
def new_window():
win2 = Toplevel(root)
win2.title("Window 2")
win2.geometry("300x300")
win2.attributes('-topmost', True)
Button2 = Button(win2, text="Browse", command=browse).pack()
button1 = Button(root, text="New window", command=new_window).pack()
root.mainloop()
My browse window is going under the window 2. Can you please suggest me the best way to keep it on top. I am sharing the screenshot of the problem as well
Starting code
Click on new window
Click browse button and the browse window is hidden
Cheers
You need to set the parent option of askopenfilename() to the toplevel window win2:
from tkinter import *
from tkinter.filedialog import askopenfilename
root = Tk()
root.title("Base Window")
root.geometry("300x300")
def browse(parent):
file_to_open = askopenfilename(parent=parent)
def new_window():
win2 = Toplevel(root)
win2.title("Window 2")
win2.geometry("300x300")
win2.attributes('-topmost', True)
# pass 'win2' to browse()
Button2 = Button(win2, text="Browse", command=lambda:browse(win2)).pack()
button1 = Button(root, text="New window", command=new_window).pack()
root.mainloop()

How to remove/disable the minimize button in Tkinter without removing/disabling the close button

I am building a simple login system using Tkinter in python, for that I need a non-resizable and it can be done by 'resizable(0,0) but it only disables the maximize button. But I what the minimize button to be disabled also, so please someone help me find the solution for these.
Here's the sample of my code,
from tkinter import *
root = Tk()
root.geometry("400x300")
def signIn():
# Opening a new window for SignIn options
signin = Toplevel()
signin.grab_set()
signin.focus_set()
# I also tried this but it removes the whole title bar along with the close 'X' button
# root.overrideredirect(True)
# SignIn button
button = Button(root, text="Sign In", command=signIn)
button.grid(row=1, column=0)
root.mainloop()
from tkinter import *
root = Tk()
root.geometry("400x300")
root.attributes('-toolwindow', True)
def signIn():
# Opening a new window for SignIn options
signin = Toplevel()
signin.grab_set()
signin.focus_set()
# I also tried this but it removes the whole title bar along with the close 'X' button
# root.overrideredirect(True)
# SignIn button
button = Button(root, text="Sign In", command=signIn)
button.grid(row=1, column=0)
root.mainloop()
If you want to disable the minimize and maximize use this. It will leave you with only the x button. I gave example for only removing maximize and then one for both.
import tkinter as tk
import time
root = tk.Tk()
root.geometry("500x500")
root.resizable(False, False)#removes only the maximize option
root.attributes("-toolwindow", True)#removes both the maximize and the minimize option
root.mainloop()

How do I destroy a tkinter frame?

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.

How to disable keyboard inputs when using Entry on Tkinter on python?

How can I disable keyboard input entries when using Entry on Tkinter in python
I was coding for a calculator project in python. So I need to make a screen like text box using Entry.
I couldn't remove keyboard inputs from the Entry field.
You can set the state of Entry widget to DISABLED.
Example:-
win = tk.Tk()
ent = Entry(win, state=DISABLED)
ent.pack()
you can disable keyboard characters from an Entry field in Tkinter using:
from tkinter import *
root=Tk()
txtDisplay = Entry(root, width=28, justify=RIGHT)
txtDisplay.grid(row=0, column=0, columnspan=5, pady=1)
txtDisplay.bind("<Key>", lambda e: "break") # Disable characters from keyboard
root.mainloop()

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.

Categories

Resources