subroot window editing - tkinter - python

I'm sure this is going to amount to my misunderstanding of what I'm calling. So I'm trying to make edits to a second window but I don't know that I'm doing it right as it doesn't appear to change. Under def open_win() I created a second window registration(which is supposed to be the equivalent of root). I got the second window to take the Screen position/size but for some reason it wont add the label/entry
from tkinter import *
from functools import partial
#outputs to IDLE
def validateLogin(username, password):
print("username entered :", username.get())
print("password entered :", password.get())
return
#centering Registration page
def open_win():
registration=Toplevel(root)
registration.title("Registration Page")
window_width=600
window_height=400
screen_width =registration.winfo_screenwidth()
screen_height =registration.winfo_screenheight()
center_x=int(screen_width/2-window_width/2)
center_y=int(screen_height/2-window_height/2)
registration.geometry(f'{window_width}x{window_height}+{center_x}+{center_y}')
#registration label and text entry box
usernameLabel=Label(registration, text="User Name").grid(row=0, column=1)
username=StringVar()
usernameEntry=Entry(registration, textvariable =UserName).grid(row=0, column=2)
#Root Window
root=Tk()
root.title('Sign in Page')
#centering window
window_width=600
window_height=400
screen_width =root.winfo_screenwidth()
screen_height =root.winfo_screenheight()
center_x=int(screen_width/2-window_width/2)
center_y=int(screen_height/2-window_height/2)
root.geometry(f'{window_width}x{window_height}+{center_x}+{center_y}')
#username label and text entry box
usernameLabel=Label(root, text="User Name").grid(row=0, column=1)
username=StringVar()
usernameEntry=Entry(root, textvariable=username).grid(row=0, column=2)
#password label and password entry box
passwordLabel=Label(root,text="Password").grid(row=1, column=1)
password=StringVar()
passwordEntry=Entry(root, textvariable=password, show='*').grid(row=1, column=2)
validateLogin=partial(validateLogin, username, password)
#login button
loginButton=Button(root, text="Login", command=validateLogin).grid(row=4, column=1)
SignUpButton=Button(root, text="Sign up", command=open_win).grid(row=4, column=2)
#registration label and text entry box
usernameLabel=Label(registration, text="User Name").grid(row=0, column=1)
username=StringVar()
usernameEntry=Entry(registration, textvariable =UserName).grid(row=0, column=2)
root.mainloop()

Your main issue with not being able to work with the 2nd window is basically a issue of namespace. Your registration variable is stored in the local namespace of the function. If you want to edit it from outside the function like you attempt to do then you need your variable to be in the global namespace.
Because you appear to try and write the same label and entry field a couple of times to the registration top window then I suspect you do not actually need to edit it from outside the function but need to edit it when you created the window.
I have cleaned up your code a little and condensed it to make it a little easier to read.
You should first import tkinter ask tk instead of importing *. This will help prevent any issue with overwriting imports down the road and it makes it a little easier to ID what is referencing a tk widget or some other function.
You use 2 different naming conventions in your code. Chose one and stick with that. It will improve readability. I recommend following PEP8 guidelines.
Items that are not going to be changed later do not need to have variables assigned to them so you can clean up your code a bit there also.
You do not need to go the extra mile to use StringVar here. We can simply pull directly from the entry field as long as the geometry manager (ie grid()) is assigned on a new line so you can still access the variable reference for the entry field.
I am not sure what you were needing partial() for and I think you should use lambda instead in this situation.
If you have any questions let me know.
import tkinter as tk
def validate_login(username, password):
print("username entered :", username.get())
print("password entered :", password.get())
def open_win():
reg = tk.Toplevel(root)
reg.title("Registration Page")
reg.geometry(f'600x400+{int(reg.winfo_screenwidth()/2-600/2)}+{int(reg.winfo_screenheight()/2-400/2)}')
tk.Label(reg, text="User Name").grid(row=0, column=1)
r_un = tk.Entry(reg)
r_un.grid(row=0, column=2)
root = tk.Tk()
root.title('Sign in Page')
root.geometry(f'600x400+{int(root.winfo_screenwidth()/2-600/2)}+{int(root.winfo_screenheight()/2-400/2)}')
tk.Label(root, text="User Name").grid(row=0, column=1)
un = tk.Entry(root)
un.grid(row=0, column=2)
tk.Label(root, text="Password").grid(row=1, column=1)
pw = tk.Entry(root, show='*')
pw.grid(row=1, column=2)
tk.Button(root, text="Login", command=lambda u=un, p=pw: validate_login(u, p)).grid(row=4, column=1)
tk.Button(root, text="Sign up", command=open_win).grid(row=4, column=2)
root.mainloop()

Related

I am trying to have my "multible label widget" as well as my "creating buttons" but when when i get one to work the other does not

Here is the code that i have scripted i know it looks bad i am a total noob at this but i really need help. I want my GUI to show the "welcome" and "this gui was written by..." message at the bottom and then add the button functions that i am later going to intergrate with a api.
from cProfile import label
from tkinter import *
root = Tk()
def create_label():
# creating multible label widgets
myLabel1= Label(root,text="Welcome")
myLabel2= Label(root,text=" ")
myLabel3= Label(root,text=" ")
myLabel4= Label(root,text=" ")
myLabel5= Label(root,text="This Gui was written by Seha")
# Showing it on the screen and putting it in rows and columns
myLabel1.grid(row=0, column=10)
myLabel2.grid(row=1, column=10)
myLabel4.grid(row=2, column=10)
myLabel3.grid(row=3, column=10)
myLabel5.grid(row=4, column=10)
create_label.pack()
def create_button():
# Creating buttons
myButton= Button(root, text="Click on this button to check floor price for a specific collection: ",command=label)
myButton2= Button(root, text="Click on this button to check the 24h volume for a specific collection:", command=label)
myButton.pack()
myButton2.pack()
root.mainloop()
This is what my code looks like and i screenshotted what the gui shows
[1]: https://i.stack.imgur.com/jJnxu.png

how to get an output message from tkinter?

I'm trying to make a quiz app and I have written the following code which is incomplete I am trying to get an output message from the app which gives the answer which the student has written it seems funny but i will do some more stuff on it too. the output I want should be something like this:
the client enters 12
the app shows another box which says your answer is 12
but in this example it is being done for a single answer and it should be performable for more questions too.
import tkinter as tk
from tkinter import *
import math
import random
window=tk.Tk()
def question():
window=tk.Tk()
q1=tk.Label(window, text="enter your question").grid(row=1, column=1)
e1=tk.Entry(window, text="the number of your answer ").grid(row=2, column=1)
b1=tk.Button(window, text="exit", command=window.destroy).grid(row=3, column=1)
window.mainloop()
after your helps I have changed my code to this but still have prolems getting a message box or something like that. the updated code is as follows. now the problem is that as soon as I run the code the empty message box opens and does not wait for me to enter some value into the entry
def question():
window=tk.Tk()
q1=tk.Label(window, text="enter your question")
e1=tk.Entry(window, text="the number of your answer ")
b1=tk.Button(window, text="exit", command=window.destroy)
q1.grid(row=1, column=1)
e1.grid(row=2, column=1)
b1.grid(row=3, column=1)
e1_num=e1.get()
while e1_num==None:
pass
else:
messagebox.showinfo(e1_num)
mainloop()
You could use e1.insert('0', 'subject') to insert something into the entry. You can also replace 'subject' with a variable. To delete the contents of the entry you can use e1.delete(0,END)
You can get the information from the Entry (e1) and store in it a variable like so: e1_num = e1.get()
I hope this helps you :D
Solution to your problem:
from tkinter import *
import tkinter as tk
def question():
window=tk.Tk()
window.geometry('200x125')
window.title('Test')
q1=tk.Label(window, text="Enter your question")
e1=tk.Entry(window)
e2=tk.Entry(window)
b1=tk.Button(window, text="Exit", command=window.destroy)
def Enter():
e1_num = e1.get()
e2.insert('0', e1_num)
q1.pack()
e1.pack()
b2=Button(window, text='Enter', command=Enter)
b2.pack()
e2.pack()
b1.pack()
window.mainloop()
question()
What it will look like:

python entry widget and get method

Is there any way to put the textvariable in another variable and not have to use the ".get()"? I've been doing a lot of sifting thorugh tutorials and articles for what I realize is a very small issue but I'm probably misunderstanding something pretty key so i'm hoping someone can help me develop some intuition for the entry widget and .get() method.
Below is part of a script that I've been working on where I want to take the text entered in the entry box and use it later. I can use it if I use search_word.get(), but I don't why I can't do something like New_variable=search_word.get() so that from that point on I can just use "New_variable".
import tkinter as tk
from tkinter import *
from tkinter import ttk
Text_input_window = Tk()
Text_input_window.geometry('600x350+100+200')
Text_input_window.title("Test")
label_1=ttk.Label(Text_input_window, text="Enter word to search:", background="black", foreground="white")
label_1.grid(row=1, column=0, sticky=W)
search_word=StringVar()
entry_1=ttk.Entry(Text_input_window,textvariable=search_word, width=40, background="white")
entry_1.grid(row=2, column=0, sticky=W)
New_variable=StringVar()
New_variable=search_word.get()
def click():
print(New_variable)
print(search_word.get())
Text_input_window.destroy()
btn_1=ttk.Button(Text_input_window, text="submit", width=10, command=click)
btn_1.grid(row=3, column=0, sticky=W)
Text_input_window.mainloop()
Problem is not .get() but how all GUIs works.
mainloop() starts program so new_variable = search_word.get() is executed before you even see window - so it tries to get text before you put text in Entry.
You have to do it inside click() which is executed after you put text in entry and click button.
import tkinter as tk
# --- functions ---
def click():
global new_variable # inform function to use external/global variable instead of creating local one
#new_variable = entry.get() # you can get it directly from `Entry` without StringVar()
new_variable = search_word.get()
root.destroy()
# --- main ---
new_variable = '' # create global variable with default value
root = tk.Tk()
search_word = tk.StringVar()
entry = tk.Entry(root, textvariable=search_word)
entry.pack()
btn = tk.Button(root, text="submit", command=click)
btn.pack()
root.mainloop() # start program
# --- after closing window ---
print('new_variable:', new_variable)
print('search_word:', search_word.get()) # it seems it still exists
# print('entry:', entry.get()) # `Entry` doesn't exists after closing window so it gives error
Is there any way to put the textvariable in another variable and not have to use the ".get()"?
No, there is not. Tkinter variables are objects, not values. Anytime you want to use a value from a tkinter variable (StringVar, IntVar, etc) you must call the get method.

Placing Tkinter Frame in another Frame

I am trying to experiment and get the button to only display the label when the button is clicked instead it is opening up another GUI window. The main frame is called secret message. Within this when i click onto the button it should then replace the empty place with the label in row=2.
Could someone explain to me how i can raise the label rather than just opening up a new window. All code is functional but i want another way around this, i am new to python.
from tkinter import *
def topLevel():
top=Toplevel()
top.geometry("300x200")
root=Tk()
root.title("Secret Message")
button1 = Button(text="Push this button to see hidden message!", width =60, command=topLevel)
button1.grid(row=1, column=0)
label1 = Label(width=50, height=10, background="WHITE", text= "There is no secret!")
label1.grid(row=2, column=0)
root.mainloop()
You question title has nothing to do with your question.
To update the geometry of your label you simple need to tell the function where you want the label on the container you set up your label in. In this case you do not define the container so the widgets default to the root window.
Here is a working example that will update the label geometry when you press the button.
from tkinter import *
root=Tk()
root.title("Secret Message")
def grid_label():
label1.config(text="There is no secret!")
Button(root, text="Push this button to see hidden message!", width=60, command=grid_label).grid(row=1, column=0)
label1 = Label(root, width=50, height=10, background="WHITE")
label1.grid(row=2, column=0)
root.mainloop()

Tkinter GUI and import python program

I have a program that does automation by logging to the devices using netmiko library. Tkinter is the front end to provide details like Device getting connected to Username and password. If I keep all the things in a single program it works.
Now I want tkinter GUI program to call program separately using import function. By doing so I want to pass values retried from GUI frontend to backend program to do some function. Where I got stuck is some values that need to pass are inside the backend function collected from frontend GUI.
Seems after import the program its not working, any help would be appreciated.
e1 e2 and e3 values are not passing under show_entry_details function created in separate python file which i imported.
''' the code is regarding tkinter application which works at the front end to prompt user for some info, which later passes to other program to call some function.'''
# Head of Tkinter application
master = Tk()
master.title("Network Automation")
# configuration for the labels and entry
Label(master, text="Device : ").grid(row=0)
Label(master, text="User ID : ").grid(row=1)
Label(master, text="Password : ").grid(row=2)
e1 = Entry(master)
e2 = Entry(master)
e3 = Entry(master, show='*')
e1.grid(row=0, column=1)
e2.grid(row=1, column=1)
e3.grid(row=2, column=1, )
# configuration for the button
Button(master, text='Quit', command=master.destroy).grid(row=4, column=0, sticky=W, pady=4)
Button(master, text='Harden', command=show_entry_fields).grid(row=4, column=1, sticky=W, pady=4)
mainloop()
To pass arguments to a button's command, you can use a lambda expression:
button = Button(master,
text='Harden',
command=lambda: show_entry_fields(e1.get(), e2.get(), e3.get()))
button.grid(row=4, column=1)

Categories

Resources