Using a variable from one class to another tkinter - python

Here is the full code for test please run it and tell me if I can store username and password outside the class after destroy the frame
import tkinter as tk
from tkinter import *
from PIL import Image, ImageTk
from tkinter import filedialog
class SampleApp(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self._frame = None
self.title('Instagram Bot')
self.geometry("500x500")
self.switch_frame(StartPage)
def switch_frame(self, frame_class):
"""Destroys current frame and replaces it with a new one."""
new_frame = frame_class(self)
if self._frame is not None:
self._frame.destroy()
self._frame = new_frame
self._frame.pack()
class StartPage(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
tk.Label(self, text="Enter Username").pack(side="top", fill="x", pady=10)
self.username = tk.Entry(self,)
self.username.pack()
tk.Label(self, text='Enter Pssword').pack(side='top', fill='x', pady=10)
self.password = tk.Entry(self)
self.password.pack()
self.password = self.password.get()
self.username = self.username.get()
# if(username.get('text') == None or password.get('text') == None):
# tk.Button(self, text="Login",
# command=lambda: master.switch_frame(StartPage)).pack()
# else:
tk.Button(self, text="Login", command=lambda: master.switch_frame(PageOne) and login_data()).pack()
class PageOne(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
tk.Label(self, text="Welcome").pack(side="top", fill="x", pady=10)
tk.Button(self, text='Some text', command=lambda: master.switch_frame(Hashtag_page)).pack()
def __init__(self, master):
tk.Frame.__init__(self, master)
self.hastag_lbl = tk.Label(self, text='Choice file')
self.hastag_lbl.pack(side='top',fill='x',pady=10)
tk.Button(self, text='browse', command=self.browseFiles_hstg).pack()
tk.Button(self, text='Start Bot', command=self.start_hashtag).pack()
def browseFiles_hstg(self):
filename = filedialog.askopenfilename(initialdir = "/",
title = "Select a File",
filetypes = (("Text files",
"*.txt*"),
("all files",
"*.*")))
# Change label contents
self.hastag_lbl.configure(text = filename)
def start_hashtag(self):
print(StartPage.username, StartPage.password)
if __name__ == "__main__":
app = SampleApp()
app.mainloop()
Exception in Tkinter callback Traceback (most recent call last): File "/usr/lib/python3.6/tkinter/init.py", line 1705, in call
return self.func(*args) File "scofrlw.py", line 71, in start_hashtag
print(StartPage.username, StartPage.password) AttributeError: type object 'StartPage' has no attribute 'username'

In the code below, i have been storing the credentials inside the master (SampleApp) which is accessible from your class PageOne aswell.
Alternatively, you may consider storing the credentials in a dict, and passing it
to your PageOne during initialization.
import tkinter as tk
from tkinter import *
#from PIL import Image, ImageTk
from tkinter import filedialog
class SampleApp(tk.Tk):
def __init__(self):
self.test = "I am the MasterAPP"
tk.Tk.__init__(self)
self._frame = None
self.title('Instagram Bot')
self.geometry("500x500")
self.switch_frame(StartPage)
self.username = None
self.password = None
def switch_frame(self, frame_class):
"""Destroys current frame and replaces it with a new one."""
new_frame = frame_class(self)
if self._frame is not None:
self._frame.destroy()
self._frame = new_frame
self._frame.pack()
class StartPage(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
tk.Label(self, text="Enter Username").pack(side="top", fill="x", pady=10)
self.username = tk.Entry(self,)
self.username.pack()
tk.Label(self, text='Enter Pssword').pack(side='top', fill='x', pady=10)
self.password = tk.Entry(self)
self.password.pack()
tk.Button(self, text="Login",
command=lambda:
self.login()
).pack()
def login(self):
self.save_credentials()
self.master.switch_frame(PageOne)
def save_credentials(self):
self.master.password = self.password.get()
self.master.username = self.username.get()
class PageOne(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
tk.Label(self, text="Welcome").pack(side="top", fill="x", pady=10)
tk.Button(self, text='Some text', command=lambda: master.switch_frame(Hashtag_page)).pack()
def __init__(self, master):
tk.Frame.__init__(self, master)
self.hastag_lbl = tk.Label(self, text='Choice file')
self.hastag_lbl.pack(side='top',fill='x',pady=10)
tk.Button(self, text='browse', command=self.browseFiles_hstg).pack()
tk.Button(self, text='Start Bot', command=self.start_hashtag).pack()
def browseFiles_hstg(self):
filename = filedialog.askopenfilename(initialdir = "/",
title = "Select a File",
filetypes = (("Text files",
"*.txt*"),
("all files",
"*.*")))
# Change label contents
self.hastag_lbl.configure(text = filename)
def start_hashtag(self):
print(self.master.username, self.master.password)
if __name__ == "__main__":
app = SampleApp()
app.mainloop()

I would make a dictionary of the username and password, but depending on your GUI, I don't know the best option for you
Make the dictionary
dictionary = {}
class StartPage(tk.Frame):
...
Add values for the username and password.
def login_credentials(self):
dictionary['password'] = self.password.get()
dictionary['username'] = self.username.get()
Then you can just print them
def start_hashtag(self):
print(dictionary['username'],dictionary['password'])

There are few issues in your code:
should not call self.password = self.password.get() and self.username = self.username.get() just after self.username and self.password are created because they will be both empty strings and override the references to the two Entry widgets.
username and password are instance variables of StartPage, so they cannot be access by StartPage.username and StartPage.password
two __init__() function definitions in PageOne class
when switching frame, the previous frame is destroyed. So username and password will be destroyed as well and cannot be accessed anymore.
You can use instance of SampleApp to store the username and password, so they can be accessed by its child frames:
class StartPage(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
tk.Label(self, text="Enter Username").pack(side="top", fill="x", pady=10)
self.username = tk.Entry(self,)
self.username.pack()
tk.Label(self, text='Enter Pssword').pack(side='top', fill='x', pady=10)
self.password = tk.Entry(self)
self.password.pack()
tk.Button(self, text="Login", command=self.login).pack()
def login(self):
# store the username and password in instance of 'SampleApp'
self.master.username = self.username.get()
self.master.password = self.password.get()
# switch to PageOne
self.master.switch_frame(PageOne)
class PageOne(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
self.hastag_lbl = tk.Label(self, text='Choice file')
self.hastag_lbl.pack(side='top',fill='x',pady=10)
tk.Button(self, text='browse', command=self.browseFiles_hstg).pack()
tk.Button(self, text='Start Bot', command=self.start_hashtag).pack()
def browseFiles_hstg(self):
filename = filedialog.askopenfilename(initialdir = "/",
title = "Select a File",
filetypes = (("Text files",
"*.txt*"),
("all files",
"*.*")))
# Change label contents
if filename:
self.hastag_lbl.configure(text = filename)
def start_hashtag(self):
# get username and password from instance of SampleApp
print(self.master.username, self.master.password)

Related

Tkinter adding Images issue

so I have looked about but cant find anything that works for me so if I add a image to my first page (log in page) the image will display fine. However if I try and add it to my main page I get the error pyimage 1
Here is the code: (I've tried to remove all the code not needed to shorten it)
import tkinter as tk
from tkinter import ttk
from tkinter import Scrollbar, messagebox
import os
from PIL import ImageTk,Image
global appcwd
appcwd = os.getcwd()
class Login_Start(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
main_frame = tk.Frame(self, bg="black", height=768, width=1366)
main_frame.pack(fill="both", expand="true")
self.geometry("1366x768")
#INSERTING IMAGE HERE
#path = "{}\\grem.png".format(appcwd)
#img = ImageTk.PhotoImage(Image.open(path))
#pic2lab = tk.Label(main_frame, image=img)
#pic2lab.photo = img
#pic2lab.pack()
loginbut = tk.Button(main_frame, width=10, text='Login', command=lambda: Get_Login())
loginbut.pack()
def Get_Login():
validation = True
if validation:
root.deiconify()
top.destroy()
else:
tk.messagebox.showerror("Information", "The details are either wrong or you need to register")
class MenuBar(tk.Menu):
def __init__(self, parent):
tk.Menu.__init__(self, parent)
menu_file = tk.Menu(self, tearoff=0)
self.add_cascade(label="File", menu=menu_file)
menu_file.add_command(label="Main Menu", command=lambda: parent.show_frame(Main_Page))
class App(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
main_frame = tk.Frame(self, bg="grey", height=768, width=1366)
main_frame.pack_propagate(0)
main_frame.pack(fill="both", expand="true")
main_frame.grid_rowconfigure(0, weight=1)
main_frame.grid_columnconfigure(0, weight=1)
self.geometry("1366x768")
self.frames = {}
pages = (Main_Page, Admin_Page)
for F in pages:
frame = F(main_frame, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(Main_Page)
menubar = MenuBar(self)
tk.Tk.config(self, menu=menubar)
def show_frame(self, name):
frame = self.frames[name]
frame.tkraise()
class Temp(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
self.main_frame = tk.Frame(self, bg="black", height=768, width=1366)
self.main_frame.pack_propagate(0)
self.main_frame.pack(fill="both", expand="true")
self.main_frame.grid_rowconfigure(0, weight=1)
self.main_frame.grid_columnconfigure(0, weight=1)
self.main = tk.LabelFrame(self.main_frame, bg='black')
self.main.place(relx=0.01, rely=0.21, height=490, width=1330)
class Main_Page(Temp):
def __init__(self, parent, controller):
Temp.__init__(self, parent)
mainlabel = tk.Label(self.main, font=("Trebuchet MS Bold", 16), bg="grey", fg="black", text="TEXT")
mainlabel.pack()
path = "{}\\grem.png".format(appcwd)
img = ImageTk.PhotoImage(Image.open(path))
pic2lab = tk.Label(self.main, image=img)
pic2lab.photo = img
pic2lab.pack()
butbut = tk.Button(self.main, text="press", command=lambda:controller.show_frame(Admin_Page))
butbut.pack()
class Admin_Page(Temp):
def __init__(self, parent, controller):
Temp.__init__(self, parent)
hm = tk.Label(self.main, bg="grey", fg='black', text='Admin_Page')
hm.place(rely=0.02, relx=0.01,)
top = Login_Start()
top.title("main title")
root = App()
root.withdraw()
root.title("main title")
root.mainloop()
Like I said works fine in the Login_Start() Class but won't in the Main_Page()

Tkinter variable value is not passed to other class

I have a little bit of strange problem and I will try to explain.
So I am trying to connect to WiFi through tkinter, and I am passing variables like name of the WiFi and the password, between classes, and its working. I know this because I am displaying them in Labels, but when I try to connect to WiFi, the variables are not passed as arguments to the connection string.
Here is part of my code :
import tkinter as tk
from PIL import Image, ImageTk
import time
import os
from wifi import Cell, Scheme
LARGE_FONT = ("Verdana", 12)
from tkinter import END
class SeaofBTCapp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
container = tk.Frame(self)
self.geometry("480x800")
self.label = tk.Label(text="This is the start page",background="blue",height=2)
self.label.pack(side="top", fill="x", pady=0)
self.time1 = ''
self.time2 = time.strftime('%H:%M:%S')
self.watch = tk.Label(self, text=self.time2, font=('times', 12, 'bold'))
self.watch.pack()
self.changeLabel() #first call it manually
self.a=tk.StringVar()
self.passcode=tk.StringVar()
container.pack(side="top", fill="both", expand=True)
container.grid_rowconfigure(0, weight=100)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (SetUpPage,ChoseWIFI,TypePassword,Connecting):
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(SetUpPage)
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
def changeLabel(self):
self.time2 = time.strftime('%H:%M:%S')
self.watch.configure(text=self.time2)
self.after(200, self.changeLabel) # it'll call itself continuously
class SetUpPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
image = Image.open("wifi_icon.gif")
image = image.resize((50, 50), Image.ANTIALIAS)
self.reset_img = ImageTk.PhotoImage(image)
image1 = Image.open("ethernet_icon.gif")
image1 = image1.resize((50, 50), Image.ANTIALIAS)
self.reset_img1 = ImageTk.PhotoImage(image1)
self.but = tk.Button(self, text="WORK IN", height=180, width=180, image=self.reset_img,command=lambda: controller.show_frame(ChoseWIFI)).place(x=150, y=125)
self.but1 = tk.Button(self, text="WORK OUT", height=180, width=180, image=self.reset_img1).place(x=150, y=425)
class ChoseWIFI(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller=controller
self.mylistbox=tk.Listbox(self,width=80,height=10,font=('times',13))
self.mylistbox.bind('<<ListboxSelect>>',self.CurSelet)
self.mylistbox.place(x=100,y=190)
self.wifiscan()
self.but = tk.Button(self, text="CONNECT", height=10, width=10,command=lambda: controller.show_frame(TypePassword)).place(x=150, y=525)
def wifiscan(self):
allSSID = [cell.ssid for cell in Cell.all('wlan0')]
print (allSSID )# prints all available WIFI SSIDs
for i in range(len(allSSID )):
if print(str(allSSID [i]))== print(myssid):
a = i
print("hit")
myssidA = allSSID [a]
print( myssidA )
break
else:
print ("getout")
print (myssid)
self.itemsforlistbox=allSSID
for items in self.itemsforlistbox:
self.mylistbox.insert(END,items)
def CurSelet(self,a):
value=self.mylistbox.get(self.mylistbox.curselection())
self.o=self.controller.a
self.o.set(value)
class TypePassword(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller=controller
#self.entry1 = tk.Label(self, textvariable=self.controller.shared_data["username"])
#self.entry1.pack()
self.L2 = tk.Label(self, textvariable=self.controller.a)
self.L2.pack()
self.L1 = tk.Label(self, text="Type password")
self.L1.pack()
self.E1 = tk.Entry(self, bd=5)
self.E1.place(x=150, y=325)
#self.connect()
self.but = tk.Button(self, text="CONNECT", height=10, width=10,command=lambda:[self.connect(), controller.show_frame(Connecting)]).place(x=150, y=525)
def connect(self):
self.controller.passcode.set(self.E1.get())
#os.system('nmcli d wifi connect "%s" password %s iface %s' % (self.controller.a,self.controller.passcode, self.controller.a)) # vive1234 is the password to my wifi myssidA is the wifi name
self.pas=self.controller.passcode
self.passw = self.E1.get()
self.pas.set(self.passw)
class Connecting(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller=controller
self.entry1 = tk.Label(self, text="CONNECTING.....")
self.entry1.pack()
self.entry2 = tk.Label(self, textvariable=self.controller.a)
self.entry2.pack()
self.entry3 = tk.Label(self, textvariable=self.controller.passcode)
self.entry3.pack()
self.but = tk.Button(self, text="CONNECT11", height=10, width=10,command=self.k).place(x=150, y=525)
#self.but.tk.bind(('<but>', self.k))
def k(self):
#connection string for WIFI
os.system('nmcli d wifi connect "%s" password %s iface %s' % (self.controller.a,self.controller.passcode, self.controller.a)) # vi
print("KKKK")
if __name__ == "__main__":
# Calls its attribute.
app = SeaofBTCapp()
a=app.changeLabel()
app.after(200,a )
# Calls its attribute.
app.mainloop()

how do i post the path of a file into entry() in tkinter

i'm trying to make (text1) the Entry to get the file path that i open to show up
what i mean whin i open a file it show me the file path on the entry(textbox)
ps: sorry for the bad example and English
''''python
import tkinter as tk
from tkinter.filedialog import askopenfilename
from tkinter.messagebox import showerror
from tkinter import ttk
here is my class for the fream
class SchoolProjict(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
container = tk.Frame(self)
container.pack(side = "top", fill = "both", expand = True)
container.grid_rowconfigure(0, weight = 1)
container.grid_columnconfigure(0, weight = 1)
self.frames = {}
for F in (StartPage, PageOne, SetingPage):
frame = F(container, self)
self.frames[F] = frame
frame.grid(row = 0, column = 0, sticky = "nsew")
self.show_frame(StartPage)
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
this on to test printing from entry
def printingstuff(var1):
print (var1)
this to open a file i want it to chang the entry to show the file path
def load_file():
fname = askopenfilename(filetypes=(("Excel file", "*.xls"),
("HTML files", "*.html;*.htm"),
("All files", "*.*") ))
if fname:
try:
print(fname)
return
except: # <- naked except is a bad idea
showerror("Open Source File", "Failed to read file\n'%s'" % fname)
return
here are the frames for the program
class StartPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
lablel = tk.Label(self, text = "Start Page")
lablel.pack(pady = 10, padx = 10)
button1 = tk.Button(self, text = "Main Menu", command = lambda: controller.show_frame(PageOne))
button1.pack()
button2 = tk.Button(self, text = "Siting", command = lambda: controller.show_frame(SetingPage))
button2.pack()
class PageOne(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
lablel = tk.Label(self, text = "Main Menu")
lablel.pack(pady = 10, padx = 10)
button1 = tk.Button(self, text = "Start Page", command = lambda: controller.show_frame(StartPage))
button1.pack()
button2 = tk.Button(self, text = "Siting", command = lambda: controller.show_frame(SetingPage))
button2.pack()
class SetingPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
lablel = tk.Label(self, text = "Siting Page")
lablel.pack(pady = 10, padx = 10)
text1 = ttk.Entry(self)
text1.pack()
text1.focus()
button1 = tk.Button(self, text = "Print from Entry", command = lambda: printingstuff(text1.get()))
button1.pack()
button2 = tk.Button(self, text="open File", command= load_file, width=10)
button2.pack()
button3 = tk.Button(self, text = "Main Menu", command = lambda: controller.show_frame(PageOne))
button3.pack()
button4 = tk.Button(self, text = "Start Page", command = lambda: controller.show_frame(StartPage))
button4.pack()
the main loop thing
app = SchoolProjict()
app.mainloop()
''''
i am sorry if it dose not make any sense
class SetingPage(tk.Frame):
def __init__(self, parent, controller):
...
self.text1 = tk.Entry(self) #<== i want to show the path of the file i am going to open Here after i select it from openfile
self.text1.grid(row = 2, column = 0)
self.text1.focus()
button1 = tk.Button(self, text = "print text1", command = lambda: printingstuff(self.text1.get()))
...

Tkinter Multiple GUI

Hey I am having a problem during connecting two Gui together as when button pressed i want the tkinter to open another gui from another file.
File one contains the frontend dashboard and when you click on the teacher than click on login it gives me an error saying.
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
TypeError: __init__() missing 1 required positional argument: 'master'
this is the main page Source Code:
from tkinter import *
from login import *
import tkinter as tk
from tkinter import ttk
class Frontend(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
self.title('Portal') # set the title of the main window
self.geometry('300x300') # set size of the main window to 300x300 pixels
# this container contains all the pages
container = tk.Frame(self)
container.pack(side='top', fill='both', expand=True)
container.grid_rowconfigure(0, weight=1) # make the cell in grid cover the entire window
container.grid_columnconfigure(0,weight=1) # make the cell in grid cover the entire window
self.frames = {} # these are pages we want to navigate to
for F in (Dashboard, Teacher, Student): # for each page
frame = F(container, self) # create the page
self.frames[F] = frame # store into frames
frame.grid(row=0, column=0, sticky='nsew') # grid it to container
self.show_frame(Dashboard) # let the first page is Dashboard
def show_frame(self, name):
frame = self.frames[name]
frame.tkraise()
class Dashboard(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self,parent)
label = ttk.Label(self, text="Main Screen", font=LARGE_FONT)
label.pack(pady=10,padx=10)
button = ttk.Button(self, text="Teacher",
command=lambda: controller.show_frame(Teacher))
button.pack()
button1 = ttk.Button(self, text="Student",
command=lambda: controller.show_frame(Student))
button1.pack()
class Teacher(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = ttk.Label(self, text="Teacher Login", font=LARGE_FONT)
label.pack(pady=10,padx=10)
#logo = ImageTk.PhotoImage(Image.open('logo.png'))
button = ttk.Button(self, text="Login", command=LoginFrame)
button.pack()
button1 = ttk.Button(self, text="Home",
command=lambda: controller.show_frame(Dashboard))
button1.pack()
class Student(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = ttk.Label(self, text="Student Login", font=LARGE_FONT)
label.pack(pady=10,padx=10)
button = ttk.Button(self, text="Home",
command=lambda: controller.show_frame(Dashboard))
button.pack()
def main():
root = Frontend()
root.mainloop()
if __name__=='__main__':
main()
Login source code:
from tkinter import *
import tkinter.messagebox as tm
class LoginFrame(Frame):
def __init__(self, master):
super().__init__(master)
self.label_username = Label(self, text="Username")
self.label_password = Label(self, text="Password")
self.entry_username = Entry(self)
self.entry_password = Entry(self, show="*")
self.label_username.grid(row=0, sticky=E)
self.label_password.grid(row=1, sticky=E)
self.entry_username.grid(row=0, column=1)
self.entry_password.grid(row=1, column=1)
self.checkbox = Checkbutton(self, text="Keep me logged in")
self.checkbox.grid(columnspan=2)
self.logbtn = Button(self, text="Login", command=self._login_btn_clicked)
self.logbtn.grid(columnspan=2)
self.pack()
def _login_btn_clicked(self):
# print("Clicked")
username = self.entry_username.get()
password = self.entry_password.get()
# print(username, password)
if username == "admin" and password == "admin123":
tm.showinfo("Login info", "Welcome Admin")
else:
tm.showerror("Login error", "Incorrect username")
def main():
root = Tk()
page = LoginFrame(root)
root.mainloop()
if __name__=='__main__':
main()
Thanks

Tkinter - show dialog with options and change password buttons

I use a python program called Thonny. Its used to make another box that said 'You have made it into the main application' inside but I removed that piece of text for now. I would like it to show a options button and a change password button. This is the code:
import tkinter as tk
class Mainframe(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.frame = FirstFrame(self)
self.frame.pack()
def change(self, frame):
self.frame.pack_forget() # delete currrent
frame = frame(self)
self.frame.pack() # make new frame
class FirstFrame(tk.Frame):
def __init__(self, master=None, **kwargs):
tk.Frame.__init__(self, master, **kwargs)
master.title("Enter password")
master.geometry("300x200")
self.status = tk.Label(self, fg='red')
self.status.pack()
lbl = tk.Label(self, text='Enter password')
lbl.pack()
self.pwd = tk.Entry(self, show="*")
self.pwd.pack()
self.pwd.focus()
self.pwd.bind('<Return>', self.check)
btn = tk.Button(self, text="Done", command=self.check)
btn.pack()
btn = tk.Button(self, text="Cancel", command=self.quit)
btn.pack()
def check(self, event=None):
if self.pwd.get() == 'password':
self.master.change(SecondFrame)
else:
self.status.config(text="Wrong password")
class SecondFrame(tk.Frame):
def __init__(self, master=None, **kwargs):
tk.Frame.__init__(self, master, **kwargs)
master.title("Main application")
master.geometry("600x400")
def options_button(self):
def set_password(self):
e = tk.Entry(master, show="*", textvariable=self.password_set2)
e.pack()
but1 = tk.Button(self, text="Done", command=self.password_set)
but1.pack()
b = tk.Button(self, text="Set your password", command=self.set_password)
b.pack()
c = tk.Button(self, text="Options", command=self.options_button)
c.pack()
if __name__=="__main__":
app=Mainframe()
app.mainloop()
This is What is not working.
This is what it originally did
So I had a little bit of a play around and I think this is what your after. I also changed your code a little bit as I always feel its best to put self infront of all widgets on multiclass applications.
import tkinter as tk
class FirstFrame(tk.Frame):
def __init__(self, master, **kwargs):
tk.Frame.__init__(self, master, **kwargs)
self.pack()
master.title("Enter password")
master.geometry("300x200")
self.status = tk.Label(self, fg='red')
self.status.pack()
self.lbl = tk.Label(self, text='Enter password')
self.lbl.pack()
self.pwd = tk.Entry(self, show="*")
self.pwd.pack()
self.pwd.focus()
self.pwd.bind('<Return>', self.check)
self.btn = tk.Button(self, text="Done", command=self.check)
self.btn.pack()
self.btn = tk.Button(self, text="Cancel", command=self.quit)
self.btn.pack()
def check(self, event=None):
if self.pwd.get() == app.password:
self.destroy() #destroy current window and open next
self.app= SecondFrame(self.master)
else:
self.status.config(text="Wrong password")
class SecondFrame(tk.Frame):
#re organised a lot in here
def __init__(self, master, **kwargs):
tk.Frame.__init__(self, master, **kwargs)
self.pack()
master.title("Main application")
master.geometry("600x400")
self.c = tk.Button(self, text="Options", command=self.options_button)
self.c.pack()
self.e = tk.Entry(self.master, show="*")
def options_button(self):
self.e.pack()
self.but1 = tk.Button(self, text="Change password", command=self.set_password)
self.but1.pack()
def set_password(self):
app.password=self.e.get()
if __name__=="__main__":
root = tk.Tk() #removed your mainframe class
app=FirstFrame(root)
#set an attribute of the application for the password
#similar to a global variable
app.password = "password"
root.mainloop()
So with what I have done you get prompted for the password and if you get it right it goes to the next scree, then an options button appears and if it is clicked then an entry box appears allowing the user to change the password

Categories

Resources