Why can I not get the value of tkinter variables? - python-3.x

I am trying to add a configuration window in my coupled oscillator simulation. But when I want to get the value of tkinter variables to set up the system, I only get ''.
I tried to change the type from tk.DoubleVar() to tk.StringVar() but nothing seems to works...
Here the code for the configuration frame for one object. Then I create two of them and add them to the configuration frame.
import tkinter as tk
class MassConfig(tk.Frame):
def __init__(self, root, **kwargs):
tk.Frame.__init__(self, root, kwargs)
self.grid()
# Variables :
self.weight = tk.StringVar()
self.vitesse = tk.StringVar()
self.position = tk.StringVar()
self.lbl_weight = tk.Label(self, text='Masse :')
self.lbl_weight.grid(row=0, column=0)
self.entry_weight = tk.Entry(self, textvariable=self.weight, width=5)
self.entry_weight.grid(row=0, column=1)
self.lbl_vit = tk.Label(self, text='Vitesse :')
self.lbl_vit.grid(row=1, column=0, pady=5)
self.entry_vit = tk.Entry(self, textvariable=self.vitesse, width=5)
self.entry_vit.grid(row=1, column=1)
self.lbl_pos = tk.Label(self, text='Position :')
self.lbl_pos.grid(row=2, column=0)
self.entry_pos = tk.Entry(self, textvariable=self.position, width=5)
self.entry_pos.grid(row=2, column=1)
Here the code of the configuration frame, which has two 'MassConfig' frame inside.
import tkinter as tk
from gui.masse_config import MassConfig
class Configuration(tk.Frame):
def __init__(self, root, **kwargs):
tk.Frame.__init__(self, root, **kwargs)
self.root = root
self.grid()
self.update()
self.is_alive = True
self.data = {}
self.m1_frame = tk.LabelFrame(self, text='Masse 1', width=200, height=200)
self.m1_frame.grid(column=0, row=0, padx=(10, 5), pady=(10, 10))
self.m2_frame = tk.LabelFrame(self, text='Masse 2', width=200, height=200)
self.m2_frame.grid(column=1, row=0, padx=(5, 10), pady=(10, 10))
self.config_1 = MassConfig(self.m1_frame)
self.config_2 = MassConfig(self.m2_frame)
self.config_1.grid(padx=10, pady=10)
self.config_2.grid(padx=10, pady=10)
self.btn_validation = tk.Button(self, text='Valider', command=self.validation)
self.btn_validation.grid(row=3, column=1, padx=10, pady=(0, 10), sticky=tk.E)
self.update()
def validation(self):
print(":", self.config_1.position.get())
self.data['Mass 1'] = {}
self.data['Mass 1']['Position'] = self.config_1.position.get()
self.data['Mass 1']['Vitesse'] = self.config_1.vitesse.get()
self.data['Mass 1']['Masse'] = self.config_1.weight.get()
self.data['Mass 2'] = {}
self.data['Mass 2']['Position'] = self.config_2.position.get()
self.data['Mass 2']['Vitesse'] = self.config_2.vitesse.get()
self.data['Mass 2']['Masse'] = self.config_2.weight.get()
self.is_alive = False
self.root.destroy()
I want to have the value of the tkinter variables self.weight, self.vitesse and self.position from the MassConfig class in a dictionary (self.data from Configuration class). But nothing come out, except ''.

Related

Is it possible to grab input from the topview tkinter window and retrieve saved entry field value from within master tk window

The program is made up of classes and I am trying to use a tkinter topview from within a function so that when it's called it is able to retrieve the entryfield value to the master class
from tkinter import
from PIL import Image, ImageTk
Below is the driver code handling the transitioning from one class to another
class SeaofBTCapp(Tk):
def __init__(self, *args, **kwargs):
Tk.__init__(self, *args, **kwargs)
container = 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 (
WelcomePage, Register_new_user): # ,PageThree,PageFour):
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(WelcomePage)
# def show_frame(self, cont):
# frame = self.frames[cont]
# frame.tkraise()
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
frame.update()
frame.event_generate("<<show_frame>>")
def get_page(self, cont):
for page in self.frames.values():
if str(page.__class__.__name__) == cont:
return page
return None
class Register_new_user(object):
pass
Below is the entry point of the program and is the first page to be displayed
class WelcomePage(Frame):
def __init__(self, parent, controller):
Frame.__init__(self, parent)
# self.bind("<<show_frame>>", self.main_prog)
def resize_image(event):
global photo
new_width = event.width
new_height = event.height
image = copy_of_image.resize((new_width, new_height))
photo = ImageTk.PhotoImage(image)
label.config(image=photo)
label.image = photo # avoid garbage collection
def pin_input():
top = Toplevel()
top.geometry("180x100")
top.title("toplevel")
l2 = Label(top, text="This is toplevel window")
global entry_1
global password
password = StringVar
entry_1 = None
def cleartxtfield():
global password
new = "3"
password.set(new)
# ############# Function to parse for only numerical input
def validate(input):
if input.isdigit():
return True
elif input == "":
return True
else:
return False
def enternumber(x):
global entry_1
setval = StringVar()
setval = str(x)
# print(setval)
entry_1.insert(END, setval)
entry_1 = Entry(top, textvariable=password, width=64, show='*')
entry_1.place(x=200, y=100)
entry_1.focus()
reg = top.register(validate)
entry_1.config(validate="key", validatecommand=(reg, '%P'))
def getcreds():
# check if four digit entered and is not empty
global passwd
passwd = password.get()
print(f"The Credentials are {passwd}")
def funcbackspace():
length = len(entry_1.get())
entry_1.delete(length - 1, 'end')
def killwindow():
# when the user quits it should clear all the data input fields filled in in the previous steps. and should display information that it is about to quit in a few seconds
command = top.destroy()
# Label(top,text="Goodbye\n (Closing in 2 seconds)")
top.after(2000, top.quit())
cancel = Button(top, width=8, height=3, text="Cancel", bg="red", fg="black", command=killwindow)
cancel.place(x=220, y=150)
backspace = Button(top, width=8, height=3, text="Backspace", bg="red", fg="black", command=funcbackspace)
backspace.place(x=500, y=150)
# ----number Buttons------
def enternumber(x):
global entry_1
setval = StringVar()
setval = str(x)
# print(setval)
entry_1.insert(END, setval)
btn_numbers = []
for i in range(10):
btn_numbers.append(
Button(top, width=8, height=3, text=str(i), bd=6, command=lambda x=i: enternumber(x)))
btn_text = 1
for i in range(0, 3):
for j in range(0, 3):
btn_numbers[btn_text].place(x=220 + j * 140, y=250 + i * 100)
btn_text += 1
btn_zero = Button(top, width=15, height=2, text='0', bd=5, command=lambda x=0: enternumber(x))
btn_zero.place(x=330, y=550)
clear = Button(top, text="Clear", bg="green", fg="white", width=8, height=3, command=cleartxtfield)
clear.place(x=220, y=550)
okbtn = Button(top, text="Enter", bg="green", fg="black", width=8, height=3, command=getcreds)
okbtn.place(x=500, y=550)
val = getcreds()
print("The value to be returned is %s" % val)
return val
password = pin_input()
print("Gotten password is %s" % password)
copy_of_image = Image.open("image.png")
photoimage = ImageTk.PhotoImage(copy_of_image)
label = Label(self, image=photoimage)
label.place(x=0, y=0, relwidth=1, relheight=1)
label.bind('<Configure>', resize_image)
top_left_frame = Frame(self, relief='groove', borderwidth=2)
top_left_frame.place(relx=1, rely=0.1, anchor=NE)
center_frame = Frame(self, relief='raised', borderwidth=2)
center_frame.place(relx=0.5, rely=0.75, anchor=CENTER)
Button(top_left_frame, text='REGISTER', bg='grey', width=14, height=1,
command=lambda: controller.show_frame(Register_new_user)).pack()
Button(center_frame, text='ENTER', fg='white', bg='green', width=13, height=2,
command=lambda: controller.show_frame(Register_new_user)).pack()
if __name__ == '__main__':
app = SeaofBTCapp()
app.title("Password return on topview window")
width = 1000
height = 700
screenwidth = app.winfo_screenwidth()
screenheight = app.winfo_screenheight()
alignstr = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)
app.geometry(alignstr)
# app.resizable(width=False, height=False)
app.resizable(width=True, height=True)
app.mainloop()
If I understand this correctly you want to enter a password in a dialog and then get the password from the dialog when you close it.
Have a look at Dialog Windows at effbot for a discussion about creating dialog windows.
Here is an example of how you can implement a simple dialog:
from tkinter import *
from tkinter import simpledialog
class MyDialog(simpledialog.Dialog):
def body(self, master):
'''create dialog body.
return widget that should have initial focus.
This method should be overridden, and is called
by the __init__ method.'''
Label(master, text='Value:').grid(row=0)
self.e1 = Entry(master)
self.e1.grid(row=0, column=1)
return self.e1 # initial focus
def apply(self):
'''process the data
This method is called automatically to process the data, *after*
the dialog is destroyed. By default, it does nothing.'''
value = self.e1.get()
self.result = value
def validate(self):
'''validate the data
This method is called automatically to validate the data before the
dialog is destroyed. By default, it always validates OK.'''
return 1 # override
def buttonbox(self):
'''add standard button box.
override if you do not want the standard buttons
'''
box = Frame(self)
w = Button(box, text="OK", width=10, command=self.ok, default='active')
w.pack(side='left', padx=5, pady=5)
w = Button(box, text="Cancel", width=10, command=self.cancel)
w.pack(side='left', padx=5, pady=5)
self.bind("<Return>", self.ok)
self.bind("<Escape>", self.cancel)
box.pack()
if __name__ == '__main__':
root = Tk()
root.geometry('200x100+800+50')
def do():
d = MyDialog(root)
print(d.result)
b = Button(root, text='Go!', width=10, command=do)
b.pack(expand=True)
Did that answer your question?

Tkinter Image not Displaying when rendering class objects with multiple frames

I've created a desktop application using Tkinter in python3. There is a main class object 'Stack' for the application and within it is a function to render multiple frames for navigation to other windows within the app on a button click event.
I'm trying to display an image on the 'HomePage' screen (and actually all pages as a heading) using PIL.ImageTk/PIL.Image. Every time I run the app from terminal (macOS), the desktop app runs but the image does not appear. What am I doing wrong? Here is my code:
import getpass
import tkinter as tk
from tkinter import ttk
from PIL import ImageTk, Image
LARGE_FONT = ('Source Code Pro', 24)
class Stack(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 (HomePage, NdA):
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky='news')
self.show_frame(HomePage)
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
class HomePage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
username = getpass.getuser()
logo_path = 'myfilepath'.format(username)
img = ImageTk.PhotoImage(Image.open(logo_path+'myimage.png').resize((120,120)))
l = tk.Label(self, image=img)
l.grid(column=0, row=0, ipadx=10, ipady=5, sticky='w')
ttk.Label(
self,
text='Some Text',
wraplength=450,
justify=tk.LEFT
).grid(
column=1,
row=0,
ipady=10,
padx=(0,10),
sticky='nw')
tier1 = tk.Button(self, text='Button1', state=tk.DISABLED).grid(column=0, row=3, padx=10, columnspan=2, sticky='nesw')
tier2 = tk.Button(self, text='Button2', state=tk.DISABLED).grid(column=0, row=4, padx=10, columnspan=4, sticky='nesw')
tier3 = ttk.Button(self, text='Button3', command=lambda: controller.show_frame(Tier3))
tier3.grid(column=0, row=5, padx=10, columnspan=4, sticky='nesw')
nda = ttk.Button(self, text='Button4', command=lambda: controller.show_frame(NdA))
nda.grid(column=0, row=6, padx=10, pady=(0,10), columnspan=4, sticky='nesw')
class NdA(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
def clear_form():
effective_date.delete(0, END)
client_name.delete(0, END)
address.delete(0, END)
user_initials.delete(0, END)
def submit_data():
functions.create_nda(
date=effective_date.get(),
client_name=client_name.get(),
address=address.get(),
user=user_initials.get()
)
effective_date.delete(0, tk.END)
client_name.delete(0, tk.END)
address.delete(0, tk.END)
user_initials.delete(0, tk.END)
messagebox.showinfo('Heading Text', 'Message Text')
tk.Label(
self,
text='Some Text',
wraplength=450,
justify=tk.LEFT
).grid(
column=1,
row=0,
columnspan=3,
ipady=10,
padx=(0,10),
sticky='nw')
tk.Label(self, text='Label1').grid(column=0, row=2, pady=(20,10), columnspan=4, sticky='news')
tk.Label(self, text='Data1').grid(column=0, row=3, padx=(10,0), sticky='w')
client_name = tk.Entry(self, width=30)
client_name.grid(column=1, row=3, columnspan=3, padx=(0,10), sticky='news')
tk.Label(self, text='Data2').grid(column=0, row=5, padx=(10,0), sticky='w')
address = tk.Entry(self, width=30)
address.grid(column=1, row=5, columnspan=3, padx=(0,10), sticky='news')
tk.Label(self, text='Data3').grid(column=0, row=6, padx=(10,0), sticky='w')
effective_date = tk.Entry(self, width=30)
effective_date.insert(1, ' mm/dd/yyyy')
effective_date.grid(column=1, row=6, columnspan=3, padx=(0,10), sticky='news')
tk.Label(self, text='Data4').grid(column=0, row=7, padx=(10,0), sticky='w')
user_initials = tk.Entry(self, width=30)
user_initials.grid(column=1, row=7, columnspan=3, padx=(0,10), sticky='news')
create_tier3 = tk.Button(self, text='or click me', command=submit_data).grid(column=3, row=8, pady=(30,10), padx=(0,10), sticky='news')
clear_form = tk.Button(self, text='click me', command=clear_form).grid(column=2, row=8, pady=(30,10), padx=(5,5), sticky='news')
# return_home = tk.Button(self, text='HOME').grid(column=1, row=8, pady=(30,10), sticky='news')
app = Stack()
app.mainloop()
When the __init__() function in class HomePage exits the name img is garbage collected and so the label can't remember it. You need to save a reference to the image. The usual way is to save it as an attribute to the label:
l = tk.Label(self, image=img)
l.image = img # Save reference to image

Multiprocessing not working with progress bar in tkinter

I'm attempting to get the progress bar to run while a method is running. The problem is when I set the method "generatePi" into the class it won't run simultaneously; however, when I set the method "generatePi" outside of the class it works.
The code with method in class that I can get to work is:
from tkinter import (Tk, BOTH, Text, E, W, S, N, END,
NORMAL, DISABLED, StringVar)
from tkinter.ttk import Frame, Label, Button, Progressbar, Entry
from tkinter import scrolledtext
from multiprocessing import Process, Manager, Queue
from queue import Empty
from decimal import Decimal, getcontext
DELAY1 = 80
DELAY2 = 20
q = Queue()
class Example(Frame):
def __init__(self, parent):
Frame.__init__(self, parent, name="frame")
self.parent = parent
self.initUI()
def initUI(self):
self.parent.title("Pi computation")
self.pack(fill=BOTH, expand=True)
self.grid_columnconfigure(4, weight=1)
self.grid_rowconfigure(3, weight=1)
lbl1 = Label(self, text="Digits:")
lbl1.grid(row=0, column=0, sticky=E, padx=10, pady=10)
self.ent1 = Entry(self, width=10)
self.ent1.insert(END, "4000")
self.ent1.grid(row=0, column=1, sticky=W)
lbl2 = Label(self, text="Accuracy:")
lbl2.grid(row=0, column=2, sticky=E, padx=10, pady=10)
self.ent2 = Entry(self, width=10)
self.ent2.insert(END, "100")
self.ent2.grid(row=0, column=3, sticky=W)
self.startBtn = Button(self, text="Start",
command=self.onStart)
self.startBtn.grid(row=1, column=0, padx=10, pady=5, sticky=W)
self.pbar = Progressbar(self, mode='indeterminate')
self.pbar.grid(row=1, column=1, columnspan=3, sticky=W+E)
self.txt = scrolledtext.ScrolledText(self)
self.txt.grid(row=2, column=0, rowspan=4, padx=10, pady=5,
columnspan=5, sticky=E+W+S+N)
def onStart(self):
self.startBtn.config(state=DISABLED)
self.txt.delete("1.0", END)
digits = int(self.ent1.get())
accuracy = int(self.ent2.get())
self.p1 = Process(target=generatePi(q, digits, accuracy), args=())
self.p1.start()
self.pbar.start(DELAY2)
self.after(DELAY1, self.onGetValue)
def onGetValue(self):
if (self.p1.is_alive()):
self.after(DELAY1, self.onGetValue)
return
else:
try:
self.txt.insert('end', q.get(0))
self.txt.insert('end', "\n")
self.pbar.stop()
self.startBtn.config(state=NORMAL)
except Empty:
print("queue is empty")
def generatePi(q, digs, acc):
getcontext().prec = digs
pi = Decimal(0)
k = 0
n = acc
while k < n:
pi += (Decimal(1)/(16**k))*((Decimal(4)/(8*k+1)) - \
(Decimal(2)/(8*k+4)) - (Decimal(1)/(8*k+5))- \
(Decimal(1)/(8*k+6)))
k += 1
q.put(pi)
def main():
root = Tk()
root.geometry("400x350+300+300")
app = Example(root)
root.mainloop()
if __name__ == '__main__':
main()
The code with method outside class that I am unable to get to work:
from tkinter import (Tk, BOTH, Text, E, W, S, N, END,
NORMAL, DISABLED, StringVar)
from tkinter.ttk import Frame, Label, Button, Progressbar, Entry
from tkinter import scrolledtext
from multiprocessing import Process, Manager, Queue
from queue import Empty
from decimal import Decimal, getcontext
DELAY1 = 80
DELAY2 = 20
q = Queue()
class Example(Frame):
def __init__(self, parent):
Frame.__init__(self, parent, name="frame")
self.parent = parent
self.initUI()
def initUI(self):
self.parent.title("Pi computation")
self.pack(fill=BOTH, expand=True)
self.grid_columnconfigure(4, weight=1)
self.grid_rowconfigure(3, weight=1)
lbl1 = Label(self, text="Digits:")
lbl1.grid(row=0, column=0, sticky=E, padx=10, pady=10)
self.ent1 = Entry(self, width=10)
self.ent1.insert(END, "4000")
self.ent1.grid(row=0, column=1, sticky=W)
lbl2 = Label(self, text="Accuracy:")
lbl2.grid(row=0, column=2, sticky=E, padx=10, pady=10)
self.ent2 = Entry(self, width=10)
self.ent2.insert(END, "100")
self.ent2.grid(row=0, column=3, sticky=W)
self.startBtn = Button(self, text="Start",
command=self.onStart)
self.startBtn.grid(row=1, column=0, padx=10, pady=5, sticky=W)
self.pbar = Progressbar(self, mode='indeterminate')
self.pbar.grid(row=1, column=1, columnspan=3, sticky=W+E)
self.txt = scrolledtext.ScrolledText(self)
self.txt.grid(row=2, column=0, rowspan=4, padx=10, pady=5,
columnspan=5, sticky=E+W+S+N)
def onStart(self):
self.startBtn.config(state=DISABLED)
self.txt.delete("1.0", END)
digits = int(self.ent1.get())
accuracy = int(self.ent2.get())
self.p1 = Process(target=self.generatePi(q, digits, accuracy), args=())
self.p1.start()
self.pbar.start(DELAY2)
self.after(DELAY1, self.onGetValue)
def onGetValue(self):
if (self.p1.is_alive()):
self.after(DELAY1, self.onGetValue)
return
else:
try:
self.txt.insert('end', q.get(0))
self.txt.insert('end', "\n")
self.pbar.stop()
self.startBtn.config(state=NORMAL)
except Empty:
print("queue is empty")
def generatePi(self, q, digs, acc):
getcontext().prec = digs
pi = Decimal(0)
k = 0
n = acc
while k < n:
pi += (Decimal(1)/(16**k))*((Decimal(4)/(8*k+1)) - \
(Decimal(2)/(8*k+4)) - (Decimal(1)/(8*k+5))- \
(Decimal(1)/(8*k+6)))
k += 1
q.put(pi)
def main():
root = Tk()
root.geometry("400x350+300+300")
app = Example(root)
root.mainloop()
if __name__ == '__main__':
main()
With the change in code being:
self.p1 = Process(target=generatePi(q, digits, accuracy), args=())
To:
self.p1 = Process(target=self.generatePi(q, digits, accuracy), args=())
I got same problem when I try it I find windows system seems react late but in terminal it's actually running

How can I add an image to the tkinter start page class?

I am working on a simple Tkinter program to store data in excel the only problem that I have is that I am not sure how to add an image to the start page class to display to make the app look better. I would appreciate a little help. The only thing that has worked is to add the image at the end after the app object but I only want to display it on the start page.
from tkinter import ttk
from datetime import datetime
import tkinter as tk
import xlrd
from xlutils.copy import copy
import xlwt
from PIL import ImageTk, Image
style1 = xlwt.XFStyle()
style1.num_format_str = "D-MM-YY"
read_workbook = xlrd.open_workbook("test2.xls", formatting_info=True)
read_sheet = read_workbook.sheet_by_index(0)
workbook = copy(read_workbook)
sheet = workbook.get_sheet(0)
sheet.write(0, 0, datetime.now(), style1)
sheet.write(0, 1, "Item")
sheet.write(0, 2, "Size")
sheet.write(0, 3, "Color")
sheet.write(0, 4, "Quantity")
LARGE_FONT = ("Times New Roman", 16)
number = read_sheet.nrows
class App(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
tk.Tk.wm_title(self, "Ordering app")
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, Chair, Table):
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)
item_label = tk.Label(self, text="Select your item ")
item_label.grid(column=5, row=0)
chair_button1 = tk.Button(self, text="Chair",
command=lambda: controller.show_frame(Chair))
chair_button1.pack()
chair_button1.grid(column=0, row=3)
table_button = tk.Button(self, text="Table",
command= lambda: controller.show_frame(Table))
# table_button.pack()
table_button.grid(column=10, row=3)
class Chair(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
size_label = tk.Label(self, text="Enter the size")
size_label.grid(column=0, row=0)
self.size_entry = tk.Entry(self)
self.size_entry.grid(column=2, row=0)
color_label = tk.Label(self, text="Enter the color")
color_label.grid(column=0, row=1)
self.color_entry = tk.Entry(self)
self.color_entry.grid(column=2, row=1)
quantity_label = tk.Label(self, text="Enter the quantity")
quantity_label.grid(column=0, row=2)
self.quantity_entry = tk.Entry(self)
self.quantity_entry.grid(column=2, row=2)
done_button = tk.Button(self, text="Finish the order",
command=self.get_chair_data)
done_button.grid(column=1, row=4)
button1 = tk.Button(self, text="Back to Home",
command=lambda: controller.show_frame(StartPage))
button1.grid(column=1, row=5)
def get_chair_data (self):
global number
size = self.size_entry.get()
sheet.write(number, 1, "Chair")
sheet.write(number, 2, size)
color = self.color_entry.get()
sheet.write(number, 3, color)
quantity = int(self.quantity_entry.get())
sheet.write(number, 4, quantity)
number += 1
workbook.save("test2.xls")
class Table(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
size_label = tk.Label(self, text="Enter the size")
size_label.grid(column=0, row=0)
self.size_entry = tk.Entry(self)
self.size_entry.grid(column=2, row=0)
color_label = tk.Label(self, text="Enter the color")
color_label.grid(column=0, row=1)
self.color_entry = tk.Entry(self)
self.color_entry.grid(column=2, row=1)
quantity_label = tk.Label(self, text="Enter the quantity")
quantity_label.grid(column=0, row=2)
self.quantity_entry = tk.Entry(self)
self.quantity_entry.grid(column=2, row=2)
done_button = tk.Button(self, text="Finish the order",
command=self.get_table_data)
done_button.grid(column=1, row=4)
button2 = tk.Button(self, text="Back to Home",
command=lambda: controller.show_frame(StartPage))
button2.grid(column=1, row=5)
def get_table_data(self):
global number
size = self.size_entry.get()
sheet.write(number, 1, "Table")
sheet.write(number, 2, size)
color = self.color_entry.get()
sheet.write(number, 3, color)
quantity = int(self.quantity_entry.get())
sheet.write(number, 4, quantity)
number += 1
workbook.save("test2.xls")
app = App()
app.geometry("500x500")
app.mainloop()

Need help figuring out how to title the different pages in tkinter created differently without having the same title for all pages?

I am a beginner in programming in python and I have a question. With the code shown below, is it possible to give each class (which represent a different page) a different title and not a title to all the pages at once? I have looked everywhere and have been unable to find an answer. Thank you!
import tkinter as tk
# from tkinter import *
# Activate the line above when a message box is needed
class Start(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)
self.title("Application")
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (StartPage, PageOne):
# To add a new page, define the class below and then add the frame to the For Loop above
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(StartPage)
def show_frame(self, controller):
frame = self.frames[controller]
frame.tkraise()
def get_page(self, page_class):
return self.frames[page_class]
# This is the end of the baseline and the code for each page is below:
class StartPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
Name = StringVar()
Password = StringVar()
def show_credentials(event):
instructions = tk.Label(self, text="Credentials: ")
instructions.grid(row=5, column=3, sticky="E")
names = Name.get()
passwords = Password.get()
names = tk.Label(self, text=names, bg="red", fg="white")
passwords = tk.Label(self, text=passwords, bg="Red", fg="white")
names.grid(row=6, column=3, sticky="E")
passwords.grid(row=7, column=3, sticky="E")
credentials = tk.Button(self, text="Creds")
credentials.bind("<Button-1>", show_credentials)
credentials.grid(row=4, column=3, sticky="E")
def login(event):
controller.show_frame(PageOne)
log = tk.Button(self, text="Log In")
log.bind("<Button-1>", login)
log.grid(row=4, column=4, sticky="E")
# A class can be created to compare data entered to a list to identify the user and log him/her in
welcome = tk.Label(self, text="Welcome!")
welcome.grid(row=0, column=2, sticky="E")
username = tk.Label(self, text="Username: ")
username.grid(row=2, column=2, sticky='E')
password_label = tk.Label(self, text="Password: ")
password_label.grid(row=3, column=2, sticky="E")
username_entry = tk.Entry(self, textvariable=Name)
username_entry.grid(row=2, column=3, sticky="E")
password_entry = tk.Entry(self, textvariable=Password, show="*")
password_entry.grid(row=3, column=3, sticky="E")
cancel = tk.Button(self, text="Exit", command=quit)
cancel.grid(row=4, column=2, sticky="E")
class PageOne(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="This page is currently under Development")
label.grid(row=0, column=0, sticky="E")
switchpage1 = tk.Button(self, text="Back", command=lambda: controller.show_frame(StartPage))
switchpage1.grid(row=1, column=0, sticky="E")
root = Start()
root.mainloop()
Here is a way to title a different window:
import tkinter as tk
root = tk.Tk()
window1 = tk.Toplevel(root)
window1.wm_title("window 1")
root.mainloop()

Resources