I am creating a password manager software. The passwords are stored in different categories. When I click on the category it should open a ViewPasswordsInsideCategory page.
I am unable to pass the category name to the ViewPasswordsInsideCategory page.
Please help! I am new to Python and cant solve this issue.
I tried to pass an argument when I can showframe function but I couldn't achieve the goal.
class PasswordPage(Page):
def __init__(self, *args, **kwargs):
Page.__init__(self, *args, **kwargs)
self.shared_data = {
"category": tk.StringVar(),
"password": tk.StringVar()}
self.passwordScreen = Frame(self)
self.passwordScreen.pack(fill="both", expand=True)
self.passwordScreen.columnconfigure(0, weight=1)
self.passwordScreen.rowconfigure(0, weight=1)
self.frames = {}
for F in (PasswordCategoryPage,ViewPasswords_InCategory,CreateNewPassword,ViewPassword,ModifyPassword):
page_name = F.__name__
frame = F(parent=self.passwordScreen, controller=self)
self.frames[page_name] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame("PasswordCategoryPage")
def show_frame(self, page_name, arg=None):
'''Show a frame for the given page name'''
frame = self.frames[page_name]
frame.tkraise()
class PasswordCategoryPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
# passwords categories content
self.labels = []
self.dict = {'Home': 'Blue', 'Work': 'Red', 'School': 'Yellow', "Technical": 'Pink', "Office": 'Orange'}
self.button = []
j = 0
for key, value in self.dict.items():
self.name = key
self.key = Label(self.pass_page_container,text=self.name,bg=value)
# Add the Label to the list
self.labels.append(key)
self.key.grid(row=j, column=0, sticky=(N, S, E, W))
self.key.bind("<Double-Button-1>", self.showPasswordPage)
j = j + 1
def showPasswordPage(self,event):
#here need to pass the label that was clicked to the ViewPasswords_InCategory page
self.controller.show_frame("ViewPasswords_InCategory")
class ViewPasswords_InCategory(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
#here need the name of the category selected to extract data from database
# home banner
home_label = Label(self, text=here need the name of the category, bg="blue", width=200, height=3, fg='white')
home_label.pack(side=TOP, expand=False)
The simply way is to add a new function in class ViewPasswords_InCategory to update the banner. Then whenever you switch to the page, call the new function. My proposed changes are:
1) return the frame that is raised in function PasswordPage.show_frame(...):
class PasswordPage(Page):
...
def show_frame(self, page_name, arg=None):
'''Show a frame for the given page name'''
frame = self.frames[page_name]
frame.tkraise()
return frame # return the raised frame
2) add new function, for example set_category(...) inside class ViewPasswords_InCategory to update its banner:
class ViewPasswords_InCategory(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
# home banner
self.home_label = Label(self, text='', bg="blue", width=200, height=3, fg='white') # changed to instance variable
self.home_label.pack(side=TOP, expand=False)
# new function to update banner
def set_category(self, category):
self.home_label['text'] = category
3) update PasswordCategoryPage.showPasswordPage(...) to call the new fucntion:
class PasswordCategoryPage(tk.Frame):
...
def showPasswordPage(self,event):
#here need to pass the label that was clicked to the ViewPasswords_InCategory page
self.controller.show_frame("ViewPasswords_InCategory").set_category(event.widget['text'])
Related
Pardon me for my bad grammar or explanation, since I didn't know how to explain this properly.
I try to build some gui that could switch between frame, using script from this as base Switch between two frames in tkinter.
In this case, I will have a few frame that had similar design, but different function when the button is pressed. For example, I have 2 frames that have similar 2 entries and 1 button, but the button do different command (where at sub01 frame it will multiply and at sub02 frame will divide)
This is my code:
class SampleApp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
container = tk.Frame(self)
container.grid(row=1,columnspan=4,sticky='nsew')
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (sub01, sub02):
page_name = F.__name__
frame = F(parent=container, controller=self)
self.frames[page_name] = frame
frame.grid(row=1,sticky="nsew")
self.choices = {'sub01','sub02'}
self.tkvar = tk.StringVar()
self.tkvar.set('sub01')
self.popMenu = tk.OptionMenu(self,self.tkvar,*self.choices)
self.popMenu.grid(row=0)
self.show_frame()
self.button1 = tk.Button(self, text="Go to Layer",command=lambda: self.show_frame())
self.button1.grid(row=0, column=1)
def show_frame(self):
'''Show a frame for the given page name'''
page_name = self.tkvar.get()
frame = self.frames[page_name]
frame.tkraise()
class sub01(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="This SubLayer 1")
label.grid(row=0)
self.entries=[]
i = 0
while i < 2:
self.entries.append(tk.Entry(self,width=10))
self.entries[i].grid(row=i+1,columnspan=2,sticky='we')
i += 1
self.btn = tk.Button(self,text="multiply", command=lambda : self.multiply())
self.btn.grid(row=i+1, columnspan=2,sticky='we')
def multiply(self):
pass
class sub02(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="This SubLayer 2")
label.grid(row=0)
self.entries=[]
i = 0
while i < 2:
self.entries.append(tk.Entry(self,width=10))
self.entries[i].grid(row=i+1,columnspan=2,sticky='w')
i += 1
self.btn = tk.Button(self,text="divide",command=lambda : self.divide())
self.btn.grid(row=i+1, columnspan=2,sticky='we')
def divide(self):
pass
if __name__ == "__main__":
app = SampleApp()
app.mainloop()
This code itself works, but when I need to create more of these frames, it becomes inconvenient. How could I make this code simpler? Like having that similar frame as a class, and the button as other class that do differ behaviour depend of the layer shown.
Thank you in advance
The canonical way to do this sort of thing is to create a class hierarchy for your Page classes and put common functionality in the base classes and derive subclasses from them that specify the behavior that differs between them. Below is how you could do that with the sample code in your question.
Since the things that are different between them are:
The text displayed on the Label.
The text displayed on the Button.
The code in that's execute when the Button is clicked.
This means the derived classes only need to know what code to run in a generically named btn_func() method and what the text to displayed on the two widgets. The code below illustrates how to do that.
Note that I've changed the spelling of your class names to conform to the naming conventions describe in PEP 8 - Style Guide for Python Code.
import Tkinter as tk
class SampleApp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
container = tk.Frame(self)
container.grid(row=1,columnspan=4,sticky='nsew')
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (Sub01, Sub02):
page_name = F.__name__
frame = F(parent=container, controller=self)
self.frames[page_name] = frame
frame.grid(row=1,sticky="nsew")
self.choices = {'Sub01','Sub02'}
self.tkvar = tk.StringVar()
self.tkvar.set('Sub01')
self.popMenu = tk.OptionMenu(self,self.tkvar,*self.choices)
self.popMenu.grid(row=0)
self.show_frame()
self.button1 = tk.Button(self, text="Go to Layer",command=lambda: self.show_frame())
self.button1.grid(row=0, column=1)
def show_frame(self):
'''Show a frame for the given page name'''
page_name = self.tkvar.get()
frame = self.frames[page_name]
frame.tkraise()
class BaseSubLayer(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text=self.lbl_text)
label.grid(row=0)
self.entries=[]
i = 0
while i < 2:
self.entries.append(tk.Entry(self,width=10))
self.entries[i].grid(row=i+1,columnspan=2,sticky='we')
i += 1
self.btn = tk.Button(self,text=self.btn_func_name, command=self.btn_func)
self.btn.grid(row=i+1, columnspan=2,sticky='we')
def btn_func(self):
raise NotImplementedError
class Sub01(BaseSubLayer):
lbl_text = 'This SubLayer 1'
btn_func_name = 'multiply'
def btn_func(self):
print('Running multiply() method.')
class Sub02(BaseSubLayer):
lbl_text = 'This SubLayer 2'
btn_func_name = 'divide'
def btn_func(self):
print('Running divide() method.')
if __name__ == "__main__":
app = SampleApp()
app.mainloop()
I am making a game with levels and in each level, I will need to be using different operators and/or different ranges. My problem is that I don't know how to change the variables in a function from a different class. I would like to do this so I don't need to copy and paste my code making it lengthy. I'd like to use self.Answer and self.strQuestion for mulitple scope.
The code below is just to make the classes functional.
from tkinter import *
import tkinter as tk
import random
from Tkinter import messagebox
class BattleMaths(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, levelone, leveltwo):
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()
class StartPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
lvl1_button = Button(self, text="LEVEL 1", command=lambda: controller.show_frame(levelone))
lvl1_button.place(relx=0.5, rely=0.5, anchor='center')
I want to put the questions def into class leveltwo while changing it to self.Answer = int(numOne) * int(numTwo) and self.strQuestion = "{} x {}".format(str(numOne), str(numTwo))
class levelone(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
def widgets(self):
#widgets here
def question(self):
self.UserAnswer = ''
numOne = random.randrange(1,10)
numTwo = random.randrange(1,10)
self.Answer = int(numOne) + int(numTwo) #change this
self.strQuestion = "{} + {}".format(str(numOne), str(numTwo)) #and change this
def answer(self):
#answer checker
class leveltwo(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
#question def here
root = BattleMaths()
root.title("Battle Maths")
root.geometry("400x250")
root.resizable(0,0)
root.mainloop()
Create the variables you want in the main class (BattleMaths), then you can alter them in the child classes via controller.my_variable.
Example: self.Answer created in BattleMaths and accessed in levelone via controller.Answer
I need some help with updating informations between two or more frames in tkinter. I am currelty working on a small project, where I have serval frames with information, each frame is one class.
First frame is a setting frame - so where the user can click some buttons and select several things.
The second frame should show the selected image with the made choices.
So far I can make the choices on the setting page but when i click forward to the result page it shows me empty frames and no image and not the made choices.
I tried to do some shared_data with the information that should be passed between the two frames/classes, so I can acess them on the resultpage but some how it is not updating the information. So it doesn't show me the image because mode on the results page is 0 like at the beginng.
class xyz (tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
...
self.shared_data = {
"no": tk.IntVar(),
"selectedname": tk.StringVar(),
"selectedpath": tk.StringVar(),
.....
}
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 (SettingPage, PageResults):
page_name = F.__name__
frame = F(container, self)
self.frames[page_name] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame("SettingPage")
def show_frame(self, page_name):
frame = self.frames[page_name]
frame.tkraise()
class SettingPage(tk.Frame):
def __init__(self, parent, controller, *args, **kwargs):
tk.Frame.__init__(self, parent, *args, **kwargs)
self.controller = controller
self.controller.shared_data["no"] = 0
...
# after selecting serval buttons
self.controller.shared_data["no"] = 1
buttonContinue = ttk.Button(self, text='''CONTINUE >>''', command=lambda: controller.show_frame("PageResults"))
buttonContinue.place(relx=0.84, rely=0.9, height=43, width=186)
class PageResults(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
mode = self.controller.shared_data["no"]
if mode == 1 :
# show image
#......
I can't show you the exact real code I am using so I tried so simplify it. I am new to tkinter so any help would be much apprechiated.
Thank you!!
The problem is because you do this:
self.shared_data = {
"no": tk.IntVar(),
...
}
And then later you do this:
self.controller.shared_data["no"] = 0
So, shared_data["no"] starts out as an IntVar and then you replace it with an integer.
When you use an IntVar you must use the set method to change the value, and the get method to get the value:
self.controller.shared_data["no"].set(0)
...
if self.controller.shared_data["no"] == 0:
...
I have my Tkinker app where I create more frame and based on what I click I show one or another, the problem now is that I want them to refresh with new information every time that I call them; do you know how can I do?
This is my code:
class HFlair(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(10, weight=1)
container.grid_columnconfigure(10, weight=1)
self.container=container
self.frames = {}
for F in ((StartPage, None), (PageOne, None)):
page_name = F[0].__name__
frame = F[0](parent=container, controller=self, attr=F[1])
self.frames[page_name] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame("StartPage")
def show_frame(self, page_name,arg=None):
'''Show a frame for the given page name'''
frame = self.frames[page_name]
frame.tkraise()
if arg:
frame.users(arg)
class StartPage(tk.Frame):
def __init__(self, parent, controller,attr=None):
tk.Frame.__init__(self, parent,attr)
self.controller = controller
self.title=tk.Frame(self)
self.title.pack(side="top")
self.menu=tk.Frame(self)
self.menu.pack(side="top")
self.app=tk.Frame(self) #### frame that I want refresh
self.app.pack(side="top") #### frame that I want refresh
class PageOne(tk.Frame):
def __init__(self, parent, controller, attr=None):
self.controller=controller
tk.Frame.__init__(self, parent,attr)
self.controller = controller
self.title=tk.Frame(self)
self.title.pack(side="top")
self.menu=tk.Frame(self)
self.menu.pack(side="top")
self.app=tk.Frame(self) #### frame that I want refresh
self.app.pack(side="top") #### frame that I want refresh
My problem is that in the frame self.app I have some information that I take from the DB so every time that I go to this specific page I want the Frame refresh to take update information.
Is there some easy way to do it?
I try with .update() but didn't work, more than other didn't give me any issue but the Frame didn't refresh.
so there is this stackoverflow question:
Switch between two frames in tkinter
Which looks like a beautiful basis for building an application. But what if on startPage i want to have multiply buttons, and display the appropriate data on PageOne? Here is my attempt:
import tkinter as tk
from functools import partial
characters = {"character1": "abc", "character2": "def", "character3": "ghi", "character4": "jkl", "character5": "mnp", "character6": "qrs" }
class AdventureGame:
''' controller for managiging frames '''
def __init__(self, master):
self.master = master
self.frames = {}
for F in (StartGame,ShowCharacters,CharacterDetail):
frame = F(parent=master, controller=self)
self.frames[F.__name__] = frame
frame.grid(row=0, column=0, sticky="nsew")
''' rais the first frame '''
self.raise_frame("StartGame")
def raise_frame(self,page_name):
''' raise a frame '''
frame = self.frames[page_name]
frame.tkraise()
def lower_frame(self,page_name):
''' lower a frame '''
frame = self.frames[page_name]
frame.lower()
class StartGame(tk.Frame):
''' introduction screen of the game '''
def __init__(self, parent, controller):
super(StartGame,self).__init__(parent)
self.controller = controller
''' introduction text '''
tk.Label(self, text="welcome to this game").grid()
tk.Button(self, text="next", command=lambda: controller.raise_frame("ShowCharacters")).grid()
class ShowCharacters(tk.Frame):
''' main frame, overview of all pokemon '''
def __init__(self, parent, controller):
super(ShowCharacters,self).__init__(parent)
self.controller = controller
for row, character in enumerate(characters):
name_label = tk.Label(self, text=characters[character])
name_label.grid(row=row,column=0)
info_button = tk.Button(self, text="view info", command=partial(self.switch,character))
info_button.grid(row=row,column=1)
def switch(self, character):
test = self.controller.raise_frame("CharacterDetail")
class CharacterDetail(tk.Frame):
''' detail view of pokemon '''
def __init__(self, parent, controller):
super(CharacterDetail,self).__init__(parent)
self.controller = controller
tk.Button(self, text="back", command=lambda: controller.lower_frame("CharacterDetail")).grid()
# somehow display characters name here
def showdetail(self):
tk.Label(self, text="test").grid()
def main():
root = tk.Tk()
app = AdventureGame(root)
root.mainloop()
main()
It feels like the the key is in the controller, as explained here:
How to get variable data from a class
It just feels like i am missing something, does someone have an idea? Or am i thinking in the wrong direction all together?
If i try to show the detail:
def switch(self, character):
test = self.controller.raise_frame("CharacterDetail")
CharacterDetail.showdetail(self)
it shows up at the ShowCharacters frame rather then the CharacterDetail frame
I guess because self is the frame, which is self from ShowCharacters
I need to do something with the controller, but my mind just goes blank
So now i pass information to the controller:
import tkinter as tk
from functools import partial
characters = {"character1": "abc", "character2": "def", "character3": "ghi", "character4": "jkl", "character5": "mnp", "character6": "qrs" }
class AdventureGame:
''' controller for managiging frames '''
def __init__(self, master):
self.master = master
self.frames = {}
for F in (StartGame,ShowCharacters,CharacterDetail):
frame = F(parent=master, controller=self)
self.frames[F.__name__] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.app_data = {"test": "test"}
''' rais the first frame '''
self.raise_frame("StartGame")
def raise_frame(self,page_name):
''' raise a frame '''
frame = self.frames[page_name]
frame.tkraise()
def lower_frame(self,page_name):
''' lower a frame '''
frame = self.frames[page_name]
frame.lower()
class StartGame(tk.Frame):
''' introduction screen of the game '''
def __init__(self, parent, controller):
super(StartGame,self).__init__(parent)
self.controller = controller
''' introduction text '''
tk.Label(self, text="welcome to this game").grid()
tk.Button(self, text="next", command=lambda: controller.raise_frame("ShowCharacters")).grid()
class ShowCharacters(tk.Frame):
''' main frame, overview of all pokemon '''
def __init__(self, parent, controller):
super(ShowCharacters,self).__init__(parent)
self.controller = controller
for row, character in enumerate(characters):
name_label = tk.Label(self, text=characters[character])
name_label.grid(row=row,column=0)
info_button = tk.Button(self, text="view info", command=partial(self.switch,character))
info_button.grid(row=row,column=1)
def switch(self, character):
test = self.controller.raise_frame("CharacterDetail")
CharacterDetail.example(self)
class CharacterDetail(tk.Frame):
''' detail view of pokemon '''
def __init__(self, parent, controller):
super(CharacterDetail,self).__init__(parent)
self.controller = controller
tk.Button(self, text="back", command=lambda: controller.lower_frame("CharacterDetail")).grid()
def example(self):
tk.Label(self, text=self.controller.app_data["test"]).grid()
def main():
root = tk.Tk()
app = AdventureGame(root)
root.mainloop()
main()
the label is still on the wrong frame, how can i get access to the right self so i can add the label to the right frame?
As you call CharacterDetail.example(self) in function switch(...) of class ShowCharacters, self will be class ShowCharacters. Therefore the label created in function example(self) of class CharacterDetail will be in ShowCharacters frame.
Try:
return the raised frame in function raise_frame(...) of class AdventureGame:
def raise_frame(self, page_name):
frame = self.frames[page_name]
frame.tkraise()
return frame # return the raised frame
modify function switch(...) of class ShowCharacters:
def switch(self, character):
frame = self.controller.raise_frame("CharacterDetail")
frame.example()