Tkinter Switching between multiple frames with 2 buttons - python

I am new to Python and tk and trying to learn by creating a application. In this I want to have one window with 5 frames stacked on top of each other and two buttons called "Next" and "Back".
When opening the window, frame_1 should be displayed and when I press "Next" frame_2 gets displayed. Pressing "Next" a second time raises frame_3 and so one. Do I press "Back" the previous frame should be displayed again.
What I got working so far is the change between two frames back and forth:
from tkinter import *
test = Tk()
def but_next_click():
frame_2.tkraise()
def but_back_click():
frame_1.tkraise()
test.geometry("300x300")
frame_1 = LabelFrame(test, text="frame_1", bg="blue4")
frame_2 = LabelFrame(test, text="frame_2", bg="yellow4")
frame_3 = LabelFrame(test, text="frame_3", bg="green4")
frame_4 = LabelFrame(test, text="frame_4", bg="red4")
but_next = Button(test, text="Next", width=5, height=1, pady=2,
command=but_next_click)
but_back = Button(test, text="Back", width=5, height=1, pady=2,
command=but_back_click)
frame_1.place(relx=0.5, rely=0.2, relwidth=0.9, relheight=0.9, anchor='n')
frame_2.place(relx=0.5, rely=0.2, relwidth=0.9, relheight=0.9, anchor='n')
frame_3.place(relx=0.5, rely=0.2, relwidth=0.9, relheight=0.9, anchor='n')
frame_4.place(relx=0.5, rely=0.2, relwidth=0.9, relheight=0.9, anchor='n')
but_next.place(relx=0.7, rely=0.05, anchor='n')
but_back.place(relx=0.3, rely=0.05, anchor='n')
frame_1.tkraise()
test.mainloop()
However now I am trying to kind of safe the "page_number". So what I tried to do, was to have a global variable called "pagenumber" and store the return value of the but-next-click() or but-back-click() functions inside it. But at this point I cant get any further because the functions and variables don't work they way I imagined it (From working a bit with VBA). I think I am missing some basic understanding of how the functions and variables work with each other.
from tkinter import *
page_number = 0
test = Tk()
test.geometry("300x300")
frame_1 = LabelFrame(test, text="frame_1", bg="blue4")
frame_2 = LabelFrame(test, text="frame_2", bg="yellow4")
frame_3 = LabelFrame(test, text="frame_3", bg="green4")
frame_4 = LabelFrame(test, text="frame_4", bg="red4")
but_next = Button(test, text="Next", width=5, height=1, pady=2,
command=lambda: but_next_click(page_number))
but_back = Button(test, text="Back", width=5, height=1, pady=2,
command=lambda: but_back_click(page_number))
def but_next_click(page):
print(f'Button Next Start - Page is {page}')
if page == 0:
frame_1.tkraise()
page = page + 1
if page == 1:
frame_2.tkraise()
page = page + 1
if page == 2:
frame_3.tkraise()
page = page + 1
print(f'Button Next END - Page is {page}')
return page
def but_back_click(page):
print(f'Button Back Start - Page is {page}')
if page == 1:
frame_1.tkraise()
page = page - 1
if page == 2:
frame_2.tkraise()
page = page - 1
if page == 3:
frame_3.tkraise()
page = page - 1
print(f'Button Back End - Page is {page}')
return page
page_number = but_next_click(page_number) or but_back_click(page_number)
# thats how I would store the output of a function. But this also executes the functions.
# Which I dont want. I only want to store the page value and use with the next button click
frame_1.place(relx=0.5, rely=0.2, relwidth=0.9, relheight=0.9, anchor='n')
frame_2.place(relx=0.5, rely=0.2, relwidth=0.9, relheight=0.9, anchor='n')
frame_3.place(relx=0.5, rely=0.2, relwidth=0.9, relheight=0.9, anchor='n')
frame_4.place(relx=0.5, rely=0.2, relwidth=0.9, relheight=0.9, anchor='n')
but_next.place(relx=0.7, rely=0.05, anchor='n')
but_back.place(relx=0.3, rely=0.05, anchor='n')
frame_1.tkraise()
test.mainloop()
I tried to understand the input and output of the function. What I don't understand is the Run output without clicking a button:
Button Next Start - Page is 0
Button Next END - Page is 3 (*1)
What I would expect is: The program checks which value page_number has and then using the first "if". But I don't understand, why it iterates through all the if´s leading to the output of 3 when I run the program. (*1)
But at least the value gets stored so that but_back_click can work with it. But somehow the output value then gets not stored.
Button Back Start - Page is 3
Button Back End - Page is 2
Button Back Start - Page is 3
Button Back End - Page is 2
What can I try next?

I am going to suggest an alternative strategy. Instead of using a variable that keeps track of the current page number I would suggest creating a list containing each of your frames that you can iterate through, and storing it as well as the current top frame in a dictionary.
Then when either the back or forward button is pressed it can iterate through the list containing the frames and check if each one is the top frame. When it finds the current top frame it can then determine which frame to raise next based on it's position in the list. This avoids needing an if statement for each and every frame and it will work equally for any number of frames you end up needing to create.
It also has the benefit of not needing to pass anything to the button callbacks, or the use of a lambda in the buttons command parameter.
For example:
from tkinter import *
test = Tk()
test.geometry("300x300")
frame_1 = LabelFrame(test, text="frame_1", bg="blue4")
frame_2 = LabelFrame(test, text="frame_2", bg="yellow4")
frame_3 = LabelFrame(test, text="frame_3", bg="green4")
frame_4 = LabelFrame(test, text="frame_4", bg="red4")
frame_info = {
"top": frame_1, # start with frame_1 on top
"frames": [frame_1, frame_2, frame_3, frame_4]
}
def get_frame_index():
"""Iterate list of frames to find which one is on top."""
for i, frame in enumerate(frame_info["frames"]):
if frame == frame_info["top"]:
return i
def but_next_click():
"""Determine next frame based on it's position in the list."""
frames = frame_info["frames"]
index = get_frame_index()
if index == len(frames) - 1:
next_frame = frames[0]
else:
next_frame = frames[index+1]
next_frame.tkraise() # raise the next frame
frame_info["top"] = next_frame # assign the next frame to the "top" frame in dictionary.
def but_back_click():
frames = frame_info["frames"]
index = get_frame_index()
if index == 0:
next_frame = frames[-1]
else:
next_frame = frames[index-1]
next_frame.tkraise()
frame_info["top"] = next_frame
but_next = Button(test, text="Next", width=5, height=1, pady=2,
command=but_next_click)
but_back = Button(test, text="Back", width=5, height=1, pady=2,
command=but_back_click)
frame_1.place(relx=0.5, rely=0.2, relwidth=0.9, relheight=0.9, anchor='n')
frame_2.place(relx=0.5, rely=0.2, relwidth=0.9, relheight=0.9, anchor='n')
frame_3.place(relx=0.5, rely=0.2, relwidth=0.9, relheight=0.9, anchor='n')
frame_4.place(relx=0.5, rely=0.2, relwidth=0.9, relheight=0.9, anchor='n')
but_next.place(relx=0.7, rely=0.05, anchor='n')
but_back.place(relx=0.3, rely=0.05, anchor='n')
frame_1.tkraise()
test.mainloop()

Just in case other newbies having a similiar problem, the following also works. But to clearify this answer: I just post it to get feedback from the experts, wether this is working but just a crutch or actually a usable solution.
So what I found is, that I had to add "global" to both functions. This way but_back_click() and but_next_click() can read and write it.
def but_next_click():
global page_number
print(f'Button Next Start - Page is {page_number}')
if page_number <= 2: #this just prevents overcounting, when the button is clicked too many times
if page_number == 0:
frame_2.tkraise()
elif page_number == 1:
frame_3.tkraise()
elif page_number == 2:
frame_4.tkraise()
page_number = page_number + 1
print(f'Button Next END - Page is {page_number}')
return

Different way, work with classes
Create Ui object and do all the stuff in this object. Create screens and add them to
a list. Later you can change the current index position. A manage method tracks the current index and pack the frame on window.
Maybe it will help you.
import tkinter as tk
from tkinter import ttk
class Ui:
def __init__(self):
self.frame_obj_array=[]
self.create_screens(5)
self.activescreen_index=0
self.last_activescreen_index=1
root.after(12,self.update)
def create_screens(self,n):
for i in range(n):
frame=tk.Frame(root)
btn_back=ttk.Button(frame,text='back',command=self.back)
btn_next=ttk.Button(frame,text='next',command=self.next)
lbl=tk.Label(frame,text=f'Frame: {str(i)}!',width=100,font=('Railway',20))
btn_back.pack(side='left',anchor='sw',pady=40,padx=40)
btn_next.pack(side='right',anchor='se',pady=40,padx=40)
lbl.pack(side='top')
self.frame_obj_array.append(frame)
def back(self):
if not self.activescreen_index <= 0:
self.activescreen_index-=1
def next(self):
if self.activescreen_index < len(self.frame_obj_array)-1:
self.activescreen_index+=1
def manage_screens(self):
if self.activescreen_index != self.last_activescreen_index:
self.frame_obj_array[self.last_activescreen_index].pack_forget()
self.frame_obj_array[self.activescreen_index].pack(expand=True,fill='both')
self.last_activescreen_index=self.activescreen_index
def update(self):
self.manage_screens()
root.after(12,self.update)
if __name__ == 'main':
root=tk.Tk()
root.geometry('%dx%d+%d+%d' % (900,600, 0, 0))
app=Ui()
root.mainloop()

Related

How can I either ignore blank pages in a pdf using python or add blank pages to a location without changing the total amnt of pages until doc saved?

So I'm using the tkinter and pymupdf libraries to add blank pages to a desired location. This is done by pressing a button which inserts the blank page below the page on the button. My issue is that once it inserts the blank page, the original page order now changes.
When you press a button corresponding to a page number, it inserts the blank page, but if you try with a second blank page, it inserts it at the wrong place because it messes up the button's assigned page number. Please help I'm losing my hair.
import tkinter as tk
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
from tkinter.filedialog import asksaveasfilename
import fitz
btnClick = 0
def launchInsert():
global root
global buttonframe
root = tk.Tk()
root.title("Bla bla bla")
root.geometry("800x600")
#Displays "text" name as title of program
label = tk.Label(root, text ="Insert Blank Page", font=('Arial',18))
label.pack(padx=20, pady=20)
#File Explorer Button
buttonframe = tk.Frame(root, padx=100, pady=25)
btn1 = tk.Button(buttonframe,text="Browse...", font=('Arial',18), command=browse_file)
btn1.grid(row=1, column=6, padx=225, sticky=tk.W+tk.E)
buttonframe.pack(side="bottom")
def save_file():
f = asksaveasfilename(initialfile = 'untitled.pdf',
defaultextension=".pdf",filetype=[("All Files","*.*"),("PDF Files","*.pdf")])
pdf2.save(f)
# with open(file, "wb") as pdfCombined:
# newPdf.write(pdfCombined)
def blank(i):
#program is recognizing blank page as document original page then counting it as pagenumber
#try to just ignore blank pages
pdf2.new_page(pno=i, width=595, height=842)
global btnClick
btnClick = btnClick + 1
if btnClick == 1:
pdf2.new_page(pno=i, width=595, height=842)
elif btnClick > 1:
print("This is button click: ", btnClick)
i = i + 1
pdf2.new_page(pno=i, width=595, height=842)
for slices in range(len(pdf2)):
print("This is new page - ", slices)
print("This is pageCount after addition", slices)
print("The page was added successfully")
print("This is ", i)
def browse_file():
global filename
filename = filedialog.askopenfilename(title="Select a File", filetype=(("PDF Files","*.pdf"),("All Files","*.*")))
global pdf2, pageCount, i
pdf2 = fitz.open(filename)
# Create A Main Frame
main_frame = Frame(root)
main_frame.pack(fill=BOTH, expand=1)
# Create A Canvas
my_canvas = Canvas(main_frame)
my_canvas.pack(side=LEFT, fill=BOTH, expand=1)
# Add A Scrollbar To The Canvas
my_scrollbar = ttk.Scrollbar(main_frame, orient=VERTICAL, command=my_canvas.yview)
my_scrollbar.pack(side=RIGHT, fill=Y)
# Configure The Canvas
my_canvas.configure(yscrollcommand=my_scrollbar.set)
my_canvas.bind('<Configure>', lambda e: my_canvas.configure(scrollregion = my_canvas.bbox("all")))
# Create ANOTHER Frame INSIDE the Canvas
second_frame = Frame(my_canvas)
# Add that New frame To a Window In The Canvas
my_canvas.create_window((0,0), window=second_frame, anchor="nw")
btn2 = tk.Button(buttonframe,text="Save", font=('Arial',18), command=save_file)
btn2.grid(row=1, column=7, pady=20, sticky=tk.W+tk.E)
buttonframe.pack(side="bottom")
for i in range(len(pdf2)):
insClick = tk.Button(second_frame, text=f'Insert\nbelow {i}', padx= 50, command= lambda i=i: blank(i)).grid(row=i, column=5, pady=25, padx=50)
numShow = Label(second_frame, text=f"Page number {i}",padx=200).grid(row=i, column=1)
launchInsert()
mainloop()

Python tkinter navigation using grids

I am trying to navigate between two simple pages:-
Page 1:
root = tk.Tk()
root.minsize(230,300)
root.title("Page1")
label = tk.Label(root,text="File Path")
textBox = tk.Text(root,height=2,width=10)
textBox.config(state='disabled')
label.grid(row=0,column=0)
Page 2:
root = tk.Tk()
root.minsize(230,300)
root.title("Page2")
label = tk.Label(root,text="File Path")
textBox = tk.Text(root,height=2,width=10)
textBox.config(state='disabled')
label.grid(row=0,column=0)
I have searched for some solution but they involve hiding buttons using the pack methods which give me an error.
store the pages in a list and use grid_forget to hide the previous page and use page[index].grid to bring the next page.
In your case, you are switching between two Text Widgets so store those widgets in a list.
here is an example:
import tkinter as tk
def previousPage():
global index
if index > 0:
pages[index].grid_forget()
index -= 1
msg = index
pages[index].grid(row=1, column=1)
else:
msg = 'No more previous pages'
lbl.config(text=msg)
def nextPage():
global index
if index < len(pages)-1:
pages[index].grid_forget()
index += 1
msg = index
pages[index].grid(row=1, column=1)
else:
msg = 'Last Page Reached'
lbl.config(text=msg)
root = tk.Tk()
root.grid_columnconfigure((0, 1), weight=1)
root.grid_rowconfigure((0, 1, 2), weight=1)
index = 0
frame1 = tk.Frame(root)
tk.Label(frame1, text='Hello').pack()
tk.Text(frame1, state='disabled').pack()
frame2 = tk.Frame(root)
tk.Label(frame2, text='Welcome').pack()
tk.Entry(frame2).pack()
pages = [frame1, frame2]
pages[0].grid(row=1, column=1)
tk.Button(root, text='Next', command= nextPage).grid(row=2, column=2)
tk.Button(root, text='Previous', command= previousPage).grid(row=2, column=0)
lbl = tk.Label(root, text=f'Page: {index}')
lbl.grid(row=0, column=1)
root.mainloop()

Button on far right despite only being in 2nd (1) column

import random
from tkinter import *
root = Tk()
FirstPageFrame = Frame(root) # CREATES FIRST PAGE FRAME
FirstPageFrame.pack() # CREATES FIRST PAGE FRAME
RolltheDiceTitle = Label(FirstPageFrame, text="Roll the Dice")
RolltheDiceTitle.config(font=("Courier", 30))
RolltheDiceTitle.grid()
LoginRegisterWelcomeMessage = Label(FirstPageFrame, text="Welcome to the Roll the Dice Game.")
LoginRegisterWelcomeMessage.grid(row=1, padx=10, pady=10)
DiceImage = PhotoImage(file="dice.png")
DiceImageLabel = Label(FirstPageFrame, image=DiceImage)
DiceImageLabel.grid()
registerButton = Button(FirstPageFrame, text="Register", fg="orange") # CREATES REGISTER BUTTON
registerButton.grid(row=4, padx=10, pady=10)
loginButton = Button(FirstPageFrame, text="Login", fg="Green") # CREATES LOGIN BUTTON
loginButton.grid(row=4, column=1, padx=10, pady=10)
root.mainloop() # Continues tkinter window loop so program does not close
I'm trying to have both the register and login buttons in the middle of the window (where register button is located) but side by side, not stacked.
Apologies for any incorrect formatting with this question or any easy fixes with the code. I'm super new to Tkinter and trying to figure stuff out :)
When you put the Login button in column 1 all the other widgets are in column 0, so the Login button will be displayed on the far right.
One solution is to create a contaner frame for the buttons which can be placed in the center of column 0, and then place the buttons in culmns in that frame.
I have stated row and colun explicitly for all widgets which makes it easier to follow, and also assigned a bg color to the buttonFrame so you can see where it goes.
import random
from tkinter import *
root = Tk()
FirstPageFrame = Frame(root) # CREATES FIRST PAGE FRAME
FirstPageFrame.pack() # CREATES FIRST PAGE FRAME
RolltheDiceTitle = Label(FirstPageFrame, text="Roll the Dice")
RolltheDiceTitle.config(font=("Courier", 30))
RolltheDiceTitle.grid(row=0, column=0)
LoginRegisterWelcomeMessage = Label(FirstPageFrame, text="Welcome to the Roll the Dice Game.")
LoginRegisterWelcomeMessage.grid(row=1, column=0, padx=10, pady=10)
DiceImage = PhotoImage(file="dice.png")
DiceImageLabel = Label(FirstPageFrame, image=DiceImage)
DiceImageLabel.grid(row=2, column=0)
# Here is the container frame for the buttons.
buttonFrame = Frame(FirstPageFrame, bg='tan') # bg color to indicate
buttonFrame.grid(row=3) # position and extent of frame
registerButton = Button(buttonFrame, text="Register", fg="orange") # CREATES REGISTER BUTTON
registerButton.grid(row=0, column=0, padx=10, pady=10)
loginButton = Button(buttonFrame, text="Login", fg="Green") # CREATES LOGIN BUTTON
loginButton.grid(row=0, column=1, padx=10, pady=10)
root.mainloop() # Continues tkinter window loop so program does not close

GUI - hiding buttons

from tkinter import *
import tkinter as tk
class dashboard(Frame):
def __init__(self, master):
super(dashboard, self).__init__(master)
self.grid()
self.buttons()
def buttons(self):
#student dashboard button
bttn1 = Button(self, text = "Student",
command=self.student, height = 2, width= 15)
bttn1.grid()
#teacher dashboard button
bttn2 = Button(self, text = "Teacher", height = 2, width= 15)
bttn2.grid()
#exit button
bttn3 = Button(self, text = "Exit",
command=root.destroy, height = 2, width= 15)
bttn3.grid()
def student(self):
#view highscores button
bttn1 = Button(self, text = "Highscores", height = 2, width= 15)
bttn1.grid()
#print score button
bttn2 = Button(self, text = "Print Score", height = 2, width= 15)
bttn2.grid()
#exit button
bttn3 = Button(self, text = "Main Menu",
command=root.destroy, height = 2, width= 15)
bttn3.grid()
#main
root = Tk()
root.title("Dashboard")
root.geometry("300x170")
app = dashboard(root)
root.mainloop()
Wondered if someone could help me basically, with this GUI I am creating I want to be able to access a new page on the same frame but the buttons from the main menu stay once I go to another page, does anyone know how I can hide/forget the buttons and go back to them at a later stage? Thanks.
Updated to use sub-Frames
You could do it using the universal grid_remove() method (here's some documentation). One way to use it would be to keep references to each of the Button widgets created so you can call this method on them as needed.
However that can be simplified slightly—even though it takes about the same amount of code—by putting all the Buttonss for each page into a separate sub-Frame and just showing or hiding it which will automatically propagate do to all the widgets it contains. This approach also provides a better foundation for the rest of your program.
I've implemented this by adding a main_button_frame attribute to your class, as well as one named student_button_frame to hold those you have on the student page (since you'll probably need it to hide them too).
One nice thing about grid_remove() is that if you later call grid() on the same widget, it will remember all the settings it (and its sub-widgets) had before it was removed, so you don't need to create and maintain a list of every single one of them yourself.
Also note I also made some general modifications to your code so it conforms to the PEP 8 - Style Guide for Python Code recommendations better. I highly recommend you read and start following it.
from tkinter import *
import tkinter as tk
class Dashboard(Frame):
def __init__(self, master):
super().__init__(master)
self.grid()
self.main_button_frame = None
self.student_button_frame = None
self.create_main_buttons()
def create_main_buttons(self):
if self.student_button_frame: # Exists?
self.student_button_frame.grid_remove() # Make it invisible.
if self.main_button_frame: # Exists?
self.main_button_frame.grid() # Just make it visible.
else: # Otherwise create it.
button_frame = self.main_button_frame = Frame(self)
button_frame.grid()
# Student Dashboard button
bttn1 = Button(button_frame, text="Student",
command=self.create_student_buttons, height=2,
width=15)
bttn1.grid()
# Teacher Dashboard button
bttn2 = Button(button_frame, text="Teacher", height=2, width=15)
bttn2.grid()
# Dashboard Exit button
bttn3 = Button(button_frame, text="Exit", command=root.destroy,
height=2, width=15)
bttn3.grid()
def create_student_buttons(self):
if self.main_button_frame: # Exists?
self.main_button_frame.grid_remove() # Make it invisible.
if self.student_button_frame: # Exists?
student_button_frame.grid() # Just make it visible.
else: # Otherwise create it.
button_frame = self.student_button_frame = Frame(self)
button_frame.grid()
# Highscores button
bttn1 = Button(button_frame, text="Highscores", height=2, width=15)
bttn1.grid()
# Print Score button
bttn2 = Button(button_frame, text="Print Score", height=2, width=15)
bttn2.grid()
# Student Exit button
bttn3 = Button(button_frame, text="Exit", command=root.destroy,
height=2, width=15)
bttn3.grid()
# main
root = Tk()
root.title("Dashboard")
root.geometry("300x170")
app = Dashboard(root)
root.mainloop()

Tkinter Confirmation buttons and game GUI (splice(?))

Never used Tkinter before, and I'm not quite sure what to do with it or how it works. Windows IDLE Shell.
import time
from tkinter import *
input("Press enter to begin...")
print ("Welcome Traveller!")
time.sleep(1)
def name_identify():
print ()
global name_input
name_input = input ("What is your name? ").lower()
name_input = name_input.title()
time.sleep(0.75)
def name_confirm():
print ()
print ("So %s is your name then?" % name_input)
time.sleep(1.5)
print ()
confirmation = input ("Are you sure? Yes or No? ").lower()
if confirmation == "Yes" or confirmation == "yes" or confirmation == "aye" or confirmation == "yay":
print("")
print ("Then %s, let your adventure begin..." % name_input)
elif confirmation == "no" or confirmation == "No" or confirmation == "nay":
name_identify()
else:
print ("Please answer with either yes or no young traveller.")
time.sleep(2)
name_confirm()
name_confirm()
name_identify()
If possible I would like to put the game into a small GUI made with Tkinter just to make the mini text adventure tests I'm making easier to navigate when people play it. As such, I wish to turn the required "yes" and "no" responses needing to be typed into buttons, so the player doesn't need to touch the keyboard to finish. Problem is, I have no idea how to get all the data into the little TKinter interface along with the buttons working how I intend.
I can create the root which holds the buttons themselves, on a very basic level(likely not even correctly), but I do not know how to link parameters and variables to the buttons, nor how to place the text into the created console. All my attempts have simply ended with loops or the console simply not opening.
from tkinter import *
def main():
root = Tk()
root.title("Tkinter Test")
root.minsize(width=200, height=120)
root.maxsize(width=400, height=240)
button = Button(root, text="This is a button!", width=20, height=5)
button.pack()
root.mainloop()
if __name__ == '__main__':
main()
I thank whoever helps in advance. Even a template to work off would be great help, as I can just customise and modify until it suits my needs, but if someone would be so kind as to make a simple template for me based on the below image I would be grateful, as I would like it to follow a simple enough flow similar to that. And sorry if the image isn't clear enough. And maybe some advice on aligning said buttons and text, if it's possible for you.
The below code shows how you can achieve this and is commented to explain:
from tkinter import *
root = Tk() #declares that the main window belongs to root
frame = Frame(root) #creates a frame inside the main window so that we don't destroy the actual window when we refresh
def command1(frame):
frame.destroy() #destroys the frame and everything in it
frame = Frame(root) #new frame
label1 = Label(frame, text="What is your name?") #text label
entry1 = Entry(frame) #entry widget
button1 = Button(frame, text="Ok", command=lambda:command2(frame, entry1)) #continue button
frame.pack() #packs item
label1.pack() #packs item
entry1.pack() #packs item
button1.pack() #packs item
def command2(frame, entry1):
var = entry1.get() #gets the text entered in the last phase and stores it before the item is destroyed
frame.destroy() #destroys the frame and everything in it
frame = Frame(root) #new frame
label1 = Label(frame, text="So %s is your name then? Are you sure?" % var) #text label
button1 = Button(frame, text="Yes", command=lambda:command3(frame, var)) #yes button
button2 = Button(frame, text="No", command=lambda:command1(frame)) #no button
frame.pack() #packs item
label1.pack() #packs item
button1.pack() #packs item
button2.pack() #packs item
def command3(frame, var):
frame.destroy() #destroys the frame and everything in it
frame = Frame(root) #new frame
label1 = Label(frame, text="Then %s, let your adventure begin..." % var) #text label
frame.pack() #packs item
label1.pack() #packs item
label1 = Label(frame, text="Press below to begin...") #text label
button1 = Button(frame, text="Begin", command=lambda:command1(frame)) #begin button
frame.pack() #packs item
label1.pack() #packs item
button1.pack() #packs item
root.mainloop() #starts event loop
I would still recommend http://effbot.org/tkinterbook/ as a starting point for tkinter.
The below shows how you can align the two buttons next to each other, the code is commented to show where it varies from the original:
from tkinter import *
root = Tk()
frame = Frame(root)
def command1(frame):
frame.destroy()
frame = Frame(root)
label1 = Label(frame, text="What is your name?")
entry1 = Entry(frame)
button1 = Button(frame, text="Ok", command=lambda:command2(frame, entry1))
frame.pack()
label1.pack()
entry1.pack()
button1.pack()
def command2(frame, entry1):
var = entry1.get()
frame.destroy()
frame = Frame(root)
frame1 = Frame(frame) #creates lower frame
label1 = Label(frame, text="So %s is your name then? Are you sure?" % var)
button1 = Button(frame1, text="Yes", command=lambda:command3(frame, var)) #this button is now in the lower frame
button2 = Button(frame1, text="No", command=lambda:command1(frame)) #this button is now in the lower frame
frame.pack()
frame1.pack(side="bottom") #packs lower frame
label1.pack()
button1.pack(side="left") #packs button left
button2.pack(side="right") #packs button right
def command3(frame, var):
frame.destroy()
frame = Frame(root)
frame1 = Frame(frame)
label1 = Label(frame, text="Then %s, let your adventure begin..." % var)
frame.pack()
label1.pack()
label1 = Label(frame, text="Press below to begin...")
button1 = Button(frame, text="Begin", command=lambda:command1(frame))
frame.pack()
label1.pack()
button1.pack()
root.mainloop()

Categories

Resources