So far, I have the generator working but I can't get the tkinter to display the variable for the generated password, it only comes up in the console. Once I have the password checker working as well, I need that to be able to change variable as well, please help, here is a copy of my code
from tkinter import *
import tkinter as tk
from tkinter import font as tkfont
import random
import time
global strength
global gen
strength = 0;
gen = '[password will be here]';
global mypw
mypw = '';
def generate():
alphabet = "abcdefghijklmnopqrstuvwxyz"
pw_length = 8
mypw = ""
for i in range(pw_length):
next_index = random.randrange(len(alphabet))
mypw = mypw + alphabet[next_index]
# replace 1 or 2 characters with a number
for i in range(random.randrange(1,3)):
replace_index = random.randrange(len(mypw)//2)
mypw = mypw[0:replace_index] + str(random.randrange(10)) + mypw[replace_index+1:]
# replace 1 or 2 letters with an uppercase letter
for i in range(random.randrange(1,3)):
replace_index = random.randrange(len(mypw)//2,len(mypw))
mypw = mypw[0:replace_index] + mypw[replace_index].upper() + mypw[replace_index+1:]
print(mypw)
gen = mypw;
class SampleApp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
self.title_font = tkfont.Font(family='Helvetica', size=18, weight="bold", slant="italic")
# the container is where we'll stack a bunch of frames
# on top of each other, then the one we want visible
# will be raised above the others
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, PageTwo):
page_name = F.__name__
frame = F(parent=container, controller=self)
self.frames[page_name] = frame
# put all of the pages in the same location;
# the one on the top of the stacking order
# will be the one that is visible.
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame("StartPage")
def show_frame(self, page_name):
'''Show a frame for the given page name'''
frame = self.frames[page_name]
frame.tkraise()
class StartPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="Passowrd program", font=controller.title_font)
label.pack(side="top", fill="x", pady=10)
button1 = tk.Button(self, text="Check your password strength",
command=lambda: controller.show_frame("PageOne"))
button2 = tk.Button(self, text="Generate a new password",
command=lambda:[generate(),time.sleep(0.1),controller.show_frame("PageTwo")])
button3 = tk.Button(self, text="quit", command=close)
button1.pack()
button2.pack()
button3.pack()
class PageOne(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label1 = tk.Label(self, text="Check your password", font=controller.title_font)
label1.pack(side="top", fill="x", pady=10)
entry = tk.Entry(self, bd =6)
button2 = tk.Button(self, text="Back",
command=lambda: controller.show_frame("StartPage"))
label2 = tk.Label(self, text="Strength:", font=controller.title_font)
label3 = tk.Label(self, text=strength, font=controller.title_font)
entry.pack()
button2.pack()
label2.pack()
label3.pack()
password = list(entry.get())
class PageTwo(tk.Frame):
def __init__(self, parent, controller):
'''while 0 == 0:
gen = mypw;'''
var = StringVar()
var.set(gen)
tk.Frame.__init__(self, parent)
self.controller = controller
label1 = tk.Label(self, text="Generate a password", font=controller.title_font)
label1.pack(side="top", fill="x", pady=10)
label2 = tk.Label(self, textvariable=var, font=controller.title_font)
button = tk.Button(self, text="Back",
command=lambda: controller.show_frame("StartPage"))
label2.pack()
button.pack()
def close():
messagebox.showinfo("BYE", "Thank you")
time.sleep(1)
app.destroy()
#def check_generate():
if __name__ == "__main__":
app = SampleApp()
app.mainloop()
generate()
so, that's my code, I hope someone can help, it would be really useful, thanks
The problem is that you aren't updating the var StringVar that is used to display the generated password. Here's a version of your code which fixes that, but it is a little messy. There are a couple of other problems with your code, but I'll let you discover those. ;)
from tkinter import *
import tkinter as tk
from tkinter import font as tkfont
import random
import time
global strength
global gen
strength = 0
gen = '[password will be here]'
global mypw
mypw = ''
def generate(pwvar):
alphabet = "abcdefghijklmnopqrstuvwxyz"
pw_length = 8
mypw = ""
for i in range(pw_length):
next_index = random.randrange(len(alphabet))
mypw = mypw + alphabet[next_index]
# replace 1 or 2 characters with a number
for i in range(random.randrange(1,3)):
replace_index = random.randrange(len(mypw)//2)
mypw = mypw[0:replace_index] + str(random.randrange(10)) + mypw[replace_index+1:]
# replace 1 or 2 letters with an uppercase letter
for i in range(random.randrange(1,3)):
replace_index = random.randrange(len(mypw)//2,len(mypw))
mypw = mypw[0:replace_index] + mypw[replace_index].upper() + mypw[replace_index+1:]
print(mypw)
gen = mypw
pwvar.set(gen)
class SampleApp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
self.title_font = tkfont.Font(family='Helvetica', size=18, weight="bold", slant="italic")
# the container is where we'll stack a bunch of frames
# on top of each other, then the one we want visible
# will be raised above the others
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, PageTwo):
page_name = F.__name__
frame = F(parent=container, controller=self)
self.frames[page_name] = frame
# put all of the pages in the same location;
# the one on the top of the stacking order
# will be the one that is visible.
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame("StartPage")
def show_frame(self, page_name):
'''Show a frame for the given page name'''
frame = self.frames[page_name]
frame.tkraise()
class StartPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="Password program", font=controller.title_font)
label.pack(side="top", fill="x", pady=10)
button1 = tk.Button(self, text="Check your password strength",
command=lambda: controller.show_frame("PageOne"))
button2 = tk.Button(self, text="Generate a new password",
command=lambda:[generate(self.controller.frames['PageTwo'].var),time.sleep(0.1),controller.show_frame("PageTwo")])
button3 = tk.Button(self, text="quit", command=close)
button1.pack()
button2.pack()
button3.pack()
class PageOne(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label1 = tk.Label(self, text="Check your password", font=controller.title_font)
label1.pack(side="top", fill="x", pady=10)
entry = tk.Entry(self, bd =6)
button2 = tk.Button(self, text="Back",
command=lambda: controller.show_frame("StartPage"))
label2 = tk.Label(self, text="Strength:", font=controller.title_font)
label3 = tk.Label(self, text=strength, font=controller.title_font)
entry.pack()
button2.pack()
label2.pack()
label3.pack()
password = list(entry.get())
class PageTwo(tk.Frame):
def __init__(self, parent, controller):
self.var = StringVar()
self.var.set(gen)
tk.Frame.__init__(self, parent)
self.controller = controller
label1 = tk.Label(self, text="Generate a password", font=controller.title_font)
label1.pack(side="top", fill="x", pady=10)
label2 = tk.Label(self, textvariable=self.var, font=controller.title_font)
button = tk.Button(self, text="Back",
command=lambda: controller.show_frame("StartPage"))
label2.pack()
button.pack()
def close():
messagebox.showinfo("BYE", "Thank you")
time.sleep(1)
app.destroy()
if __name__ == "__main__":
app = SampleApp()
app.mainloop()
generate()
Here's a slightly better way. Instead of having that dodgy list as the callback function in PageTwo we make a proper method, generate_password. Not only is it easier to read & to debug, by doing it this way we don't need to pass the password StringVar to generate, instead we can get generate to return the new password and then set the StringVar insidegenerate_password.
I've also gotten rid of that useless mypw global. I removed the messy from tkinter import *, and I added the tkinter.messagebox so that your close function will work.
import tkinter as tk
from tkinter import font as tkfont
import tkinter.messagebox as messagebox
import random
import time
global strength
global gen
strength = 0
gen = '[password will be here]'
def generate():
alphabet = "abcdefghijklmnopqrstuvwxyz"
pw_length = 8
mypw = ""
for i in range(pw_length):
next_index = random.randrange(len(alphabet))
mypw = mypw + alphabet[next_index]
# replace 1 or 2 characters with a number
for i in range(random.randrange(1,3)):
replace_index = random.randrange(len(mypw)//2)
mypw = mypw[0:replace_index] + str(random.randrange(10)) + mypw[replace_index+1:]
# replace 1 or 2 letters with an uppercase letter
for i in range(random.randrange(1,3)):
replace_index = random.randrange(len(mypw)//2,len(mypw))
mypw = mypw[0:replace_index] + mypw[replace_index].upper() + mypw[replace_index+1:]
print(mypw)
return mypw
class SampleApp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
self.title_font = tkfont.Font(family='Helvetica', size=18, weight="bold", slant="italic")
# the container is where we'll stack a bunch of frames
# on top of each other, then the one we want visible
# will be raised above the others
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, PageTwo):
page_name = F.__name__
frame = F(parent=container, controller=self)
self.frames[page_name] = frame
# put all of the pages in the same location;
# the one on the top of the stacking order
# will be the one that is visible.
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame("StartPage")
def show_frame(self, page_name):
'''Show a frame for the given page name'''
frame = self.frames[page_name]
frame.tkraise()
class StartPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="Password program", font=controller.title_font)
label.pack(side="top", fill="x", pady=10)
button1 = tk.Button(self, text="Check your password strength",
command=lambda: controller.show_frame("PageOne"))
button2 = tk.Button(self, text="Generate a new password",
command=self.generate_password)
button3 = tk.Button(self, text="quit", command=close)
button1.pack()
button2.pack()
button3.pack()
def generate_password(self):
password = generate()
password_var = self.controller.frames['PageTwo'].var
password_var.set(password)
time.sleep(0.1)
self.controller.show_frame("PageTwo")
class PageOne(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label1 = tk.Label(self, text="Check your password", font=controller.title_font)
label1.pack(side="top", fill="x", pady=10)
entry = tk.Entry(self, bd =6)
button2 = tk.Button(self, text="Back",
command=lambda: controller.show_frame("StartPage"))
label2 = tk.Label(self, text="Strength:", font=controller.title_font)
label3 = tk.Label(self, text=strength, font=controller.title_font)
entry.pack()
button2.pack()
label2.pack()
label3.pack()
password = list(entry.get())
class PageTwo(tk.Frame):
def __init__(self, parent, controller):
self.var = tk.StringVar()
self.var.set(gen)
tk.Frame.__init__(self, parent)
self.controller = controller
label1 = tk.Label(self, text="Generate a password", font=controller.title_font)
label1.pack(side="top", fill="x", pady=10)
label2 = tk.Label(self, textvariable=self.var, font=controller.title_font)
button = tk.Button(self, text="Back",
command=lambda: controller.show_frame("StartPage"))
label2.pack()
button.pack()
def close():
messagebox.showinfo("BYE", "Thank you")
time.sleep(1)
app.destroy()
if __name__ == "__main__":
app = SampleApp()
app.mainloop()
generate()
Related
I have been searching a lot and I still don't know, what is the problem. I have two windows asking for some values and as a result different functions are executed. I tried to bind an "Enter" key to buttons of different windows (so different functions should be executed), but this doesn't work.
Only thing that i could do is to bind key to the whole Frame, then unbind it and bind one more time. It works, but i'm curious why i can't link "Enter" key to separate buttons while no error appear. Thanks in advance!
Here is my code:
import tkinter as tk
class Page(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
self.shared_data = {
"number_of_frequencies": tk.StringVar(),
"frequencies": []}
container = tk.Frame(self)
container.grid()
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (StartPage, PageOne):
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(StartPage)
def create_entry_widget(self, i):
self.number = tk.StringVar()
self.number.set('')
self.shared_data["frequencies"].append(self.number)
new_widget = tk.Entry(self.master, textvariable=self.number)
return new_widget
def show_frame(self, c):
for frame in self.frames.values():
frame.grid_remove()
frame = self.frames[c]
frame.grid()
global number_of_frequencies
try:
number_of_frequencies = int(self.shared_data["number_of_frequencies"].get())
for i in range(number_of_frequencies):
tk.Label(self.master, text="Frequency "+str(i+1)).grid(row=i, column=0, padx=10, pady=5)
self.entry_widgets = self.create_entry_widget(i)
self.entry_widgets.grid(row=i, column=1, padx=10, pady=5)
page1 = self.get_page(PageOne)
tk.Button(self, text="Exit",
command=lambda: self.quitALL()).grid(row=i+1, column=0, padx=10, pady=10)
self.button1 = tk.Button(self, text = " Done ",
command=lambda: [page1.enter_freqs(), self.quitALL()])
self.unbind_all('<Return>') # work
self.bind('<Return>', (lambda a: [page1.enter_freqs(), self.quitALL()])) # work
# self.button1.bind('<Return>', (lambda a: [page1.enter_freqs(), self.quitALL()])) #doesn't work
self.button1.grid(row=i+1, column=1, padx=10, pady=10)
frame.tkraise()
except:
frame.tkraise()
def get_page(self, page_class):
return self.frames[page_class]
def quitALL(self):
self.destroy()
class StartPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller=controller
self.text = tk.Text(self, bg='gray93', bd=0, height=1, width=30, font=('Helvetica', 14))
self.text.insert(tk.INSERT, "Please enter number of frequencies:")
self.text.grid(padx=10, pady=10)
entry = tk.Entry(self, textvariable=self.controller.shared_data["number_of_frequencies"])
entry.grid(padx=10)
self.controller.bind('<Return>', (lambda a: controller.show_frame(PageOne))) # work
self.button = tk.Button(self, text=" Done ",
command=lambda: controller.show_frame(PageOne))
# self.button.bind('<Return>', (lambda a: controller.show_frame(PageOne))) # doesn't work
self.button.grid(padx=10, pady=10)
class PageOne(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller=controller
self.freq_list = self.controller.shared_data["frequencies"]
self.freq_list_int = []
def enter_freqs(self):
for freq in self.freq_list:
self.freq_list_int.append(int(freq.get()))
self.func(self.freq_list_int)
def func(self, freq_list):
print('some stuff')
if __name__ == "__main__":
app = Page()
app.mainloop()
I'm designing a login screen for my chat application. As I don't have much information about switching frames, I'm looking at the code here and edit for my project accordingly. For now, I want the "Page 2" to be shown when the credentials are entered correctly. However, when I enter the nickname and password correctly, nickname form remains in the second screen and it looks messed up like in the screenshoot I uploaded. Screenshot
How can I solve this problem? The code is below:
class SampleApp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
self.title_font = tkfont.Font(family='Helvetica', size=18, weight="bold", slant="italic")
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, PageTwo):
page_name = F.__name__
frame = F(parent=container, controller=self)
self.frames[page_name] = frame
F.grid_propagate(self)
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame("StartPage")
def show_frame(self, page_name):
frame = self.frames[page_name]
frame.tkraise()
class StartPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent, width=500, height=500)
self.controller = controller
db = MySQLdb.connect(host="localhost", user="root", passwd="", db="members")
cursor = db.cursor()
label = tk.Label(self, text="Nickname:")
label.place(x=140, y=150)
user_id = tk.Entry()
user_id.place(x=210, y=150)
label_2 = tk.Label(self, text="Password:")
label_2.place(x=140, y=200)
password = tk.Entry(self, show="*")
password.place(x=210, y=200)
def auth_login(event=None):
id = user_id.get()
pswd = password.get()
cursor.execute(
"SELECT nickname, password FROM chatmembers WHERE nickname='{}' AND password='{}' ".format(id, pswd))
if cursor.fetchone():
controller.show_frame("PageTwo")
else:
messagebox.showerror("Wrong credentials", "Either nickname or password is wrong. Please try again.")
login_button = tk.Button(self, text="Log In", command=auth_login, height=2, width=20)
login_button.place(x=195, y=250)
class PageOne(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent, width=500, height=500)
self.controller = controller
label = tk.Label(self, text="This is page 1", font=controller.title_font)
label.pack(side="top", fill="x", pady=10)
button = tk.Button(self, text="Go to the start page",
command=lambda: controller.show_frame("StartPage"))
button.place(x=100, y=200)
class PageTwo(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="This is page 2", font=controller.title_font)
label.pack(side="top", fill="x", pady=10)
button = tk.Button(self, text="Go to the start page",
command=lambda: controller.show_frame("StartPage"))
button.pack()
if __name__ == "__main__":
app = SampleApp()
app.mainloop()
I'm trying to load a new frame when the user presses the login button as long as the details entered are correct. I've included print commands within the LogInCheck function in order to see if the code is executing correctly, which it is. My only problem is that it wont change the frame. I get the error 'LogIn' object missing attribute 'show_frame'
from tkinter import *
from tkinter import ttk
import tkinter as tk
LARGE_FONT= ("Arial", 16)
SMALL_FONT= ("Arial", 12)
current_tariff = None
def tariff_A():
global current_tariff
current_tariff= "A"
def tariff_B():
global current_tariff
current_tariff= "B"
def tariff_C():
global current_tariff
current_tariff= "C"
class PhoneCompany(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, PageTwo, PageThree, PageFour, PageFive, LogIn):
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(LogIn)
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
Thats my main class and this is the login page class:
class LogIn(tk.Frame):
def LogInCheck(self):
global actEntry
global pinEntry
act = "james"
pin = "Python123"
actNum = actEntry.get()
pinNum = pinEntry.get()
print("FUNCTION RUN")
if actNum == act and pinNum == pin:
print("CORRECT")
self.show_frame(StartPage)
elif actNum != act or pinNum != pin:
print("INCORRECT")
self.show_frame(LogIn)
def __init__(self, parent, controller):
global actEntry
global pinEntry
self.controller = controller
tk.Frame.__init__(self, parent)
logLabel = ttk.Label(self, text = "Login With Your Username and
Password", font = LARGE_FONT)
logLabel.pack(side = TOP, anchor = N, expand = YES)
actLabel = Label(self, text = 'Username:')
actEntry = Entry(self)
pinLabel = Label(self, text = 'Password: ')
pinEntry = Entry(self, show ="*")
actLabel.pack(pady =10, padx = 10, side = TOP, anchor = N)
pinLabel.pack(pady =5, padx = 10, side = TOP, anchor = S)
actEntry.pack(pady =10, padx = 10, side = TOP, anchor = N)
pinEntry.pack(pady =5, padx = 10, side = TOP, anchor = S)
logInButton = tk.Button(self, text = "Login",
command = self.LogInCheck)
logInButton.pack(side = TOP, anchor = S)
quitButton = tk.Button(self, text = "Quit", command = quit)
quitButton.pack(side = BOTTOM, anchor = S)
if __name__ == "__main__":
app = PhoneCompany()
app.mainloop()
I'll include my full code if you need to look at the rest of it:
from tkinter import *
from tkinter import ttk
import tkinter as tk
LARGE_FONT= ("Arial", 16)
SMALL_FONT= ("Arial", 12)
current_tariff = None
def tariff_A():
global current_tariff
current_tariff= "A"
def tariff_B():
global current_tariff
current_tariff= "B"
def tariff_C():
global current_tariff
current_tariff= "C"
class PhoneCompany(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, PageTwo, PageThree, PageFour, PageFive, LogIn):
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(LogIn)
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)
label = tk.Label(self, text="MENU", font=LARGE_FONT)
label.pack(pady=10,padx=10)
button = tk.Button(self, text="View Account Balance",
command=lambda: controller.show_frame(PageOne))
button.pack()
button2 = tk.Button(self, text="Display Current Tariff",
command=lambda: controller.show_frame(PageTwo))
button2.pack()
button3 = tk.Button(self, text="View List of Rates",
command=lambda: controller.show_frame(PageThree))
button3.pack()
button4 = tk.Button(self, text="View Latest Bill",
command=lambda: controller.show_frame(PageFour))
button4.pack()
class PageOne(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="Account Balance", font=LARGE_FONT)
label.pack(pady=10,padx=10)
sublabel = tk.Label(self, text="Your current account balance is £230", font=SMALL_FONT)
sublabel.pack(pady=10,padx=10)
button1 = tk.Button(self, text="Back to Menu",
command=lambda: controller.show_frame(StartPage))
button1.pack()
class PageTwo(tk.Frame):
def __init__(self, parent, controller):
global current_tariff
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="Current Tariff", font=LARGE_FONT)
label.pack(pady=10,padx=10)
sublabel = tk.Label(self, text="Your current tariff is "+str(current_tariff), font=SMALL_FONT)
sublabel.pack(pady=10,padx=10)
button1 = tk.Button(self, text="Change Tariff",
command=lambda: controller.show_frame(PageFive))
button1.pack()
button2 = tk.Button(self, text="Back to Home",
command=lambda: controller.show_frame(StartPage))
button2.pack()
class PageThree(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="Tariff Rates", font=LARGE_FONT)
label.pack(pady=10,padx=10)
sublabel = tk.Label(self, text="Peak Rates: A: £0.30 | B: £0.10 | C: £0.90", anchor="w", font=SMALL_FONT)
sublabel.pack(pady=10,padx=10)
sublabel2 = tk.Label(self, text="Off Peak: A: £0.05 | B: £0.02 | C: -", anchor="w", font=SMALL_FONT)
sublabel2.pack(pady=10,padx=10)
sublabel3 = tk.Label(self, text="Line Rental: A: £15.00 | B: £20.00 | C: £30.00", anchor="w", font=SMALL_FONT)
sublabel3.pack(pady=10,padx=10)
button1 = tk.Button(self, text="Back to Home",
command=lambda: controller.show_frame(StartPage))
button1.pack()
class PageFour(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="Latest Bill", font=LARGE_FONT)
label.pack(pady=10,padx=10)
button1 = tk.Button(self, text="Back to Home",
command=lambda: controller.show_frame(StartPage))
button1.pack()
class PageFive(tk.Frame):
def __init__(self, parent, controller):
global current_tariff
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="Change Tariff", font=LARGE_FONT)
label.pack(pady=10,padx=10)
sublabel = tk.Label(self, text="Select new tariff\nView list of tariff rates on the main menu to see the prices.", font=SMALL_FONT)
sublabel.pack(pady=10,padx=10)
button1 = tk.Button(self, text="A",
command=lambda:[controller.show_frame(StartPage),tariff_A])
button1.pack()
button2 = tk.Button(self, text="B",
command=lambda:[controller.show_frame(StartPage),tariff_B])
button2.pack()
button3 = tk.Button(self, text="C",
command=lambda:[controller.show_frame(StartPage),tariff_C])
button3.pack()
button4 = tk.Button(self, text="Back to Home",
command=lambda: controller.show_frame(StartPage))
button4.pack()
class LogIn(tk.Frame):
def LogInCheck(self):
global actEntry
global pinEntry
act = "james"
pin = "Python123"
actNum = actEntry.get()
pinNum = pinEntry.get()
print("FUNCTION RUN")
if actNum == act and pinNum == pin:
print("CORRECT")
self.show_frame(StartPage)
elif actNum != act or pinNum != pin:
print("INCORRECT")
self.show_frame(LogIn)
def __init__(self, parent, controller):
global actEntry
global pinEntry
self.controller = controller
tk.Frame.__init__(self, parent)
logLabel = ttk.Label(self, text = "Login With Your Username and Password", font = LARGE_FONT)
logLabel.pack(side = TOP, anchor = N, expand = YES)
actLabel = Label(self, text = 'Username:')
actEntry = Entry(self)
pinLabel = Label(self, text = 'Password: ')
pinEntry = Entry(self, show ="*")
actLabel.pack(pady =10, padx = 10, side = TOP, anchor = N)
pinLabel.pack(pady =5, padx = 10, side = TOP, anchor = S)
actEntry.pack(pady =10, padx = 10, side = TOP, anchor = N)
pinEntry.pack(pady =5, padx = 10, side = TOP, anchor = S)
# runs the 'LoginCheck' function
logInButton = tk.Button(self, text = "Login",
command = self.LogInCheck)
logInButton.pack(side = TOP, anchor = S)
quitButton = tk.Button(self, text = "Quit", command = quit)
quitButton.pack(side = BOTTOM, anchor = S)
if __name__ == "__main__":
app = PhoneCompany()
app.mainloop()
I know it's quite messy and there may be other errors, but for now i just need to figure out why it wont change the frame after successfully logging in.
It needs to be self.controller.show_frame(StartPage).
i'm currently trying to creat a small accounting program where the user should type his earnings and expanses and the program should count it and display the differnt transactions in an secound frame. Im stuck at this point: So far ive created 6 frames where the user can switch between with buttons.
When the user click on the button "first transaction" he can entry a ammount and after he click on validate the ammount is displaying under the button.
But i want that the ammount is display at the frame "transaction overview"
After hours spending with searching the web i couln't find a way to display a functions output on a secound frame/window in the App. Thanks for your helf.
class Finanzapp(tk.Tk):
def get_page(self, classname):
for page in self.frames.values():
if str(page.__class__.__name__) == classname:
return page
return None
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
tk.Tk.wm_title(self, "Finanz Manager V2")
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, PageTwo, PageThree, Pagefour, Pagefive):
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):
self.controller = controller
tk.Frame.__init__(self,parent)
label = tk.Label(self, text="Start Page", font=LARGE_FONT)
label.pack(pady=10,padx=10)
button1 = ttk.Button(self, text="erste Buchung",
command=lambda: controller.show_frame(PageOne)) # add a page
button1.pack()
button2 = ttk.Button(self, text="Konten",
command=lambda: controller.show_frame(PageTwo)) # add a page
button2.pack()
button3 = ttk.Button(self, text="neue Buchung",
command=lambda: controller.show_frame(PageThree)) # add a page
button3.pack()
button4 = ttk.Button(self, text="Kategorien",
command=lambda: controller.show_frame(Pagefour)) # add a page
button4.pack()
button5 = ttk.Button(self, text="Übersicht",
command=lambda: controller.show_frame(Pagefive)) # add a page
button5.pack()
button6 = ttk.Button(self, text="Diagramm",
command=lambda: controller.show_frame(StartPage)) # add a page
button6.pack()
class PageOne(tk.Frame):
def __init__(self, parent, controller):
self.controller = controller
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="erste Buchung", font=LARGE_FONT)
label.pack(pady=10,padx=10)
button1 = ttk.Button(self, text="zurück",
command=lambda: controller.show_frame(StartPage)) # add a page
button1.pack()
def calc():
monthly_earning = float(m_earning.get())
labelresult1 = Label(self, text='gebucht: € %.2f' % monthly_earning).pack()
label1 = Label(self, text='Enter the amount').pack()
m_earning=StringVar()
earning=Entry(self, textvariable=m_earning).pack()
buttoncalc=Button(self,text='Buchen', command=calc).pack()
class PageTwo(tk.Frame):
def __init__(self, parent, controller):
def get_page(self,PageOne):
def print_it(self):
page_one = self.controller.get_page("PageOne")
value = page_one.monthly_m_earning.get()
labelresult2 = Label(self, text='gebucht: € %.2f' % value).pack()
self.controller = controller
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="Konten", font=LARGE_FONT)
label.pack(pady=10,padx=10)
button1 = ttk.Button(self, text="zurück",
command=lambda: controller.show_frame(StartPage))
button1.pack()
I am having trouble getting data input from one class to another and I cant seem to get the global function to work. The part i need help with is in the last function but it only works if you have the whole code.
import tkinter as tk
import os
self = tk
TITLE_FONT = ("AmericanTypewriter", 18, "bold")
#exit function
def Exit():
os._exit(0)
#Functions end
class SampleApp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
# the container is where we'll stack a bunch of frames
# on top of each other, then the one we want visible
# will be raised above the others
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 (Home, Population, Survival, Birth,NEW, data, Quit):
page_name = F.__name__
frame = F(parent=container, controller=self)
self.frames[page_name] = frame
# put all of the pages in the same location;
# the one on the top of the stacking order
# will be the one that is visible.
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame("Home")
def show_frame(self, page_name):
'''Show a frame for the given page name'''
frame = self.frames[page_name]
frame.tkraise()
class Home(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="Home", font=TITLE_FONT)
label.pack(side="top", fill="x", pady=10)
button1 = tk.Button(self, text="Population",
command=lambda: controller.show_frame("Population"))
button5 = tk.Button(self, text = "Quit",
command=lambda: controller.show_frame("Quit"))
button1.pack()
button5.pack()
class Population(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="Enter Generation 0 Values", font=TITLE_FONT)
label.pack(side="top", fill="x", pady=10)
#Function
def EnterPopulation():
b1 = populationa.get()
print (str(populationa.get()))
bj = populationj.get()
print (str(populationj.get()))
bs = populations.get()
print (str(populations.get()))
def cal(*args):
total = population_juveniles + population_adults + population_seniles
#Population
population = tk.Label(self, text="Value for the Populations")
population.pack()
labela= tk.Label(self, text= 'Population of Adults')
populationa = tk.Entry(self)
labela.pack()
populationa.pack()
population3 = tk.Button(self, text="Enter", command = EnterPopulation)
population3.pack()
labelj= tk.Label(self, text= 'Population of Juvenile')
populationj = tk.Entry(self)
labelj.pack()
populationj.pack()
population5 = tk.Button(self, text="Enter", command = EnterPopulation)
population5.pack()
labels= tk.Label(self, text= 'Population of Seniles')
populations = tk.Entry(self)
labels.pack()
populations.pack()
population6 = tk.Button(self, text="Enter", command = EnterPopulation)
population6.pack()
buttonS = tk.Button(self, text = "Survival Rates",
command=lambda: controller.show_frame("Survival"))
buttonS.pack()
class Survival(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="Survival Rates", font=TITLE_FONT)
label.pack(side="top", fill="x", pady=10)
def EnterSurvival(*self):
S = survivalaa.get()
ss = survivalj.get()
sss =survivals.get()
print(str(survivalaa.get()))
#Survival
Survival = tk.Label(self, text="Value of Survival Rates between 0-1")
Survival.pack()
survivala= tk.Label(self, text= 'Survival rates of Adults')
survivalaa = tk.Entry(self)
survivala.pack()
survivalaa.pack()
survival69= tk.Button(self, text="Enter", command = EnterSurvival)
survival69.pack()
survivaljj= tk.Label(self, text= 'Survival rates of Juvenile')
survivalj = tk.Entry(self)
survivaljj.pack()
survivalj.pack()
survival5 = tk.Button(self, text="Enter", command = EnterSurvival)
survival5.pack()
labelss= tk.Label(self, text= 'Survival rates of Seniles')
survivals = tk.Entry(self)
labelss.pack()
survivals.pack()
survival6 = tk.Button(self, text="Enter", command = EnterSurvival)
survival6.pack()
buttonS = tk.Button(self, text = "Birth Rates",
command=lambda: controller.show_frame("Birth"))
buttonS.pack()
class Birth(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="Birth Rates", font=TITLE_FONT)
label.pack(side="top", fill="x", pady=10)
def EnterBirth(*args):
Birth1 = Birth2.get()
Birtha = tk.Label(self, text="Birth rates")
Birtha.pack()
Birth2 = tk.Entry(self)
Birth2.pack()
Birth3 = tk.Button(self, text="OK", command = EnterBirth)
Birth3.pack()
buttonB = tk.Button(self, text = "New Generatons",
command=lambda: controller.show_frame("NEW"))
buttonB.pack()
#Number of New Generations To Model
class NEW(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="New Generations", font=TITLE_FONT)
label.pack(side="top", fill="x", pady=10)
def EnterNew(*args):
print (New2.get())
news = New2.get()
New = tk.Label(self, text="Number of New Generatiions 5 - 25")
New.pack()
New2 = tk.Entry(self)
New2.pack()
New3 = tk.Button(self, text="OK", command = EnterNew)
New3.pack()
button = tk.Button(self, text="BACK To Home",
command=lambda: controller.show_frame("data"))
button.pack()
class data(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="Data", font=TITLE_FONT)
label.pack(side="top", fill="x", pady=10)
no = tk.Button(self, text = "No",
command = lambda: controller.show_frame("Home"))
no.pack()
global Birth1
global s
global ss
global sss
global b1
global bj
global bs
global news
spja= b1 * s
spjb = bj * ss
spjs= bs * sss
st = spja + spjb + spjs
born = spja* rebirth
old = b1 + bj + bs
labelold = tk.Label(self, text = 'Orignal populaton'+str(old))
labelold.pack()
labelto = tk.Label(self, text='Adults that survived = '+str(spja)+ 'Juveniles = ' +str(spjb)+ 'Seniles = '+str(spjs)+ '/n Total= '+str(st))
labelto.pack()
Labelnew= tk.Label(self, text='New Juveniles = '+str(born))
Labelnew.pack()
# function for export data
class Quit(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="Are you sure you want to quit?", font=TITLE_FONT)
label.pack(side="top", fill="x", pady=10)
yes = tk.Button(self, text="Yes", command = Exit)
yes.pack()
no = tk.Button(self, text = "No",
command = lambda: controller.show_frame("Home"))
no.pack()
if __name__ == "__main__":
app = SampleApp()
app.mainloop(
If you want to use global variables, you need to do this:
var1 = <some value>
var2 = <some other value>
s1 = <yet another value here>
# then create your classes
class Whatever(tk.whatever_you_want):
def __init__(self, arg1, arg2, whatever_arg):
global var1 #whis tells the function to use the variable you defined already in the module scope
local_var_1 = var1 * 100 #
Of course, perhaps you don't know this already, global variables are usually considered bad to start with, but I don't think it matters much for you. It's going to matter when you modify and read the variables from waaay too many places to keep track of, but I'm not sure you're building that big of a script.