Passing variables between frames in Tkinter 2.0? - python-3.x

Passing variables between frames in Tkinter
Followed the multiframe class example in:
from Switch between two frames in tkinter
by Bryan Oakley / Steven M. Vascellaro
Everything works fine within each frame, but trying to pass a Frame StartPage-entry text into the Frame PageTwo-scroll requires syntax in :
txtScroll(txt): ??????scroll.insert(tk.INSERT,scrolltxt)
I do not get.
BTW:
Tried following the original solution to:
Passing variables between frames in Tkinter
by adding
def __init__(self, master,controller, uploadPage=None):
self.controller = controller
self.uploadPage = PageTwo
To no avail ??????
# from https://stackoverflow.com/questions/7546050/switch-between-two-frames-in-tkinter
# by Bryan Oakley / Steven M. Vascellaro
import tkinter as tk # python 3
from tkinter import ttk, font as tkfont, scrolledtext # python 3
from tkinter.ttk import *
#definitions ----------------------
def txtClicked(txt):
res = "Entry text " + txt.get()
print(res)
def txtScroll(txt):
# Problem with output to scroll in different class ?
scroll.insert(tk.INSERT,scrolltxt)
def scrollInsert(scroll,scrolltxt):
scroll.insert(tk.INSERT,scrolltxt)
#Frame class ----------------------
class SampleApp(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self._frame = None
self.replace_frame(StartPage)
def replace_frame(self, frame_class):
"""Destroys current frame and replaces i with a new one."""
new_frame = frame_class(self)
if self._frame is not None:
self._frame.destroy()
self._frame = new_frame
self._frame.pack()
class StartPage(tk.Frame):
def __init__(self, master, uploadPage=None):
tk.Frame.__init__(self, master)
#self.controller = controller
self.uploadPage = PageTwo
tk.Label(self, text="This is the start page").pack(side="top", fill="x", pady=10)
# Entry
txt = Entry(self,width=10)
txt.pack(side="top", fill="x", pady=10)
btn = Button(self, text="Get Entry", command=lambda: txtClicked(txt)).pack()
btn = Button(self, text="Scroll Output", command=lambda: txtScroll(txt)).pack()
#-------------
tk.Button(self, text="Open page one", command=lambda: master.replace_frame(PageOne)).pack()
tk.Button(self, text="Open page two", command=lambda: master.replace_frame(PageTwo)).pack()
class PageOne(tk.Frame):
def __init__(self, master, uploadPage=None):
tk.Frame.__init__(self, master)
#self.controller = controller
self.uploadPage = PageTwo
tk.Label(self, text="This is page one").pack(side="top", fill="x", pady=10)
tk.Button(self, text="Return to start page", command=lambda: master.replace_frame(StartPage)).pack()
class PageTwo(tk.Frame):
def __init__(self, master, uploadPage=None):
tk.Frame.__init__(self, master)
#self.controller = controller
print ("tk.Frame: ", tk.Frame )
print ("self: ", self )
print ("master: ", master )
# scrolledtext
scroll = scrolledtext.ScrolledText(self,width=40,height=10)
scroll.pack(side="bottom", padx=10, pady=10)
scrolltxt = "Print scroll stuff..."
btn = Button(self, text="Print scroll", command=lambda: scrollInsert(scroll,scrolltxt)).pack()
#-------------
tk.Label(self, text="This is page two").pack(side="top", fill="x", pady=10)
tk.Button(self, text="Return to start page", command=lambda: master.replace_frame(StartPage)).pack()
#Tkinder Main ----------------------
if __name__ == "__main__":
app = SampleApp()
app.mainloop()

Related

Trouble Binding a Button in a Class - Python (Tkinter)

Just started learning Tkinter and was hoping someone could help me. I've been trying to bind a keyboard character (Enter button) to a tk button following this example and not getting anywhere.
Say I take the button (Enter) and try bind it nothing happens:
Enter.bind('<Return>', lambda:self.retrieve_Input(t))
If I bind to self instead using Lambda nothing happens also. I can get it to trigger if I remove the lambda but that's not the desired outcome
self.bind('<Return>', lambda:self.retrieve_Input(t))
My Code:
import sys
import tkinter as tk
from tkinter import ttk
class windows(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
self.wm_title("Test Application")
self.lift() #Bringing the GUI to the front of the screen
main_frame = tk.Frame(self, height=400, width=600) #Creating a main Frame for all pages
main_frame.pack(side="top", fill="both", expand=True)
main_frame.grid_rowconfigure(0, weight=1) #Configuring the location of the main frame using grid
main_frame.grid_columnconfigure(0, weight=1)
# We will now create a dictionary of frames
self.frames = {}
for F in (MainPage, CompletionScreen): #Add the page components to the dictionary.
page = F(main_frame, self)
self.frames[F] = page #The windows class acts as the root window for the frames.
page.grid(row=0, column=0, sticky="nsew")
self.show_page(MainPage) #Method to switch Pages
def show_page(self, cont):
frame = self.frames[cont]
frame.tkraise()
##########################################################################
class MainPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
#switch_window_button = tk.Button(self, text="Go to the Side Page", command=lambda: controller.show_page(SidePage))
#switch_window_button.pack(side="bottom", fill=tk.X)
tk.Label(self, text="Project Python Search Engine", bg='white').pack()
tk.Label(self, text="", bg='white').pack()
tk.Label(self, text="Song", bg='white').pack()
tk.Label(self, text="", bg='white').pack()
t = tk.Entry(self, bg='white', width = 50)
t.pack()
tk.Label(self, text="", bg='white').pack()
Enter = tk.Button(self, text='Search', command= lambda:self.retrieve_Input(t))
Enter.pack()
tk.Button(self, text="Latest Popular Songs", command=lambda:self.Popular_Songs(t)).pack() #Line 210 onwards
Enter.bind('<Return>', lambda:self.retrieve_Input(t))
def retrieve_Input(self, t):
print ("work")
print (t)
class CompletionScreen(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="Completion Screen, we did it!")
label.pack(padx=10, pady=10)
switch_window_button = ttk.Button(
self, text="Return to menu", command=lambda: controller.show_page(MainPage)
)
switch_window_button.pack(side="bottom", fill=tk.X)
if __name__ == "__main__":
App = windows()
App.mainloop()
I'm not really sure what I'm missing
Answer: The button probably doesn't have the keyboard focus. When I run your code and then use the keyboard to move the focus to the button, your binding works. You probably want to bind to the entry widget rather than the button since that's what will have the keyboard focus. – Thanks Bryan Oakley

Python Tkinter: How reset a combobox label from selecting option in another combobox in a parent, controler, container model?

The code is correct (and very interesting indeed - From stackoverlflow, because facilitate working comboboxes in classes!). The code is a little long, but just to create the structure to make combobox work in this parent, controler, container model. On the other hand,comoboboxes are "burning my brains out". The hard part: I can reset the lower combobox clicking the button. But I need to reset it to 'I´m your friend' just choosing any option in upper combobox (without use of button). I've tried insert "self.combobox_HPFilter.set('I´m your friend')" in a function and insert this in the functions called "make_guess", unfortunately unsuccessfuly. I really appreciate any help.
# from Bryan Oakley and others from the "amazing" Stackoverflow
# https://stackoverflow.com/questions/7546050/switch-between-two-frames-in-tkinter/7557028#7557028
import tkinter as tk # python 3
from tkinter import font as tkfont # python 3
from tkinter import ttk
class SampleApp(tk.Tk):
'''
All the code is working.The sole issue is: to reset second combobox text direct from options in upper combobox
'''
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):
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("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 make_guess01(self):
print("I've got a cute friend")
def make_guess02(self):
print('Ned is correct')
def make_guess03(self):
print('Patrick')
def make_guess04(self):
print('Best Hommer friend')
def labels_reset(self):
self.combobox_HPFilter.set('I´m your friend')
#-------------------------first combobox start
def change_Montage_combobox(self, event): # this method goes inside def montage_Combo(self):
myvar = (self.comboboxMontages.get())
# lines 1 2 3 4 say that values(function_name) in montageDict are functions in StartPage
function_name = self.montagesDict[myvar] #1 returns the function(method) in montageDic(value of key:value pair)
# just for reference: print(function_name)--> montage_Original (dictionary montagesDict value)
an_object = StartPage(self, tk.Frame) # 2--> the page (class) where function is
class_method = getattr(StartPage, function_name) # 3 returns method and says the page of the method
result = class_method(an_object) # 4 result is the method right for use
def montage_Combo(self):
self.montage_selector = tk.StringVar()
self.comboboxMontages = ttk.Combobox(self, values=sorted(list(self.montagesDict.keys())),
justify="center", textvariable=self.montage_selector, state="readonly",
)
self.comboboxMontages.bind('<<ComboboxSelected>>', lambda event: self.change_Montage_combobox(event))
self.comboboxMontages.pack()
self.comboboxMontages.set('Who is my friend')
#-------------------------first combobox end
#-------------------------second combobox start
def highPassFilter_Change_combobox(self, event): # this method goes inside def montage_Combo(self):
myvar = (self.combobox_HPFilter.get())
function_name = self.highPassFilterDict[myvar] # 1
an_object = StartPage(self, tk.Frame) # 2
class_method = getattr(StartPage, function_name) # 3
highPassFilter_result = class_method(an_object) # 4
def highPassFilter_Combo(self):
self.highPassFilter_selector = tk.StringVar()
self.combobox_HPFilter = ttk.Combobox(self, values=sorted(list(self.highPassFilterDict.keys())),
justify="center", textvariable=self.highPassFilter_selector,
state="readonly")
self.combobox_HPFilter.bind('<<ComboboxSelected>>', lambda event: self.highPassFilter_Change_combobox(event))
self.combobox_HPFilter.pack()
self.combobox_HPFilter.set('I´m your friend')
#-------------------------second combobox end
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
self.montagesDict = {'SpongeBob': 'make_guess01',
'Hommer': 'make_guess02'
}
self.highPassFilterDict = {'Patrick': 'make_guess03',
'Ned Flanders': 'make_guess04',
}
label = tk.Label(self, text="This is the start page", font=controller.title_font)
label.pack(side="top", fill="x", pady=10)
button1 = tk.Button(self, text="how reset lower combobox clicking upper combobox?",
command=self.labels_reset)
button1.pack()
self.montage_Combo()
self.highPassFilter_Combo()
#class PageOne just to make code play
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()
if __name__ == "__main__":
app = SampleApp()
app.mainloop()
Python is both challenging and exciting, it seems a zen Koan. After "lots of try an error" and frustration...comes the light.
import tkinter as tk # python 3
from tkinter import font as tkfont # python 3
from tkinter import ttk
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):
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("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 make_guess01(self):
print("I've got a cute friend")
def make_guess02(self):
print('Ned is correct')
def make_guess03(self):
print('Patrick')
def make_guess04(self):
print('Best Hommer friend')
def labels_reset(self):
self.combobox_HPFilter.set('I´m your friend')
#-------------------------first combobox start
def change_Montage_combobox(self, event): # this method goes inside def montage_Combo(self):
myvar = (self.comboboxMontages.get())
# lines 1 2 3 4 say that values(function_name) in montageDict are functions in StartPage
function_name = self.montagesDict[myvar] #1 returns the function(method) in montageDic(value of key:value pair)
# just for reference: print(function_name)--> montage_Original (dictionary montagesDict value)
an_object = StartPage(self, tk.Frame) # 2--> the page (class) where function is
class_method = getattr(StartPage, function_name) # 3 returns method and says the page of the method
result = class_method(an_object) # 4 result is the method right for use
#################################
# answer: #
#################################
if self.combobox_HPFilter != '':
self.labels_reset()
else:
pass
def montage_Combo(self):
self.montage_selector = tk.StringVar()
self.comboboxMontages = ttk.Combobox(self, values=sorted(list(self.montagesDict.keys())),
justify="center", textvariable=self.montage_selector, state="readonly",
)
self.comboboxMontages.bind('<<ComboboxSelected>>', lambda event: self.change_Montage_combobox(event))
self.comboboxMontages.pack()
self.comboboxMontages.set('Who is my friend')
#-------------------------first combobox end
#-------------------------second combobox start
def highPassFilter_Change_combobox(self, event): # this method goes inside def montage_Combo(self):
myvar = (self.combobox_HPFilter.get())
function_name = self.highPassFilterDict[myvar] # 1
an_object = StartPage(self, tk.Frame) # 2
class_method = getattr(StartPage, function_name) # 3
highPassFilter_result = class_method(an_object) # 4
def highPassFilter_Combo(self):
self.highPassFilter_selector = tk.StringVar()
self.combobox_HPFilter = ttk.Combobox(self, values=sorted(list(self.highPassFilterDict.keys())),
justify="center", textvariable=self.highPassFilter_selector,
state="readonly")
self.combobox_HPFilter.bind('<<ComboboxSelected>>', lambda event: self.highPassFilter_Change_combobox(event))
self.combobox_HPFilter.pack()
self.combobox_HPFilter.set('I´m your friend')
def all_ComboBox_labels_reset(self):
self.combobox_HPFilter.set('I´m your friend')
#-------------------------second combobox start
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
self.montagesDict = {'SpongeBob': 'make_guess01',
'Hommer': 'make_guess02'
}
self.highPassFilterDict = {'Patrick': 'make_guess03',
'Ned Flanders': 'make_guess04',
}
label = tk.Label(self, text="This is the start page")
label.pack(side="top", fill="x", pady=10)
button1 = tk.Button(self, text="how reset lower combobox clicking upper combobox?",
command=self.labels_reset)
button1.pack()
self.montage_Combo()
self.highPassFilter_Combo()
#class PageOne just to make code play
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")
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 used method self.combobox_HPFilter != '': because in my code there are multiple comboboxes to be reseted. "If" because at beginnig of script they are empty.
Excuse me I dont get the (-1)in my question, it is a question. It was usefull to me a beginner and no one answered until I found the answer. Indulge me and be more proactive explaining it. Best.

Tkinter objects are not centering

I am trying to create a simple Python 3.x GUI project with tkinter, just to learn the language better (I started learning Python not long ago), of which the only thing it does is switching between different pages as a button is clicked. The problem is that the objects are not getting in the center of the screen. What's wrong in my code?
Images:
Start Page
First Page
Second Page
import tkinter as tk
LARGE_FONT = ("verdana", 10)
class Application(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
container = tk.Frame(self)
container.grid()
self.frames = {}
for F in (StartPage, PageOne, PageTwo):
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="snew")
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)
label1 = tk.Label(self, text="Start Page", font=LARGE_FONT)
label1.grid(row=0, column=0)
button1 = tk.Button(self, text="Go to Page One",
command=lambda: controller.show_frame(PageOne))
button1.grid(row=1, column=0)
button2 = tk.Button(self, text="Go to Page Two",
command=lambda: controller.show_frame(PageTwo))
button2.grid(row=2, column=0)
class PageOne(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label2 = tk.Label(self, text="Page One", font=LARGE_FONT)
label2.grid(row=0, column=0, sticky="E")
button2 = tk.Button(self, text="Go to Page Two",
command=lambda: controller.show_frame(PageTwo))
button2.grid(row=1, column=0)
button3 = tk.Button(self, text="Go to Start Page",
command=lambda: controller.show_frame(StartPage))
button3.grid(row=2, column=0)
class PageTwo(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label2 = tk.Label(self, text="Page Two", font=LARGE_FONT)
label2.grid(row=0, column=0,sticky="E")
button2 = tk.Button(self, text="Go to Page One",
command=lambda: controller.show_frame(PageOne))
button2.grid(row=1, column=0)
button3 = tk.Button(self, text="Go to Start Page",
command=lambda: controller.show_frame(StartPage))
button3.grid(row=2, column=0)
app = Application()
app.title("Application")
app.mainloop()
I put a menu on the left with tkinter. Everything to the right of the menu is aligned in the middle. How to align to the right of the menu
There is a text on the back of the textbox, but because it is center-aligned, it crosses over the text and the text does not appear.
Tkinter program
All code:
from tkinter import *
from tkinter import messagebox
import tkinter.font as font
import tkinter as tkMessageBox
from typing import Sized
from PIL import ImageTk, Image
window = Tk()
window.title("Ogretmen+")
window.geometry("900x447")
window.configure(bg="#202020")
genelgorunumbaslik = font.Font(size=20)
menuyazilar = font.Font(size=20)
guncellemebuyuk = font.Font(size=15)
def sinifYonetimi():
sinifyonetimiaciklama.config(text="Sınıf yönetimi kısmına hoş geldiniz. Bu bölümden sınıf ekleyebilir ve silebilirsiniz. Örnek sınıf adı: 10 B")
sinifyonetimiaciklama.grid(row=1, column=2)
sinifadigir.config(text="Sınıf Adı:")
sinifadigir.grid(row=2, column=2)
sinifadientry.grid(row=2, column=2)
islemsec.grid_remove()
sinifyonetimiaciklama = Label(fg="white", bg="#202020")
sinifadigir = Label(fg="white", bg="#202020")
sinifadientry = Entry(bd=4)
menubuton2 = Button(text="Sınıf Yönetimi", fg="white", bg="#282528", height=3, command=sinifYonetimi)
menubuton3 = Button(text="Öğrenci Yönetimi", fg="white", bg="#282528", height=3)
menubuton4 = Button(text="Konu Takibi", fg="white", bg="#282528", height=3)
menubuton5 = Button(text="İletişim", fg="white", bg="#282528", height=2)
menubuton2['font'] = menuyazilar
menubuton3['font'] = menuyazilar
menubuton4['font'] = menuyazilar
menubuton5['font'] = menuyazilar
menubuton2.grid(row=1, column=1, sticky="ew")
menubuton3.grid(row=2, column=1, sticky="ew")
menubuton4.grid(row=3, column=1, sticky="ew")
menubuton5.grid(row=4, column=1, sticky="ew")
islemsec = Label(text="Lütfen sol menüden işlem seçiniz.", bg="#202020", fg="white")
islemsec.grid(row=1, column=3)
window.mainloop()

switch frame with tkinter

I use following code:
Switch between two frames in tkinter
import RPi.GPIO as GPIO
from threading import Timer,Thread,Event
import tkinter as tk # python 3
from tkinter import font as tkfont # python 3
#import Tkinter as tk # python 2
#import tkFont as tkfont # python 2
#----------------------------------------------------------
#Setup GPIO
#----------------------------------------------------------
GPIO.setwarnings(False)
# RPi.GPIO Layout verwenden (wie Pin-Nummern)
#GPIO.setmode(GPIO.BOARD)
GPIO.setmode(GPIO.BCM)
# (GPIO 17,27,22,5) auf Input setzen
chan_list1 = [17, 27, 22, 5]
GPIO.setup(chan_list1, GPIO.IN, pull_up_down=GPIO.PUD_UP)
# (GPIO 12,13,23,24) auf Output setzen
chan_list = [12, 13, 23, 24]
GPIO.setup(chan_list, GPIO.OUT)
#----------------------------------------------------------
#--------------------------------------------------------
#Timer
#--------------------------------------------------------
class perpetualTimer():
def __init__(self,t,hFunction):
self.t=t
self.hFunction = hFunction
self.thread = Timer(self.t,self.handle_function)
def handle_function(self):
self.hFunction()
self.thread = Timer(self.t,self.handle_function)
self.thread.start()
def start(self):
self.thread.start()
def cancel(self):
self.thread.cancel()
#--------------------------------------------------------
class SampleApp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
self.overrideredirect(1) #Remove Title bar
self.geometry("480x272") #Set the window dimensions
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="This is the start page", font=controller.title_font)
label.pack(side="top", fill="x", pady=10)
button1 = tk.Button(self, text="Go to Page One",
command=lambda: controller.show_frame("PageOne"))
button2 = tk.Button(self, text="Go to Page Two",
command=lambda: controller.show_frame("PageTwo"))
button1.pack()
button2.pack()
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()
def printer():
print ('PIT(!)')
SampleApp.show_frame('PageOne')
if __name__ == "__main__":
t = perpetualTimer(0.01,printer)
t.start()
app = SampleApp()
app.mainloop()
Is it possible to switch the frames without using buttons?
e.g. comparing a counter. if the counter value is 1 show page 1
if counter value is 2 show page 2 and so on.
If I'm honest, I do not remember exactly what I've all tried.
One thing I tried was "controller.show_frame("StartPage")" from def printer sub.
What I want to achieve is to switch the pages from the "def printer" sub,
which is called periodically.
I do not know if that's possible?
One thing I tried was controller.show_frame("StartPage") from def printer sub.
You have to call switch_frame on the object that has that method. This is no different than any other object or any other class in python.
In your case, since SampleApp is the class that has the method, and app is a global variable that holds an instance of the class, you would do it this way:
app.show_frame("StartPage")

how to switch from pack() to place() properly

i have my tkinter gui split in different classes and want to connect them in a home screen with buttons, like Steven M. Vascellaro did here: Switch between two frames in tkinter
import tkinter.ttk as ttk
#from alexa_site_2 import Frame_alexa
from globals import Globals
from tkinter import PhotoImage
import tkinter as tk
class SampleApp(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self._frame = None
self.geometry('{}x{}'.format(1024, 600))
self.configure(bg="white")
for i in range(len(Globals.image_files)):
image_box = PhotoImage(file=Globals.image_files[i])
Globals.list_images.append(image_box)
self.switch_frame(StartPage)
def switch_frame(self, frame_class):
"""Destroys current frame and replaces it with a new one."""
new_frame = frame_class(self)
if self._frame is not None:
self._frame.destroy()
self._frame = new_frame
self._frame.place(x=110,y=0)
print("switch frame function")
class StartPage(ttk.Frame):
def __init__(self, master):
ttk.Frame.__init__(self, master)
#self.place(x=0,y=0)
ttk.Label(self, text="This is the start page").pack()
ttk.Button(self, text="Open page one",
command=lambda: master.switch_frame(PageOne)).pack()
ttk.Button(self, text="Open page two",
command=lambda: master.switch_frame(PageTwo)).pack()
ttk.Button(self, text="Open page two",
command=lambda: master.switch_frame(Frame_alexa)).pack()
class PageOne(ttk.Frame):
def __init__(self, master):
ttk.Frame.__init__(self, master)
ttk.Label(self, text="This is page one").pack(side="top", fill="x", pady=10)
ttk.Button(self, text="Return to start page",
command=lambda: master.switch_frame(StartPage)).pack()
class PageTwo(ttk.Frame):
def __init__(self, master):
ttk.Frame.__init__(self, master)
ttk.Label(self, text="This is page two").place(x=40,y=10)
ttk.Button(self, text="Return to start page",
command=lambda: master.switch_frame(StartPage)).place(x=0,y=0)
if __name__ == "__main__":
app = SampleApp()
app.mainloop()
when I try connect my own classes i get a white window as result. You can see it working in pageOne and my problem in PageTwo. I am not planning on mixing place() and pack(). I just need place() and your help please.

Resources