How do I make entry boxes in a second window? - python

I have been trying to make an entry box for people to enter their names, as part of a "registration" for a mini-program that I am doing, but the result is that an entry box doesn't appear at all.
Here is the section of the code that is troubling me:
def win2(self):
# this is the child window
board = Toplevel()
board.title("Sign up")
board.focus_set()
board.grab_set()
userVar = StringVar()
userVar.set('Username')
square1Label = Label(board,textvariable=userVar)
square1Label.grid(row=0, column=7)
userEnt=Entry(self)
userEnt.grid(row=1, column=7)
s2Var = StringVar()
s2Var.set('First Name')
square2Label = Label(board,textvariable=s2Var)
square2Label.grid(row=1, column=7)
leaveButton = Button(board, text="Quit", command=board.destroy)
leaveButton.grid(row=1, column=1, sticky='nw')
board.wait_window(board)
And here is the coding in full, minus the importing of Tkinter and the mainloop:
class Application(Frame):
"""GUI Application for making Baakibook"""
def __init__(self, parent):
"""Initialize the frame"""
Frame.__init__(self, parent, bg="light blue")
self.win1()
# different windows
def win1(self):
# this is the main/root window
signupButton = Button(root, text="Sign up", command=self.win2)
signupButton.grid(row=9, column=7)
loginButton = Button(root, text="Log in", command=self.win3)
loginButton.grid(row=10, column=7)
leaveButton = Button(root, text="Quit", command=root.destroy)
leaveButton.grid(row=1, column=1, sticky='nw')
b1Var = StringVar()
b2Var = StringVar()
b1Var.set('b1')
b2Var.set('b2')
box1Label = Label(root,textvariable=b1Var,width=12)
box1Label.grid(row=3, column=2)
box2Label = Label(root,textvariable=b2Var,width=12)
box2Label.grid(row=3, column=3)
root.mainloop()
def win2(self):
# this is the child window
board = Toplevel()
board.title("Sign up")
board.focus_set()
board.grab_set()
userVar = StringVar()
userVar.set('Username')
square1Label = Label(board,textvariable=userVar)
square1Label.grid(row=0, column=7)
userEnt=Entry(self)
userEnt.grid(row=1, column=7)
s2Var = StringVar()
s2Var.set('First Name')
square2Label = Label(board,textvariable=s2Var)
square2Label.grid(row=1, column=7)
leaveButton = Button(board, text="Quit", command=board.destroy)
leaveButton.grid(row=1, column=1, sticky='nw')
board.wait_window(board)
def win3(self):
# this is the child window
board = Toplevel()
board.title("Login User")
board.focus_set()
board.grab_set()
s1Var = StringVar()
s2Var = StringVar()
s1Var.set("s1")
s2Var.set("s2")
square1Label = Label(board,textvariable=s1Var)
square1Label.grid(row=0, column=7)
square2Label = Label(board,textvariable=s2Var)
square2Label.grid(row=0, column=6)
leaveButton = Button(board, text="Quit", command=board.destroy)
leaveButton.grid(row=1, column=1, sticky='nw')
board.wait_window(board)

The first argument you use to create the widget is what parent you want it assigned to. So, this line:
userEnt=Entry(self)
userEnt.grid(row=1, column=7)
makes the Entry widget in the Frame that you created in __init__. If you want it to appear in the Toplevel, create it like the other widgets you made in that method, ie:
userEnt=Entry(board)
userEnt.grid(row=1, column=7)
Also, your grid in the Toplevel doesn't make sense right now and a couple of your widgets will appear stacked until you change it.

Related

how to add admin priviledge with tkinter

I’m coding a database management app with python tkinter packages. This API is on a NAS (network attached storage). So the users can open it from a connection and make modifications in real time.
I want to give some privilege for admin users. That means if a users log in the app, they can tick and fill entry box which is disabled for normal users.
How to do it?
Here is my try:
from tkinter import *
import tkinter as tk
from tkinter import ttk
#Initialisation
root=Tk()
root.title("Test")
#Tab creation
my_tab=ttk.Notebook(root)
my_tab.pack(expand=True, fill=tk.BOTH)
#Tab name and their creation
frames=[]
nom_des_onglets=["Main", "First tab", "Second tab"]
def admin():
global longentrie
win=Toplevel()
longentrie = StringVar()
password_msg = tk.Label(win,text="Enter password for administrator privileges")
password_msg.pack()
password_entries = tk.Entry(win,textvariable=longentrie)
password_entries.pack()
tk.Button(win,text='Enter', command=admin_privilege).pack()
def admin_privilege():
global login_value
password_admin = longentrie.get()
if password_admin == 'good':
login_value=1
else:
login_value=0
for i in range(3):
frame=ttk.Frame(my_tab) # add tab
frame.pack(fill="both")
frames.append(frame)
my_tab.add(frames[i], text=nom_des_onglets[i])
#Login button
login=tk.Button(frames[0],text="login", command=admin)
login.pack()
#special priviledge
var1 = tk.IntVar()
ts = [tk.StringVar() for _ in range(17)]
lbl7 = tk.Checkbutton(frames[1], text='Text',variable=var1, onvalue=1,offvalue=0, bg='#ececec', state='disabled')
lbl7.grid(row=0, column=0, padx=5, pady=3)
lbl1=tk.Label(frames[1], text="Name")
lbl1.grid(row=2, column=0, padx=5, pady=3)
ent7=Entry(frames[1], textvariable=ts[6])
ent7.grid(row=2, column=1, padx=5, pady=3,sticky="nsew")
lbl8=tk.Label(frames[1], text="Age")
lbl8.grid(row=3, column=0, padx=5, pady=3)
ent8=Entry(frames[1], textvariable=ts[7],state='disabled')
ent8.grid(row=3, column=1, padx=5, pady=3,sticky="nsew")
if login_value == 1:
lbl7.configure(state='normal')
ent8.configure(state='normal')
root.mainloop()
Here's an example where entering the right password does correctly change the disabled state of those two fields.
This could be refactored to be a lot less messy (better variable naming for one), but it's a start:
import tkinter as tk
from tkinter import ttk
is_admin = False
def setup_ui():
lbl7.configure(state=("normal" if is_admin else "disabled"))
ent8.configure(state=("normal" if is_admin else "disabled"))
def do_login_window():
def admin_privilege():
global is_admin
if password_var.get() == "good":
is_admin = True
setup_ui()
login_win.destroy() # Close the login box
login_win = tk.Toplevel()
password_var = tk.StringVar()
password_msg = tk.Label(login_win, text="Enter password for administrator privileges")
password_msg.pack()
password_entries = tk.Entry(login_win, textvariable=password_var)
password_entries.pack()
tk.Button(login_win, text="Enter", command=admin_privilege).pack()
# Initialisation
root = tk.Tk()
root.title("Test")
# Tab creation
my_tab = ttk.Notebook(root)
my_tab.pack(expand=True, fill=tk.BOTH)
frames = []
for name in ["Main", "First tab"]:
frame = ttk.Frame(my_tab)
frame.pack(fill="both")
frames.append(frame)
my_tab.add(frame, text=name)
# Login button
login_frame = frames[0]
login = tk.Button(login_frame, text="login", command=do_login_window)
login.pack()
# special priviledge
data_frame = frames[1]
var1 = tk.IntVar()
ts = [tk.StringVar() for _ in range(17)]
lbl7 = tk.Checkbutton(
data_frame, text="Text", variable=var1, onvalue=1, offvalue=0, bg="#ececec"
)
lbl7.grid(row=0, column=0, padx=5, pady=3)
lbl1 = tk.Label(data_frame, text="Name")
lbl1.grid(row=2, column=0, padx=5, pady=3)
ent7 = tk.Entry(data_frame, textvariable=ts[6])
ent7.grid(row=2, column=1, padx=5, pady=3, sticky="nsew")
lbl8 = tk.Label(data_frame, text="Age")
lbl8.grid(row=3, column=0, padx=5, pady=3)
ent8 = tk.Entry(data_frame, textvariable=ts[7])
ent8.grid(row=3, column=1, padx=5, pady=3, sticky="nsew")
setup_ui() # Will be called after logging in too
root.mainloop()

How can I remove items on a Tkinter window?

I am trying to clear the items on the window without closing the root window just the items visible.While everything is deleted Some of the labels are still left.I created a button "close" to remove the items.My code is as below;
from tkinter import*
root = Tk()
root.geometry("480x480")
# Node
myLabel1 = Label(root, text=f'Node')
myLabel1.grid(row=0, column=0)
rows = [] # show the input entry boxes
for i in range(6):
# name
entry = Entry(root, width=5, bd=5)
entry.grid(row=2+i, column=0)
# x
myLabel2 = Label(root, text=f'x{i}')
myLabel2.grid(row=2+i, column=1)
entry_x = Entry(root, width=5, bd=5)
entry_x.grid(row=2+i, column=2)
# y
myLabel3 = Label(root, text=f'y{i}')
myLabel3.grid(row=2+i, column=3)
entry_y = Entry(root, width=5, bd=5)
entry_y.grid(row=2+i, column=4)
# save current input row
rows.append((entry, entry_x, entry_y))
def close():
for name,ex,ey in rows:
name.destroy()
ex.destroy()
ey.destroy()
myLabel3.destroy()
myLabel2.destroy()
myLabel1.destroy()
myButton_close.destroy()
myButton_close = Button(root, text="close",padx = 10,pady = 10, command=close)
myButton_close.grid(row=8, column=6)
root.mainloop()
where could i be going wrong?
Create a Frame to hold the widgets and then you can destroy the frame to clear the window:
from tkinter import *
root = Tk()
root.geometry("480x480")
frame = Frame(root)
frame.pack(fill=BOTH, expand=1)
# Node
myLabel1 = Label(frame, text=f'Node')
myLabel1.grid(row=0, column=0)
rows = [] # store the input entry boxes
for i in range(6):
# name
entry = Entry(frame, width=5, bd=5)
entry.grid(row=2+i, column=0)
# x
myLabel2 = Label(frame, text=f'x{i}')
myLabel2.grid(row=2+i, column=1)
entry_x = Entry(frame, width=5, bd=5)
entry_x.grid(row=2+i, column=2)
# y
myLabel3 = Label(frame, text=f'y{i}')
myLabel3.grid(row=2+i, column=3)
entry_y = Entry(frame, width=5, bd=5)
entry_y.grid(row=2+i, column=4)
# save current input row
rows.append((entry, entry_x, entry_y))
def close():
frame.destroy()
myButton_close = Button(frame, text="close", padx=10, pady=10, command=close)
myButton_close.grid(row=8, column=6)
root.mainloop()
Grouping widgets into a frame make it easier to clear certain part of the window.
You create the labels in a loop but you are not saving any reference to the labels except for the last myLabel2/3. However you can ask a widget about its children, and then destroy them all:
def close():
for widget in root.winfo_children():
widget.destroy()

Graphical user interface with TK - button position and actions

I started using TK in python to build a graphical interface for my program.
I'm not able to fix 2 issues concerning (1) the position of a button in the window and (2) use a value of a radiobutton inside a fucntion.
This is my current code:
root = tk.Tk()
root.title("START")
root.geometry("500x200+500+200")
v = tk.IntVar()
v.set(0) # initializing the choice
my_choise = [
("Basic",1),
("Advanced",2),
('Extreme',3)
]
def ShowChoice():
print(v.get())
tk.Label(root,
text="""Choose your configuration:""",
justify = tk.LEFT,
padx = 20).pack()
val = 0
for val, choise in enumerate(my_choise):
tk.Radiobutton(root,text=choise,padx = 20,variable=v,command=ShowChoice,value=val).pack(anchor=tk.W)
def star_program(value):
os.system("ifconfig")
def open_comments_file():
os.system("gedit /home/user/Desktop/comments.txt")
def open_links_file():
os.system("gedit /home/user/Desktop/links.txt")
frame = tk.Frame(root)
frame.pack()
open_file_c = tk.Button(frame,
text="Comments",
command=open_comments_file)
open_file_f = tk.Button(frame,
text="Links",
command=open_links_file)
button = tk.Button(frame,
text="Start",
command=star_program(v.get()))
button.pack(side=tk.LEFT)
open_file_f.pack(side=tk.LEFT)
open_file_c.pack(side=tk.LEFT)
slogan = tk.Button(frame,
text="Cancel",
command=quit)
slogan.pack(side=tk.LEFT)
root.mainloop()
I would like that the buttons "Links" and "Comments" were positioned below the radiobutton, one below the other. Now, all buttons are in line, but I would like to have "start" and "cancel" at the bottom of my window.
Then I tried to use the value of the radiobutton (choice) inside the star_program function. It does not work. My idea is, based on the choice selected in the radiobutton, perform different actions when I click the button "start":
def star_program(value):
if value == 0:
os.system("ifconfig")
else:
print "Goodbye"
In addition, concerning "start" button, I have a strange behavior. The program runs "ifconfig" command also if I don't click on "start". And If I click "start" it does not perform any action.
Any suggestion?
Thanks!!!
i'm assuming this is more like what you're after:
root = tk.Tk()
root.title("START")
root.geometry("500x200+500+200")
v = tk.IntVar()
v.set(0) # initializing the choice
my_choise = [
("Basic",1),
("Advanced",2),
('Extreme',3)
]
def ShowChoice():
print(v.get())
tk.Label(root,
text="""Choose your configuration:""",
justify = tk.LEFT,
padx = 20).grid(column=1, row=0, sticky="nesw") # use grid instead of pack
root.grid_columnconfigure(1, weight=1)
val = 0
for val, choise in enumerate(my_choise):
tk.Radiobutton(root,text=choise,padx = 20,variable=v,command=ShowChoice,value=val).grid(column=1, row=val+1, sticky="nw")
def star_program(value):
os.system("ifconfig")
def open_comments_file():
os.system("gedit /home/user/Desktop/comments.txt")
def open_links_file():
os.system("gedit /home/user/Desktop/links.txt")
frame = tk.Frame(root)
frame.grid(column=1, row=4, sticky="nesw")
open_file_c = tk.Button(frame,
text="Comments",
command=open_comments_file)
open_file_f = tk.Button(frame,
text="Links",
command=open_links_file)
button = tk.Button(frame,
text="Start",
command=lambda: star_program(v.get()))
# use lambda to create an anonymous function to be called when button pushed,
needed for functions where arguments are required
button.grid(column=2, row=3, sticky="nesw")
open_file_f.grid(column=1, row=1, sticky="nesw")
open_file_c.grid(column=1, row=2, sticky="nesw")
slogan = tk.Button(frame,
text="Cancel",
command=quit)
slogan.grid(column=4, row=3, sticky="nesw")
root.mainloop()
The problem with the "start" button is due to the function definition.
This is the right code that does not trigger any action if you don't click the button:
button = tk.Button(frame,
text="Start",
command=star_program)

Tkinter: New window has nothing in it even after writing code for it

The user clicks on "Register", and then a new window appears however nothing is in it.
Here is my code, I thought this would make everything appear?
def create_regwindow(self):
t = tk.Toplevel(self)
t.wm_title("Register")
t.field_user = tk.Label(self, text="Username")
t.field_pass = tk.Label(self, text="Password")
t.entry_user = tk.Entry(self)
t.entry_pass = tk.Entry(self, show="*")
t.field_user.grid(row=0, sticky=tk.E)
t.field_pass.grid(row=1, sticky=tk.E)
t.entry_user.grid(row=0, column=1)
t.entry_pass.grid(row=1, column=1)
You are setting parents as self. You should use t as parent on new widgets to make them appear on t.
t.field_user = tk.Label(t, text="Username")
t.field_pass = tk.Label(t, text="Password")

tkinter (unsure of my error possibly due to .destroy())

from Tkinter import *
import random
menu = Tk()
subpage = Tk()
entry_values = []
population_values = []
startUpPage = Tk()
def main_menu(window):
window.destroy()
global menu
menu = Tk()
frame1 = Frame(menu)
menu.resizable(width=FALSE, height=FALSE)
button0 = Button(menu, text="Set Generation Zero Values", command=sub_menu(menu))
button1 = Button(menu, text="Display Generation Zero Values")
button2 = Button(menu, text="Run Model")
button3 = Button(menu, text="Export Data")
button4 = Button(menu, text="Exit Program", command=menu.destroy)
button0.grid(row=0, column=0, sticky=W)
button1.grid(row=2, column=0, sticky=W)
button2.grid(row=3, column=0, sticky=W)
button3.grid(row=4, column=0, sticky=W)
button4.grid(row=5, column=0, sticky=W)
menu.mainloop()
def sub_menu(window):
global subpage
window.destroy()
subpage = Tk()
subpage.resizable(width=FALSE, height=FALSE)
#defining sub page items
button5 = Button(subpage, text="Save Generation Data",command = main_menu(subpage))
juveniles_label0 = Label(subpage,text="Juveniles")
adults_label1 = Label(subpage,text="Adults")
seniles_label2 = Label(subpage,text="Seniles")
population_label3 = Label(subpage,text="Popultation")
survival_rate_label4 = Label(subpage,text="Survival Rate (Between 0 and 1)")
entry0 = Entry(subpage)
entry1 = Entry(subpage)
entry2 = Entry(subpage)
entry3 = Entry(subpage)
entry4 = Entry(subpage)
entry5 = Entry(subpage)
button4.grid(row=1, column= 6, sticky=E)
juveniles_label0.grid(row=0, column=1)
adults_label1.grid(row=0, column=2)
seniles_label2.grid(row=0, column=3)
population_label3.grid(row=1, column=0)
survival_rate_label4.grid(row=2, column=0)
entry0.grid(row=1, column=1)
entry1.grid(row=1, column=2)
entry2.grid(row=1, column=3)
entry3.grid(row=2, column=1)
entry4.grid(row=2, column=2)
entry5.grid(row=2, column=3)
#add entry 6 7 8
subpage.mainloop()
main_menu(subpage)
main_menu(startUpPage)
I'm very new to coding and stackoverflow. I am trying to create a GUI that has a main page which will be opened first and a sub page which will be opened by clicking a button which will be stored in the main page. my issue is that I have no clue why it isn't opening my main page. my thought is that it is something to do with the .destroy() or something similar. any help would be much appreciated.
As a general rule, you should create exactly one instance of Tk for the life of your program. That is how Tkinter is designed to be used. You can break this rule when you understand the reasoning behind it, though there are very few good reasons to break the rule.
The simplest solution is to implement your main menu and your sub menu as frames, which you've already done. To switch between them you can simply destroy one and (re)create the other, or create them all ahead of time and then remove one and show the other.
For example, the following example shows how you would create them ahead of time and simply swap them out. The key is that each function needs to return the frame, which is saved in a dictionary. The dictionary is used to map symbolic names (eg: "main", "sub", etc) to the actual frames.
def main_menu(root):
menu = Frame(root)
button0 = Button(menu, text="Set Generation Zero Values",
command=lambda: switch_page("sub"))
...
return menu
def sub_menu(root):
subpage = Frame(root)
button5 = Button(subpage, text="Save Generation Data",
command = lambda: switch_page("main"))
...
return subpage
def switch_page(page_name):
slaves = root.pack_slaves()
if slaves:
# this assumes there is only one slave in the master
slaves[0].pack_forget()
pages[page_name].pack(fill="both", expand=True)
root = Tk()
pages = {
"main": main_menu(root),
"sub": sub_menu(root),
...
}
switch_page("main")
root.mainloop()
For a more complex object-oriented approach see Switch between two frames in tkinter
heres some code that does what you want.. make a window, destroy it when button is clicked and then make a new window...
from Tkinter import *
import random
def main_menu():
global root
root = Tk()
b = Button(root,text='our text button',command = next_page)
b.pack()
def next_page():
global root,parent
parent = Tk()
root.destroy()
new_b = Button(parent,text = 'new Button',command=print_something)
new_b.pack()
def print_something():
print('clicked')
main_menu()
root.mainloop()
parent.mainloop()
ps. ive done this in python3 so keep that in mind though it wouldnt be a problem in my opinion

Categories