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.
Related
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()
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 writing a GUI code that opens frame using Tkinter. I referred various websites. Now while testing I am facing problem. For example:
In 1st frame, I select MainController button.
in 2nd frame press MC_CONFIG button.
in 3rd frame I set XML PATH then clicked MC SYSTEM.xml button
If I go to Back to Home button and follow the same procedure, MC_CONFIG button gets disabled (i.e I cannot go further).
If I comment(delete) this line(126)
tk.Frame.__init__(self)
in method def nacxml(self): of class MC_CONFIG, it is working perfectly.
The below one is just part of my main code bu facing problem here.
Please guide me.
import Tkinter as tk
import xml.dom.minidom
from Tkinter import *
import tkMessageBox
from array import *
import tkFileDialog
import os
LARGE_FONT= ("Verdana", 12)
class SeaofBTCapp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
tk.Tk.wm_title(self, "Switch Installer window")
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):
for F in (StartPage, MainController,xmlpath,MC_CONFIG):
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)
self.modules_label = ['MAINCONTROLLER']
self.modules_function = [MainController]
self.modules_label_index = len(self.modules_label)
self.modules_function_index = len(self.modules_function)
print("self.modules_label_index = %s" %self.modules_label_index)
label = Label(self, text="SWITCH INSTALLER", font=LARGE_FONT)
label.pack(pady=10,padx=10)
#button = Button(self, text="Visit Page 1",
button3 = Button(self, text="SELECT",
command=lambda: controller.show_frame(MainController))
button3.pack()
label3 = Label(self, text="MainController", font = LARGE_FONT)
label3.place(x= 50, y=100+10)
button8 = Button(self, text="Quit", command=self.quit)
button8.pack()
class xmlpath(tk.Frame):
#xfilename="+++"
def __init__(self, parent, controller):
self.xfilename="srinivasan"
tk.Frame.__init__(self, parent)
label = Label(self, text="Page One!!!", font=LARGE_FONT)
label.pack(pady=10,padx=10)
button1 = Button(self, text="Back to Home",
command=lambda: controller.show_frame(StartPage))
button1.pack()
button1 = Button(self, text="XML PATH",
command=self.newxmlpath)
button1.pack()
def newxmlpath(self,*args):
# ObjNAC= NacHandler()
self.filename = tkFileDialog.askopenfilename()
print(self.filename)
#ObjNAC.temp_method(self,self.filename)
return self.filename
class MainController(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = Label(self, text="|--Frame1 MainController --|", font = LARGE_FONT)
label.pack(pady=10,padx=10)
mc_button1 = Button(self, text="MC_CONFIG", command = lambda: controller.show_frame(MC_CONFIG))
mc_button1.pack()
mc_button2 = Button(self, text="MENU HOME", command = lambda: controller.show_frame(StartPage))
mc_button2.pack()
self.pack (fill = BOTH, expand = 1)
class MC_CONFIG(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
print "Inside MC_CONFIG"
self.database = []
# set root as parent
self.parent = parent
label1 = Label(self, text="|------------Frame2--MainController---------------|", font=LARGE_FONT)
label1.pack(pady = 10,padx = 10)
label2 = Label(self, text="Edit SYSTEM.xml File", font=LARGE_FONT)
label2.pack(pady = 10,padx = 10)
button1 = Button(self, text="XML PATH",
command=self.newxmlpath)
button1.pack(pady = 10,padx = 10)
button2 = Button(self, text = "MC SYSTEM.xml", command = self.nacxml)
button2.pack(pady = 10,padx = 10)
button3 = Button(self, text="Back to Home",
command=lambda: controller.show_frame(StartPage))
button3.pack(pady = 10,padx = 10)
def newxmlpath(self, *args):
self.filename = tkFileDialog.askopenfilename()
print(self.filename)
return self.filename
def nacxml(self):
tk.Frame.__init__(self)
print "===Inside Nacxml1==="
app = SeaofBTCapp()
app.geometry ("640x480+300+300")
app.mainloop()
The problem is this:
def nacxml(self):
tk.Frame.__init__(self)
You should only ever call the superclass constructor from within the constructor of the subclass. Doing so anywhere else will certainly not do whatever you think it's doing.
Finally code is working as intended
1.Deleted tk.Frame.__init__(self) as indicated by Bryan Oakley
def nacxml(self):
tk.Frame.__init__(self)
2.Controller is not intialized in self.But it is present in def __init__(self, parent, controller):.Hence added
self.controller = controller in MC_CONFIG class
class MC_CONFIG(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
print "Inside MC_CONFIG"
So can be used in below method as self.controller.show_frame(StartPage)
def nacxml(self):
tk.Frame.__init__(self)
print "===Inside Nacxml1==="
# xml read,edit,widget code will be added here
self.controller.show_frame(StartPage)
So I'm fairly new to the tkiner programming and trying my hands at a GUI with more than one window wich should scan Wifi-Hotspots and show me a list of them. I've copied an example from Switch between two frames in tkinter to get the different windows
I have a Main Menu to enable Monitor Mode for the Wifi-Card and to start the scan. I'm calling another frame with a Listbox to show the results.
My problem now is, that the function startScan(self) is called within StartPage, while the Listbox is in PageOne. How can I adress it there and add entrys to it?
class PyWiFi(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 (StartPage, PageOne, PageTwo):
frame = F(container, self)
self.frames[F] = 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, c):
'''Show a frame for the given class'''
frame = self.frames[c]
frame.tkraise()
class StartPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="Main Menu", font=TITLE_FONT)
label.pack(side="top", fill="x", pady=10)
self.var = tk.IntVar()
monCheck = tk.Checkbutton(self, text="Monitor Mode", variable=self.var, command=self.monSwitch)
scanButton = tk.Button(self, text="Start Scan", command=self.startScan)
quitButton = tk.Button(self, text="Quit", command=self.master.quit)
monCheck.pack()
scanButton.pack()
quitButton.pack()
def monSwitch(self):
if(self.var.get()):
print "Monitor Modus an"
check_call(["airmon-ng", "start", "wlan0"])
else:
print "Monitor Modus aus"
check_call(["airmon-ng", "stop", "mon0"])
def startScan(self):
print "Scan gestartet"
app.show_frame(PageOne)
output=check_output('iwlist wlan0 scan | grep -E "Channel:|ESSID:"', shell=True)
netze = output.split()
print netze
for i in range(0,(len(netze)/2)-1):
string = netze[2*i]+" "+netze[2*i+1]
app.frames[PageOne].netzList.insert(END, string)
class PageOne(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="Scanergebnisse", font=TITLE_FONT)
label.pack(side="top", fill="x", pady=10)
menuButton = tk.Button(self, text="Menu", command=lambda: controller.show_frame(StartPage))
quitButton = tk.Button(self, text="Quit", command=self.master.quit)
button = tk.Button(self, text="P2", command=lambda: controller.show_frame(PageTwo))
netzList = tk.Listbox(self, width=30)
netzList.pack()
quitButton.pack(side=LEFT)
menuButton.pack(side=LEFT)
button.pack(side=LEFT)
class PageTwo(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="This is page 2", font=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 = PyWiFi()
app.resizable(0, 0)
app.geometry("320x240")
app.mainloop()
netzlist and all other widgets defined in PageOne are local to __init__. You should name them self.netzlist etc. to be able to reference them as class attributes of PageOne later on.