can't switch between frames in Tkinter - python

I've used Tkinter-Designer to convert a Figma frame into a python code, I then added that code to the StartPage class, and used the code mentioned here to switch between the frames.
For some reason, I can't get button_5 to work. When I click button_5 I expect it to switch to PageOne, but nothing happens. I'm not good with OOP, can you tell me what I'm doing wrong here?
Here is the full code:
import tkinter as tk # python 3
from tkinter import font as tkfont # python 3
from pathlib import Path
OUTPUT_PATH = Path(__file__).parent
ASSETS_PATH = OUTPUT_PATH / Path(r"Z:\python\projects\v\code\gui\tmp\TkinterDesigner\build\assets\frame0")
def relative_to_assets(path: str) -> Path:
return ASSETS_PATH / Path(path)
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
canvas = tk.Canvas(
bg="#FFFFFF",
height=724,
width=1056,
bd=0,
highlightthickness=0,
relief="ridge"
)
canvas.place(x=0, y=0)
canvas.create_rectangle(
56.0,
68.0,
954.0,
673.0,
fill="#F2F2F2",
outline="")
canvas.create_rectangle(
56.0,
68.0,
285.0,
673.0,
fill="#D4D3D3",
outline="")
self.button_image_1 = tk.PhotoImage(
file=relative_to_assets("button_1.png"))
button_1 = tk.Button(
image=self.button_image_1,
borderwidth=0,
highlightthickness=0,
command=lambda: print("button_1 clicked"),
relief="flat"
)
button_1.place(
x=56.0,
y=348.0,
width=229.0,
height=37.0
)
self.button_image_2 = tk.PhotoImage(
file=relative_to_assets("button_2.png"))
button_2 = tk.Button(
image=self.button_image_2,
borderwidth=0,
highlightthickness=0,
command=lambda: print("button_2 clicked"),
relief="flat"
)
button_2.place(
x=56.0,
y=312.0,
width=229.0,
height=37.0
)
self.button_image_3 = tk.PhotoImage(
file=relative_to_assets("button_3.png"))
button_3 = tk.Button(
image=self.button_image_3,
borderwidth=0,
highlightthickness=0,
command=lambda: print("button_3 clicked"),
relief="flat"
)
button_3.place(
x=56.0,
y=274.0,
width=229.0,
height=36.0
)
self.button_image_4 = tk.PhotoImage(
file=relative_to_assets("button_4.png"))
button_4 = tk.Button(
image=self.button_image_4,
borderwidth=0,
highlightthickness=0,
command=lambda: print("button_4 clicked"),
relief="flat"
)
button_4.place(
x=56.0,
y=239.0,
width=229.0,
height=36.0
)
self.button_image_5 = tk.PhotoImage(
file=relative_to_assets("button_5.png"))
button_5 = tk.Button(
image=self.button_image_5,
borderwidth=0,
highlightthickness=0,
command=lambda: controller.show_frame("PageOne"),
relief="flat"
)
button_5.place(
x=56.0,
y=201.0,
width=229.0,
height=37.0
)
self.image_image_1 = tk.PhotoImage(
file=relative_to_assets("image_1.png"))
image_1 = canvas.create_image(
617.0,
300.0,
image=self.image_image_1
)
canvas.create_text(
706.0,
574.0,
anchor="nw",
text=" -Jim Rohn",
fill="#000000",
font=("RobotoMono Regular", 14 * -1)
)
canvas.create_text(
433.0,
500.0,
anchor="nw",
text="“Reading is essential for those who seek to rise above the ordinary.” ",
fill="#000000",
font=("RobotoMono Regular", 14 * -1)
)
canvas.create_text(
84.0,
100.0,
anchor="nw",
text="Hello ZZZ!",
fill="#000000",
font=("RobotoMono Bold", 18 * -1)
)
class PageOne(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
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.pack()
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.geometry("1056x724")
app.configure(bg="#FFFFFF")
app.mainloop()

You did not specify the parent when creating those widgets inside StartPage, so they will be children of the root window. The canvas is large enough to cover those pages so you cannot see them.
Specify the parent (self) when creating those widgets:
class StartPage(tk.Frame):
def __init__(self, parent, controller):
...
canvas = tk.Canvas(
self, # specify parent
bg="#FFFFFF",
...
)
...
button_1 = tk.Button(
self,
image=...
...
)
...
button_2 = tk.Button(
self,
image=...
...
)
...
button_3 = tk.Button(
self,
image=...
...
)
...
button_4 = tk.Button(
self,
image=...
...
)
...
button_5 = tk.Button(
self,
image=...
...
)
...

Related

Why tkinter multiple window GUI not working properly?

I am creating multiple window GUI using tkinter.
I did not receive any errors. First window runs successfully but when I clicked the button the second window doesn't run.
I don't understand where there's an error,
and if I pack Entry widget and Buttons they don't show in window.
import tkinter as tk
import pywhatkit
import pyautogui
class automation(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
self.geometry("842x510")
self.configure(bg="#ffffff")
self.resizable(False, False)
self.container = container = tk.Frame(self, background="#ffffff")
container.grid(row=0, column=0, sticky='nesw')
container.configure(background="#ffffff")
container.pack(side="top", fill="both")
self.frames = {}
for F in (MainWindow, SecondWindow):
page_name = F.__name__
frame = F(parent=container, controller=self)
frame.grid(row=0, column=0, sticky="nsew")
self.frames[page_name] = frame
self.show_frame('MainWindow')
def show_frame(self, page_name):
if page_name not in self.frames:
self.frames[page_name] = page_name(self.container, self)
frame = self.frames[page_name]
frame.tkraise()
def btn_clicked():
print("Button Clicked")
Code for first window.
class MainWindow(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
self.frame = tk.Frame(self, background="#ffffff")
self.canvas = tk.Canvas(self, bg="#ffffff", height=510, width=391, bd=0,
highlightthickness=0, relief="ridge")
self.canvas.place(x=0, y=0)
self.canvas.pack(side='left')
self.background_img = tk.PhotoImage(file="background.png")
self.canvas.create_image(0, 0, image=self.background_img, anchor="nw")
self.img1 = tk.PhotoImage(file="img1.png")
self.b1 = tk.Button(self, image=self.img1, borderwidth=0, highlightthickness=0,
command=lambda: controller.show_frame(SecondWindow),
relief="flat")
self.b1.place(x=392, y=100, width=348, height=62)
self.b1.pack(padx=10, pady=125)
self.b1.pack()
# creating third button
self.img3 = tk.PhotoImage(file="img3.png")
self.b3 = tk.Button(self, image=self.img3, borderwidth=0, highlightthickness=0,
command=btn_clicked, relief="flat")
self.b3.place(x=392, y=200, width=348, height=62)
self.b3.pack(padx=10, pady=0)
self.b3.pack()
self.canvas.pack()
def send(num, msg, hour, minute):
pywhatkit.sendwhatmsg(f"+91{num}", msg, hour, minute, 36)
print("hello")
pyautogui.click()
pyautogui.press("enter")
Code for second window:
class SecondWindow(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
a = tk.StringVar()
b = tk.StringVar()
c = tk.IntVar()
d = tk.IntVar()
self.controller = controller
self.frame = tk.Frame(self, background="#ffffff")
self.canvas = tk.Canvas(self, bg="#ffffff", height=510, width=842, bd=0,
highlightthickness=0, relief="ridge")
self.canvas.place(x=0, y=0)
self.canvas.pack(side='left')
# set image in background
self.background_img = tk.PhotoImage(file="background2.png")
self.canvas.create_image(0, 0, image=self.background_img, anchor="nw")
# enter a number
self.entry1_img = tk.PhotoImage(file="textBox1.png")
self.canvas.create_image(570, 112, image=self.entry1_img)
self.entry1 = tk.Entry(self, bd=0, bg="#c4c4c4", highlightthickness=0, textvariable=a)
self.entry1.place(x=423, y=90, width=280, height=45)
#self.entry1.pack()
# enter a massage
self.entry2_img = tk.PhotoImage(file="textBox2.png")
self.canvas.create_image(570, 225, image=self.entry2_img)
self.entry2 = tk.Entry(self, bd=0, bg="#c4c4c4", highlightthickness=0, textvariable=b)
self.entry2.place(x=423, y=203, width=280, height=45)
#self.entry2.pack()
# enter a time -> Hour
self.entry3_img = tk.PhotoImage(file="textBox3.png")
self.canvas.create_image(470, 329, image=self.entry3_img)
self.entry3 = tk.Entry(self, bd=0, bg="#c4c4c4", highlightthickness=0, textvariable=c)
self.entry3.place(x=423, y=312, width=80.0, height=35)
#self.entry3.pack()
# minute
self.entry4_img = tk.PhotoImage(file="textBox4.png")
self.canvas.create_image(676, 329, image=self.entry4_img)
self.entry4 = tk.Entry(self, bd=0, bg="#c4c4c4", highlightthickness=0, textvariable=d)
self.entry4.place(x=630, y=312, width=80.0, height=35)
#self.entry4.pack()
# Go home
self.img4 = tk.PhotoImage(file="img4.png")
self.b4 = tk.Button(self, image=self.img4, borderwidth=0, highlightthickness=0,
command=lambda: controller.show_frame(MainWindow), relief="flat")
self.b4.place(x=418, y=400, width=100, height=37)
#self.b4.pack()
# Send message
self.img5 = tk.PhotoImage(file="img5.png")
self.b5 = tk.Button(self, image=self.img5, borderwidth=0, highlightthickness=0,
command=lambda: send(a.get(), b.get(), c.get(), d.get()),
relief="flat")
self.b5.place(x=642, y=400, width=100, height=37)
#self.b5.pack()
self.canvas.pack()
if __name__ == '__main__':
app = automation()
app.mainloop()
command=lambda: controller.show_frame(SecondWindow), is passing the class id as argument so page_name is not being found.
suggest
command=lambda: controller.show_frame('SecondWindow')

how to move my label's text position above the label's image Tkinter

I'm building a GUI for academic use. However, I have a main window with several changing frames. All frames have the same background image, but only the first one has the text above it - Start Page. The two others have their text up to the image. How can I solve it so the other two will be the same?
import tkinter as tk
# from tkinter import *
from tkinter import ttk, font, filedialog
from PIL import ImageTk, Image
import os
GUI_WIDTH, GUI_HEIGHT = 600, 900
# FONT_STYLE = font.Font(family="Segoe Script", size=10, weight=font.BOLD)
# FONT_STYLE = ("Segoe Script", 10)
BUTTONS_FONT_STYLE = ('Vardine', 11, 'bold')
TITLES_FONT_STYLE = ('Vardine', 21, 'bold')
class App(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
tk.Tk.iconbitmap(self, default='afeka logo 3.ico')
tk.Tk.wm_title(self, 'Detection of colon tumors through ultrasound images')
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, OverviewPage, LaunchPage):
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()
def openDocxFile():
os.startfile("Final_Project.docx")
def uploadImage(event=None):
filename = filedialog.askopenfilename()
if filename:
print('Selected:', filename)
def adjustImage(event):
label = event.widget
width = event.width
height = event.height
image = Image.open('background1.png')
resizedImage = image.resize((width, height))
newImage = ImageTk.PhotoImage(resizedImage)
label.config(image=newImage)
label.image = newImage
class StartPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.image = tk.PhotoImage(file='background1.png')
label = ttk.Label(self, text='Start Page', image=self.image, font=TITLES_FONT_STYLE, relief='raised', compound='bottom')
label.bind('<Configure>', adjustImage)
label.pack(expand=True)
button_overview_page = tk.Button(self, text='overview', font=BUTTONS_FONT_STYLE,
command=lambda: controller.show_frame(OverviewPage))
button_overview_page.place(relx=0.35, rely=0.2, relwidth=0.3, relheight=0.1)
button_doc_file = tk.Button(self, text='docx file', font=BUTTONS_FONT_STYLE, command=openDocxFile)
button_doc_file.place(relx=0.35, rely=0.4, relwidth=0.3, relheight=0.1)
button_launch_page = tk.Button(self, text='launch page', font=BUTTONS_FONT_STYLE,
command=lambda: controller.show_frame(LaunchPage))
button_launch_page.place(relx=0.35, rely=0.6, relwidth=0.3, relheight=0.1)
button_exit = tk.Button(self, text='exit', font=BUTTONS_FONT_STYLE, command=quit)
button_exit.place(relx=0.35, rely=0.8, relwidth=0.3, relheight=0.1)
class OverviewPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.image = tk.PhotoImage(file='background1.png')
label = tk.Label(self, text="Overview Page", image=self.image, font=TITLES_FONT_STYLE, relief='raised',
compound='bottom')
label.bind('<Configure>', adjustImage)
label.pack(expand=True)
button_start_page = tk.Button(self, text='start page', font=BUTTONS_FONT_STYLE,
command=lambda: controller.show_frame(StartPage))
button_start_page.place(relx=0.35, rely=0.6, relwidth=0.3, relheight=0.1)
# button_launch_page = tk.Button(self, text='launch page', font=BUTTONS_FONT_STYLE,
# command=lambda: controller.show_frame(LaunchPage))
# button_launch_page.place(relx=0.35, rely=0.4, relwidth=0.3, relheight=0.1)
button_exit = tk.Button(self, text='exit', font=BUTTONS_FONT_STYLE, command=quit)
button_exit.place(relx=0.35, rely=0.8, relwidth=0.3, relheight=0.1)
class LaunchPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.image = tk.PhotoImage(file='background1.png')
label = tk.Label(self, text="Launch Page", image=self.image, font=TITLES_FONT_STYLE, relief='raised', compound='bottom')
label.bind('<Configure>', adjustImage)
label.pack(expand=True)
button_start_page = tk.Button(self, text='start page', font=BUTTONS_FONT_STYLE,
command=lambda: controller.show_frame(StartPage))
button_start_page.place(relx=0.35, rely=0.6, relwidth=0.3, relheight=0.1)
# button_overview_page = tk.Button(self, text='overview', font=BUTTONS_FONT_STYLE,
# command=lambda: controller.show_frame(OverviewPage))
# button_overview_page.place(relx=0.35, rely=0.3, relwidth=0.3, relheight=0.1)
button_upload_image = tk.Button(self, text='upload image', font=BUTTONS_FONT_STYLE,
command=lambda: [uploadImage(), button_launch_detection.config(text='launch detection', state='normal')])
button_upload_image.place(relx=0.35, rely=0.2, relwidth=0.3, relheight=0.1)
button_launch_detection = tk.Button(self, text='upload an image\nto enable launching', font=BUTTONS_FONT_STYLE)
button_launch_detection.place(relx=0.35, rely=0.4, relwidth=0.3, relheight=0.1)
button_launch_detection.config(state='disabled')
button_exit = tk.Button(self, text='exit', font=BUTTONS_FONT_STYLE, command=quit)
button_exit.place(relx=0.35, rely=0.8, relwidth=0.3, relheight=0.1)
app = App()
# Define geometry - size and position
# Center app window on the screen
screen_width = app.winfo_screenwidth()
screen_height = app.winfo_screenheight()
center_x = int(screen_width / 2 - GUI_WIDTH / 2)
center_y = int(screen_height / 2 - GUI_HEIGHT / 2)
app.geometry(f'{GUI_WIDTH}x{GUI_HEIGHT}+{center_x}+{center_y}')
# # Decrease factor to change window's transparency
# app.attributes('-alpha', 1)
# Create sizegrip
app.mainloop()
enter image description here2
enter image description here

my program has a page(main page) that has 5 radio button in it and a button "ok",and I have 5 other Frame

my program has a page(main page) that has 5 radio button in it and a button "ok",and I have 5 other Frame. I want my program to go to these frames after clicking the "ok" ( based on the chosen radio button).
when the "ok" is clicked it will call a lambda and get the value of chosen radiobutton and based on this value put the correct string (veg) which represent the name of the page we want to go to. I don't know where to call this:
controller.show_frame(veg)
if i put : controller.show_frame(veg) in the okclick function I receive this error:
Exception in Tkinter callback Traceback (most recent call last): File "C:\ProgramData\Anaconda3\lib\tkinter_init_.py", line 1699, in call return self.func(*args) File "C:/Users/AI/PycharmProjects/KBS/alaki.py", line 37, in button2 = ttk.Button(self, command=lambda : okclick(v) ,text='OK', width=25) File "C:/Users/AI/PycharmProjects/KBS/alaki.py", line 65, in okclick controller.show_frame(veg) NameError: name 'controller' is not defined
here is the code:
import tkinter as tk
from tkinter import ttk
from win32print import StartPage
class KBSapp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
tk.Tk.iconbitmap(self,default="icon.ico")
tk.Tk.wm_title(self, "Diseases and pests of vegetable crops")
container = tk.Frame(self, width=200, height=200, bg='black')
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,carrot,celery, potato, wheat, bean):
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)
label = tk.Label(self, width=0, height=20)
label.pack()
button2 = ttk.Button(self, command=lambda : okclick(v) ,text='OK', width=25)
button2.pack( )
v = tk.IntVar( )
self.option1 = ttk.Radiobutton(self, text="Carrot", variable=v, value=1);self.option1.pack( )
self.option2 = ttk.Radiobutton(self, text="Celery", variable=v, value=2);self.option2.pack( )
self.option3 = ttk.Radiobutton(self, text="potato", variable=v, value=3);self.option3.pack( )
self.option4 = ttk.Radiobutton(self, text="wheat", variable=v, value=4);self.option4.pack( )
self.option5 = ttk.Radiobutton(self, text="bean", variable=v, value=5);self.option5.pack( )
v.set(1) # initializing the choice
def okclick(v):
global veg
input1=v.get( )
if input1==1:
veg="carrot"
if input1==2:
veg='celery'
if input1==3:
veg='potato'
if input1==4:
veg='wheat'
if input1==5:
veg='bean'
print(veg)
class carrot(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, width=0, height=20)
label.pack( )
button3 = ttk.Button(self, command=lambda : controller.show_frame(celery) , text='celery', width=25)
button3.pack( )
class celery(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, width=0, height=20)
label.pack( )
button4 = ttk.Button(self, command=lambda : controller.show_frame(potato) , text='potato', width=25)
button4.pack( )
class potato(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, width=0, height=20)
label.pack( )
button4 = ttk.Button(self, command=lambda : controller.show_frame(wheat) , text='wheat', width=25)
button4.pack( )
class wheat(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, width=0, height=20)
label.pack( )
button4 = ttk.Button(self, command=lambda : controller.show_frame(bean) , text='bean', width=25)
button4.pack( )
class bean(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, width=0, height=20)
label.pack( )
button4 = ttk.Button(self, command=lambda : controller.show_frame(StartPage) , text='StartPage', width=25)
button4.pack( )
app = KBSapp( )
app.mainloop( )

My buttons sit side by side in my Home window but they appear in the middle. How do I get them higher up?

I am having a similar issue with the Shop class too. My first button (Teapops) is where I want all my buttons on my Home window and Shop window to be (except for Back to Home) if I use:
button1.pack(side=TOP, anchor=NW, padx=10, pady=60, expand=NO)
button2.pack(side=TOP, anchor=NW, padx=30, pady=60, expand=NO)
button3.pack(side=TOP, anchor=NW, padx=60, pady=60, expand=NO)
But then all the others appear lower and lower and I don't have any idea why except maybe I have an issue with my frames?
If I use this,
button1.pack(side=LEFT, anchor=NW, fill=BOTH, expand=1)
button2.pack(side=LEFT, anchor=NW, fill=BOTH, expand=1)
button3.pack(side=LEFT, anchor=NW, fill=BOTH, expand=1)
then all my buttons appear side by side but in the middle of the screen again like on my Home screen:
Can someone please explain to me whats going on? I think there are some basics about Frames that I am not understanding. Please help!!!!
import Tkinter as tk
from Tkinter import *
TITLE_FONT = (“Helvetica”, 18, “bold”)
CREDITS_FONT = (“Helvetica”, 12, “bold”)
class App(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 (Home, My_Plnts, Jrnl, Shop, Mail):
page_name = F.__name__
frame = F(parent=container, controller=self)
self.frames[page_name] = frame
frame.grid(row=0, column=0, sticky=“nsew”)
self.show_frame(“Home”)
def show_frame(self, 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
Home.configure(self, background=’#ade5ad’)
label = tk.Label(self, text=“Welcome Home, Maebert!”, background=’#ade5ad’, font=TITLE_FONT)
label.pack(side=“top”, fill=“x”, pady=10)
button1 = tk.Button(self, text=“My Plnts”,
command=lambda: controller.show_frame(“My_Plnts”))
button2 = tk.Button(self, text=“Jrnl”,
command=lambda: controller.show_frame(“Jrnl”))
button3 = tk.Button(self, text=“Shop”,
command=lambda: controller.show_frame(“Shop”))
button4 = tk.Button(self, text=“Mail”,
command=lambda: controller.show_frame(“Mail”))
button1.pack(side=LEFT, padx=60)
button2.pack(side=LEFT, padx=60)
button3.pack(side=LEFT, padx=60)
button4.pack(side=LEFT, padx=60)
class My_Plnts(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
My_Plnts.configure(self, background=’#ade5ad’)
label = tk.Label(self, text=“My Plnts”, background=’#ade5ad’, font=TITLE_FONT)
label.pack(side=“top”, anchor=NW, fill=“x”, pady=10)
button = tk.Button(self, text=“Back to Home”,
command=lambda: controller.show_frame(“Home”))
button.pack(side=“top”, anchor=NE)
class Jrnl(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
Jrnl.configure(self, background=’#ade5ad’)
label = tk.Label(self, text=“Jrnl”, background=’#ade5ad’, font=TITLE_FONT)
label.pack(side=“top”, fill=“x”, pady=10)
button = tk.Button(self, text=“Back to Home”,
command=lambda: controller.show_frame(“Home”))
button.pack(side=“top”, anchor=NE)
class Shop(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
Shop.configure(self, background=’#ade5ad’)
label = tk.Label(self, text=“Shop”, background=’#ade5ad’, font=TITLE_FONT)
label.pack(side=“top”, fill=“x”, pady=10)
label = tk.Label(self, text=“More at www.gfc.com”, background=’#ade5ad’, font=CREDITS_FONT)
label.pack(side=“bottom”, fill=“x”, pady=10)
button = tk.Button(self, text=“Back to Home”,
command=lambda: controller.show_frame(“Home”))
button1 = tk.Button(self, text=“Teapops”,
command=lambda: controller.show_frame(“Teapops”))
button2 = tk.Button(self, text=“Plants”,
command=lambda: controller.show_frame(“Plants”))
button3 = tk.Button(self, text=“Nail Polish”,
command=lambda: controller.show_frame(“Nail_Polish”))
button.pack(side=“top”, anchor=NE)
button1.pack(side=LEFT, anchor=NW, fill=BOTH, expand=1)
button2.pack(side=LEFT, anchor=NW, fill=BOTH, expand=1)
button3.pack(side=LEFT, anchor=NW, fill=BOTH, expand=1)
“”“
button1.pack(side=TOP, anchor=NW, padx=10, pady=60, expand=NO)
button2.pack(side=TOP, anchor=NW, padx=30, pady=60, expand=NO)
button3.pack(side=TOP, anchor=NW, padx=60, pady=60, expand=NO)
”“”
class Mail(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
Mail.configure(self, background=’#ade5ad’)
label = tk.Label(self, text=“Mail”, background=’#ade5ad’, font=TITLE_FONT)
label.pack(side=“top”, fill=“x”, pady=10)
button = tk.Button(self, text=“Back to Home”,
command=lambda: controller.show_frame(“Home”))
button.pack(side=“top”, anchor=NE)
if __name__ == “__main__”:
app = App()
app.minsize(300,300)
app.geometry(“800x800”)
app.mainloop()
I built the below program to demonstrate to you how the .pack() method works, please feel free to play around with the different options and see how each affects the output:
from tkinter import *
root = Tk()
top = Toplevel()
top.withdraw()
var1 = StringVar(root)
var1.set("top")
var2 = StringVar(root)
var2.set("none")
var4 = StringVar(root)
var4.set("center")
var3 = BooleanVar(root)
def command(top, var1, var3, var2):
top.destroy()
top = Toplevel()
top.geometry("500x500")
Label(top, text="Welcome home").pack()
Button(top, text="Button1").pack(side=var1.get(), fill=var2.get(), expand=var3.get(), anchor=var4.get())
Button(top, text="Button2").pack(side=var1.get(), fill=var2.get(), expand=var3.get(), anchor=var4.get())
Button(top, text="Button3").pack(side=var1.get(), fill=var2.get(), expand=var3.get(), anchor=var4.get())
Button(top, text="Button4").pack(side=var1.get(), fill=var2.get(), expand=var3.get(), anchor=var4.get())
option1 = OptionMenu(root, var1, "top", "left", "bottom", "right")
check1 = Checkbutton(root, variable=var3, text="Expand?")
option2 = OptionMenu(root, var2, "none", "x", "y", "both")
option3 = OptionMenu(root, var4, "center", "n", "ne", "e", "se", "s", "sw", "w", "nw")
button1 = Button(root, text="Render", command=lambda:command(top, var1, var3, var2))
option1.pack()
check1.pack()
option2.pack()
option3.pack()
button1.pack()
root.mainloop()
This should show you how the different options affect the results of the .pack().
More to the point I believe the effect you are looking for can be achieved using .pack(side="left", expand="true", fill="x", anchor="n").

Calling Tkinter frame controller from function rather then button command

So I have the following, which works perfectly:
import tkinter as tk
class App(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 (LoginPage, ProjPage):
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, rowspan=12, columnspan=6, sticky="nsew")
self.show_frame(LoginPage)
def show_frame(self, c):
frame = self.frames[c]
frame.tkraise()
class LoginPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
Btn = tk.Button(self, text="Sign In", command=lambda: controller.show_frame(ProjPage))
But I want that last button command to be in a separate function, so I can do some evaluations first:
Btn = tk.Button(self, text="Sign In", command=self.signIn)
def signIn(self):
# do some stuff here
self.controller.show_frame(ProjPage)
This doesn't work; regardless if I try to pass the controller, or use a lambda, nothing seems to work >.<
What am I not getting?
You don't seem to initialize controller in self. Put it there in __init__ of LoginPage, like so:
self.controller = controller
my program has a page(main page) that has 5 radio button in it and a button "ok",and I have 5 other Frame. I want my program to go to these frames after clicking the "ok" ( based on the chosen radio button).
when the "ok" is clicked it will call a lambda and get the value of chosen radiobutton and based on this valuefind the string (veg) which represent the name of the page.
here is the code:
import tkinter as tk
from tkinter import ttk
from win32print import StartPage
class KBSapp(tk.Tk):
def init(self, *args, **kwargs):
tk.Tk.init(self, *args, **kwargs)
tk.Tk.iconbitmap(self,default="icon.ico")
tk.Tk.wm_title(self, "Diseases and pests of vegetable crops")
container = tk.Frame(self, width=200, height=200, bg='black')
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,carrot,celery, potato, wheat, bean):
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)
label = tk.Label(self, width=0, height=20)
label.pack()
button2 = ttk.Button(self, command=lambda : okclick(v) ,text='OK', width=25)
button2.pack( )
v = tk.IntVar( )
self.option1 = ttk.Radiobutton(self, text="Carrot", variable=v, value=1);self.option1.pack( )
self.option2 = ttk.Radiobutton(self, text="Celery", variable=v, value=2);self.option2.pack( )
self.option3 = ttk.Radiobutton(self, text="potato", variable=v, value=3);self.option3.pack( )
self.option4 = ttk.Radiobutton(self, text="wheat", variable=v, value=4);self.option4.pack( )
self.option5 = ttk.Radiobutton(self, text="bean", variable=v, value=5);self.option5.pack( )
v.set(1) # initializing the choice
def okclick(v):
global veg
input1=v.get( )
if input1==1:
veg="carrot"
if input1==2:
veg='celery'
if input1==3:
veg='potato'
if input1==4:
veg='wheat'
if input1==5:
veg='bean'
print(veg)
class carrot(tk.Frame):
def init(self, parent, controller):
tk.Frame.init(self, parent)
label = tk.Label(self, width=0, height=20)
label.pack( )
button3 = ttk.Button(self, command=lambda : controller.show_frame(celery) , text='celery', width=25)
button3.pack( )
class celery(tk.Frame):
def init(self, parent, controller):
tk.Frame.init(self, parent)
label = tk.Label(self, width=0, height=20)
label.pack( )
button4 = ttk.Button(self, command=lambda : controller.show_frame(potato) , text='potato', width=25)
button4.pack( )
class potato(tk.Frame):
def init(self, parent, controller):
tk.Frame.init(self, parent)
label = tk.Label(self, width=0, height=20)
label.pack( )
button4 = ttk.Button(self, command=lambda : controller.show_frame(wheat) , text='wheat', width=25)
button4.pack( )
class wheat(tk.Frame):
def init(self, parent, controller):
tk.Frame.init(self, parent)
label = tk.Label(self, width=0, height=20)
label.pack( )
button4 = ttk.Button(self, command=lambda : controller.show_frame(bean) , text='bean', width=25)
button4.pack( )
class bean(tk.Frame):
def init(self, parent, controller):
tk.Frame.init(self, parent)
label = tk.Label(self, width=0, height=20)
label.pack( )
button4 = ttk.Button(self, command=lambda : controller.show_frame(StartPage) , text='StartPage', width=25)
button4.pack( )
app = KBSapp( )
app.mainloop( )

Categories