I am coding a program which will need functions to change labels and enter text into text boxes however I do not know how to do this with a new style of programming which I am using (Object Orientated). I have done the program before however I generated the frames using this code:
f = [Frame(root) for i in range(0,5)]
for i in f:
i.place(relx=0,rely=0,relwidth=1,relheight=1)
and then I put it all in one class which I ran however that was bad form so I am redoing it. My code so far is as follows:
import tkinter as tk
import datetime,time,os,sys
import sqlite3 as lite
from datetime import date
Title_Font= ("Times", 18, "underline italic")
unix = time.time()
time_curr = str(datetime.datetime.fromtimestamp(unix).strftime('%H:%M'))
date1 = str(datetime.datetime.fromtimestamp(unix).strftime('%d-%m-%Y'))
class Creating_Stuff(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
container = tk.Frame(self)
container.pack(side="top", fill="both", expand = True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (StartPage, PageOne, PageTwo):
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(StartPage)
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
class StartPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self,parent)
self.grid_columnconfigure(0, weight=1)
self.grid_columnconfigure(3, weight=1)
self.option_add( "*font", "Times 12" )
self.tk_setPalette(background='#bbfff0', foreground='black',
activeBackground='#d9d9d9', activeForeground='#ff9933')
label = tk.Label(self, text="Laptop Booking System", font=Title_Font)
label.grid(row=0, column=1, pady = 30)
time = tk.Label(self, text="Time: " + time_curr + "\nDate: " + date1, font="Times 10")
time.grid(row=0, column=2,columnspan=2)
Booking_1 = tk.Button(self, text="Booking",
command=lambda: controller.show_frame(PageOne),bg='#f2f2f2',width=20)
Booking_1.grid(row=2, column=1, pady=10)
Tbl_q1 = tk.Button(self, text="Table Querying",
command=lambda: controller.show_frame(PageTwo),bg='#f2f2f2',width=20)
Tbl_q1.grid(row=3, column=1, pady=10)
Exit = tk.Button(self, text ="Exit",command=lambda:destroy(),bg='#f2f2f2')
Exit.grid(row=5, column=1)
class PageOne(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.grid_columnconfigure(0, weight=1)
self.grid_columnconfigure(3, weight=1)
label = tk.Label(self, text="Page One!!!", font=Title_Font)
label.grid(row=1, column=1)
bk2_menu = tk.Button(self, text="Back to Home",
command=lambda: controller.show_frame(StartPage))
bk2_menu.grid(row=3, column=1)
class PageTwo(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.grid_columnconfigure(0, weight=1)
self.grid_columnconfigure(3, weight=1)
label = tk.Label(self, text="Page Two!!!", font=Title_Font)
label.grid(row=1, column=1)
bk2_Menu2 = tk.Button(self, text="Back to menu",
command=lambda: controller.show_frame(StartPage))
bk2_Menu2.grid(row=3, column=1)
app = Creating_Stuff()
def destroy():
app.destroy()
app.title("Laptop Booking System")
app.geometry("700x400")
app.mainloop()
If you try it out it works however it just has 3 different frames. How can I get a button in a frame to make a label say "Hello" in the frame after it is pressed?
I've modified one of your page classes to illustrate how it could be done. It involved adding a Label to hold the message, a Button to control it, and a function, called simply handler(), to call when the latter is pressed. It saves the widgets by making them attributes of the containing Frame subclass instance, self, so they can be easily referenced in the handler() function (without resorting to global variables).
class PageOne(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.grid_columnconfigure(0, weight=1)
self.grid_columnconfigure(3, weight=1)
label = tk.Label(self, text="Page One!!!", font=Title_Font)
label.grid(row=1, column=1)
self.msg_label = tk.Label(self, text="")
self.msg_label.grid(row=2, column=1)
self.msg_button = tk.Button(self, text='Show Message',
command=self.handler)
self.msg_button.grid(row=3, column=1)
self.msg_toggle = False
bk2_menu = tk.Button(self, text="Back to Home",
command=lambda: controller.show_frame(StartPage))
bk2_menu.grid(row=5, column=1)
def handler(self):
self.msg_toggle = not self.msg_toggle
if self.msg_toggle:
self.msg_label.config(text='Hello')
self.msg_button.config(text='Clear Message')
else:
self.msg_label.config(text='')
self.msg_button.config(text='Show Message')
Screenshots
Before button is pressed:
After button is pressed:
Related
This question already has answers here:
How to get variable data from a class?
(2 answers)
Closed 1 year ago.
I'm looking for advice on how to solve my problem. I need a way to save the entries list in my saveInput() method so I can access it later outside the class with a different function. The only solution I have come up with is a global variable but I'm told they are the devil and I should try to avoid them when they are not constant. If anybody could give me a solution I would greatly appreciate it. My code is below, including the CSV file.
from tkinter import font as tkfont # python 3
import tkinter as tk
import csv
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, PageThree, PageFour):
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="Enter airport details",
command=lambda: controller.show_frame("PageOne"))
button2 = tk.Button(self, text="Enter flight details",
command=lambda: controller.show_frame("PageTwo"))
button3 = tk.Button(self, text="Enter price plan and calculate profit",
command=lambda: controller.show_frame("PageThree"))
button4 = tk.Button(self, text="Clear data",
command=lambda: controller.show_frame("PageFour"))
button1.pack()
button2.pack()
button3.pack()
button4.pack()
class PageOne(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
ukAirportOptionList = [
"LPL",
"BOH"
]
foreignAirportList = []
with open('Airports.csv', 'r') as fd:
reader = csv.reader(fd)
for row in reader:
foreignAirportList.append(row)
tk.Label(self, text="Airport Details", font=controller.title_font).grid()
ukAirportTracker = tk.StringVar()
ukAirportTracker.set("Select the UK Airport")
tk.OptionMenu(self, ukAirportTracker, *ukAirportOptionList).grid()
foreignAirportTracker = tk.StringVar()
foreignAirportTracker.set("Select the Oversea Airport")
tk.OptionMenu(self, foreignAirportTracker, *[airport[0] for airport in foreignAirportList]).grid()
saveButton = tk.Button(self, text="Save",
command=lambda: [controller.show_frame("StartPage"),
self.saveInput(ukAirportTracker, foreignAirportTracker)])
saveButton.grid(row=3, column=1)
def saveInput(self, *args):
enteries = []
for arg in args:
enteries.append(arg.get())
print(enteries)
class PageTwo(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
aircraftTypesList = [['medium narrow body', 8, 2650, 180, 8],
['large narrow body', 7, 5600, 220, 10],
['medium wide body', 5, 4050, 406, 14]]
label = tk.Label(self, text="Flight Details", font=controller.title_font)
label.grid()
aircraftTypeTracker = tk.StringVar()
aircraftTypeTracker.set("Aircraft Type")
tk.OptionMenu(self, aircraftTypeTracker, *[aircraft[0] for aircraft in aircraftTypesList]).grid()
saveButton = tk.Button(self, text="Save",
command=lambda: [controller.show_frame("StartPage"), self.saveInput(aircraftTypeTracker)])
saveButton.grid()
def saveInput(self, *args):
enteries = []
for arg in args:
enteries.append(arg.get())
print(enteries)
class PageThree(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
tk.Label(self, text="This is page 3", font=controller.title_font).grid(row=0, column=0)
tk.Label(self, text="Price of Standard Seat").grid(row=1)
tk.Label(self, text="Price of First Class Seat").grid(row=2)
e1 = tk.Entry(self)
e2 = tk.Entry(self)
e1.grid(row=1, column=1)
e2.grid(row=2, column=1)
saveButton = tk.Button(self, text="Save",
command=lambda: [controller.show_frame("StartPage"), self.saveInput(e1, e2)])
saveButton.grid(row=3, column=1)
def saveInput(self, *args):
enteries = []
for arg in args:
enteries.append(arg.get())
print(enteries)
class PageFour(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="This is page 4", 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()
The csv file:
JFK,John F Kennedy International,5326,5486
ORY,Paris-Orly,629,379
MAD,Adolfo Suarez Madrid-Barajas,1428,1151
AMS,Amsterdam Schiphol,526,489
CAI,Cairo International,3779,3584
A way to mostly✶ avoid global variables in this case is to make the local variable enteries an instance attribute of some class. In this case I chose the SampleApp "controller" this tkinter app architecture defines. (Note I also changed its name to entries in the modified code below.)
✶ I say that because it's very difficult to not have any.
Disclaimer: I don't quite understand what you want or are planning to put into the enteries list in each Page class of you code, so the results below merely do the same as in your code. I'm also not sure what you mean by "returning variables" because classes are objects and don't return anything per se. They can be containers of data and have methods that return values — but you don't have any examples of that in your question's code. To rectify that I added a Quit button to demonstrate how the data could be retrieved.
Anyway, I made the modifications needed to do that in code below. In addition, I noticed there was a lot of replicated / very similar code in each Page class, so I defined a private base class named _BasePage and derived all the others from it. This allowed me to put the common code in there and is an example of apply the DRY principle which is another benefit of using classes.
from tkinter import font as tkfont # python 3
import tkinter as tk
import csv
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")
self.entries = [] # Accumulated entries.
# 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, PageThree, PageFour):
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 _BasePage(tk.Frame):
def __init__(self, parent, controller):
super().__init__(parent)
self.controller = controller
def saveInput(self, *string_vars):
strings = [var.get() for var in string_vars]
print(f'adding entries: {strings}')
self.controller.entries.extend(strings)
class StartPage(_BasePage):
def __init__(self, parent, controller):
super().__init__(parent, controller)
label = tk.Label(self, text="This is the start page", font=controller.title_font)
label.pack(side="top", fill="x", pady=10)
tk.Button(self, text="Enter airport details",
command=lambda: controller.show_frame("PageOne")).pack()
tk.Button(self, text="Enter flight details",
command=lambda: controller.show_frame("PageTwo")).pack()
tk.Button(self, text="Enter price plan and calculate profit",
command=lambda: controller.show_frame("PageThree")).pack()
tk.Button(self, text="Clear data",
command=lambda: controller.show_frame("PageFour")).pack()
tk.Button(self, text="Quit",
command=self.quit).pack() # Terminate mainloop().
class PageOne(_BasePage):
def __init__(self, parent, controller):
super().__init__(parent, controller)
ukAirportOptionList = [
"LPL",
"BOH"
]
foreignAirportList = []
with open('Airports.csv', 'r') as fd:
reader = csv.reader(fd)
for row in reader:
foreignAirportList.append(row)
tk.Label(self, text="Airport Details", font=controller.title_font).grid()
ukAirportTracker = tk.StringVar()
ukAirportTracker.set("Select the UK Airport")
tk.OptionMenu(self, ukAirportTracker, *ukAirportOptionList).grid()
foreignAirportTracker = tk.StringVar()
foreignAirportTracker.set("Select the Oversea Airport")
tk.OptionMenu(self, foreignAirportTracker,
*[airport[0] for airport in foreignAirportList]).grid()
saveButton = tk.Button(self, text="Save", command=lambda:
[controller.show_frame("StartPage"),
self.saveInput(ukAirportTracker, foreignAirportTracker)])
saveButton.grid(row=3, column=1)
class PageTwo(_BasePage):
def __init__(self, parent, controller):
super().__init__(parent, controller)
aircraftTypesList = [['medium narrow body', 8, 2650, 180, 8],
['large narrow body', 7, 5600, 220, 10],
['medium wide body', 5, 4050, 406, 14]]
label = tk.Label(self, text="Flight Details", font=controller.title_font)
label.grid()
aircraftTypeTracker = tk.StringVar()
aircraftTypeTracker.set("Aircraft Type")
tk.OptionMenu(self, aircraftTypeTracker,
*[aircraft[0] for aircraft in aircraftTypesList]).grid()
saveButton = tk.Button(self, text="Save", command=lambda:
[controller.show_frame("StartPage"),
self.saveInput(aircraftTypeTracker)])
saveButton.grid()
class PageThree(_BasePage):
def __init__(self, parent, controller):
super().__init__(parent, controller)
tk.Label(self, text="This is page 3",
font=controller.title_font).grid(row=0, column=0)
tk.Label(self, text="Price of Standard Seat").grid(row=1)
tk.Label(self, text="Price of First Class Seat").grid(row=2)
e1 = tk.Entry(self)
e2 = tk.Entry(self)
e1.grid(row=1, column=1)
e2.grid(row=2, column=1)
saveButton = tk.Button(self, text="Save",
command=lambda: [controller.show_frame("StartPage"),
self.saveInput(e1, e2)])
saveButton.grid(row=3, column=1)
class PageFour(_BasePage):
def __init__(self, parent, controller):
super().__init__(parent, controller)
label = tk.Label(self, text="This is page 4", 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()
print('Final entries:')
for entry in app.entries:
print(f' {entry}')
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I'm trying to write the 'ping' output to a text box that will be
created in the 'output' tkinter frame
When I press the 'Submit' button while writing the output to file.
Questions:
1: Is there a way to place the text box inside the 'output' frame?
2: How can I print lines from files inside the 'output' frame?
3: How can I use threading or multiproccess to display the output in realtime?
Before clicking 'Submit':
import tkinter as tk
import subprocess as sub
from multiprocessing import Queue
import os
class GUI(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
self.geometry("650x500")
self.title("Gil Shwartz GUI Project")
menu = tk.Frame(self, height=250, width=10, relief="solid")
menu.pack(side=tk.LEFT, fill="both", anchor="w")
container = tk.Frame(self, relief="flat")
container.pack(side=tk.TOP, fill="y", expand=True)
output = tk.LabelFrame(self, text="Output", height=350, width=70)
output.pack(side=tk.BOTTOM, fill="both", expand=True)
menu.grid_columnconfigure(0, weight=1)
menu.grid_rowconfigure(0, weight=1)
self.frames = ["Menu", "MainWelcome", "testPing", "PageOne", "PageTwo"]
self.frames[0] = Menu(parent=menu, controller=self)
self.frames[1] = MainWelcome(parent=container, controller=self)
self.frames[2] = testPing(parent=container, controller=self)
self.frames[3] = PageOne(parent=container, controller=self)
self.frames[4] = PageTwo(parent=container, controller=self)
self.frames[0].grid(row=0, column=0, sticky="nsew")
self.frames[1].grid(row=0, column=0, sticky="nsew")
self.frames[2].grid(row=0, column=0, sticky="nsew")
self.frames[3].grid(row=0, column=0, sticky="nsew")
self.frames[4].grid(row=0, column=0, sticky="nsew")
self.show_frame(1)
def show_frame(self, page_name):
frame = self.frames[page_name]
print(frame)
frame.tkraise()
frame.grid(row=0, column=0, sticky="nsew")
class Menu(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
button1 = tk.Button(self, text="Ping Test",
command=lambda: controller.show_frame(2))
button1.config(bg="royalblue2")
button2 = tk.Button(self, text="Page Two",
command=lambda: controller.show_frame(4))
button2.config(bg="dark violet")
button3 = tk.Button(self, text="Quit",
command=lambda: Menu.terminate(self))
button3.config(bg="gray40")
button1.pack(fill="both", expand=True)
button2.pack(fill="both", expand=True)
button3.pack(fill="both", expand=True)
button1.grid_columnconfigure(0, weight=1)
button2.grid_columnconfigure(0, weight=0)
button3.grid_rowconfigure(0, weight=0)
def terminate(self):
exit()
class MainWelcome(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="Text 1", bg="yellow")
label.pack(fill="x", expand=True)
label = tk.Label(self, text="Text 2", bg="yellow")
label.pack(fill="x")
class testPing(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
urlLabel = tk.Label(self, text="Enter URL : ", padx=5, pady=5)
urlLabel.pack(anchor="w")
urlInputBox = tk.Entry(self)
urlInputBox.pack(anchor="w")
urlInputBox.grid_columnconfigure(0, weight=0)
clearFileLabel = tk.Label(self, text="Clear File?", padx=5, pady=5)
clearFileLabel.pack(anchor="w")
clearFile = tk.BooleanVar()
clearFile.set(False)
clearFileRadioYes = tk.Radiobutton(self, text="yes", value=True, var=clearFile,
command=lambda: self.callback(clearFile.get()))
clearFileRadioYes.pack(anchor="w")
clearFileRadioNo = tk.Radiobutton(self, text="no", value=False, var=clearFile,
command=lambda: self.callback(clearFile.get()))
clearFileRadioNo.pack(anchor="w")
urlSubmitButton = tk.Button(self, text="Submit",
command=lambda: self.pingURL(urlInputBox.get(),
clearFile.get()))
urlSubmitButton.pack(side=tk.RIGHT, anchor="e")
def callback(self, clearFile):
print(clearFile) # Debugging Mode - check Radio box Var.
def pingURL(self, host, clearFile):
global r
file = fr'c:/users/{os.getlogin()}/Desktop/ping.txt'
text = tk.Text(self, height=5, width=100, wrap=tk.WORD)
text.pack(side=tk.TOP, expand=True)
if clearFile == True:
with open(file, 'a') as output:
output.truncate(0)
sub.call(['ping', f'{host}'], stdout=output)
else:
with open(file, 'a') as output:
sub.call(['ping', f'{host}'], stdout=output)
output.close()
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", bg="red")
label.pack(side="top", fill="x", pady=10)
button = tk.Button(self, text="Go to page 2",
command=lambda: controller.show_frame(2))
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", bg="blue")
label.pack(side="top", fill="x", pady=10)
button = tk.Button(self, text="Go to the start page",
command=lambda: controller.show_frame(1))
button.pack()
if __name__ == "__main__":
app = GUI()
app.mainloop()
After clicking 'Submit':
First, you have to make the output frame available or else you can't access it later:
self.output = tk.LabelFrame(self, text="Output", height=350, width=70)
self.output.pack(side=tk.BOTTOM, fill="both", expand=True)
Then, in the testPing() class pingURL() method you can pack the Text() widget in the output labelframe:
text = tk.Text(self.controller.output, height=5, width=100, wrap=tk.WORD)
I don't know about using threading or multiproccess. In general I think you will get a better response if you post questions for each of your problems instead of listing them in the same question.
I am VERY new to coding/Python, but basically I am trying to move a button and label around using .grid, however, the button and label in the StartPage class just won't move to where I ask (or even at all).
Everything in the BMR class works fine (although the positions you see aren't the final positions, I was just checking).
What is the difference? Why do they not appear at the same position if I give the same details in both classes?
import tkinter as tk
class initials(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
container = tk.Frame(self)
container.pack(side='top', fill='both', expand= True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (StartPage, BMR):
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): #GRID WON'T WORK HOW I WANT IT TO
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="Start Page")
label.grid(column=3, row=3, sticky='we')
button = tk.Button(self, text="Calculate BMR",
command=lambda: controller.show_frame(BMR))
button.grid(row=4, column=3, sticky='we')
class BMR(tk.Frame): #GRID WORKS PERFECTLY
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="BMR Calculator")
label.grid(column=1,row=1)
button1 = tk.Button(self, text="Back to Home",
command=lambda: controller.show_frame(StartPage))
button1.grid(column=2, row=2)
submit = tk.Button(self, text="Calculate")
submit.grid(column=3, row=3)
var1 = tk.IntVar()
tk.Checkbutton(self, text='Male', bg='white', variable=var1).grid(column=4, row=4)
var2= tk.IntVar()
tk.Checkbutton(self, text='Female', bg='white', variable=var2).grid(column=5, row=5)
height_inp = tk.Entry(self, width=20, bg="white").grid(column=6, row=6)
app = initials()
app.mainloop()
class StartPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="Start Page", width = 80)
# Added width property in the line above
# and changed sticky property to N
label.grid(row = 3, column=3, sticky = 'N')
label.width = 20
button = tk.Button(self, text="Calculate BMR",
command=lambda: controller.show_frame(BMR))
button.grid(row=4, column=3)
# Removed sticky property for the button
I understand this is how you wish to position the label and the button.
Pleaase see the comments. You can edit the value for the width property and make it suitable for your frame.
I have a problem with my code. I am unable to pass a variable to another class once a submit button is pressed in my tkinter frame.
I have followed the advice from a post already (How to access variables from different classes in tkinter?), which has helped but I still have issues.
From where to where I need these variables is commented on the code below:
import tkinter as tk
from tkinter import StringVar
LARGE_FONT = ("Verdana", 12)
class Club(tk.Tk):
def get_page(self, page_class):
return self.frames[page_class]
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.shared_data = {
"username": tk.StringVar(),
"password": tk.StringVar(),
}
self.frames = {}
for F in (Terminal, newUser, newUserSubmitButton, delUser):
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(Terminal)
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
class Terminal(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="Welcome to the club terminal. Click the options below", font=LARGE_FONT)
label.grid(columnspan=3)
button = tk.Button(self, text="Visit new User",
command=lambda: controller.show_frame(newUser))
button.grid(row=1, column=0)
button2 = tk.Button(self, text="Visit del User",
command=lambda: controller.show_frame(delUser))
button2.grid(row=1, column=1)
class newUser(tk.Frame):
def __init__(self, parent, controller):
def submitButton():
username = self.controller.shared_data["username"].get()
print(username)
controller.show_frame(newUserSubmitButton)
##username variable from here to...
tk.Frame.__init__(self, parent)
welcomelabel = tk.Label(self, text="Add New User/s", font=LARGE_FONT)
welcomelabel.grid(columnspan=2, sticky="ew")
userNameLabel = tk.Label(self, text="Username")
userNameLabel.grid(row=1, column=0, sticky="e")
userNameEntry = tk.Entry(self, textvariable=self.controller.shared_data["username"])
userNameEntry.grid(row=1, column=1)
userMemTypeLabel = tk.Label(self, text="Membership Type")
userMemTypeLabel.grid(row=2, column=0, sticky="e")
variable = StringVar(self)
variable.set("Full")
userMemTypeMenu = tk.OptionMenu(self, variable, "Full", "Half")
userMemTypeMenu.grid(row=2, column=1)
userMemYearsLabel = tk.Label(self, text="Years that member is in the club")
userMemYearsLabel.grid(row=3, column=0, sticky="e")
userMemYearsEntry = tk.Entry(self)
userMemYearsEntry.grid(row=3, column=1)
self.controller = controller
newusersubmitbutton = tk.Button(self, text="submit", command=submitButton)
newusersubmitbutton.grid(columnspan=2)
class newUserSubmitButton(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
##username variable goes here
page1 = self.controller.get_page(newUser.submitButton)
page1.username.set("Hello, world")
print(page1)
class delUser(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="del User!!!", font=LARGE_FONT)
label.pack(pady=10, padx=10)
button1 = tk.Button(self, text="Back to Home",
command=lambda: controller.show_frame(Terminal))
button1.pack()
button2 = tk.Button(self, text="new User",
command=lambda: controller.show_frame(newUser))
button2.pack()
app = Club()
app.title("Club Terminal")
app.iconbitmap("table.ico")
app.mainloop()
Whenever I run this code, I get an AttributeError: 'newUser' object has no attribute 'controller'.
Any help is greatly appreciated, I'll be more than happy to try any ideas out.
With regards.
There are more problems in this code, but to solve that one, add the line:
self.controller=controller
To the newUser classes __init__ function.
I am trying to make a gui full screen. Is working as full screen but i am not able to do the followings :
1 - first row (row 0) to be scaled to max width of screen
2 - on row 1, the first and last column have fixed width and stay on left and right of the screen (this is working)
3 - the empty labels between buttons to be on the center
4 - the 2 buttons to be center aligned in left and right
This is my code till now:
import Tkinter as tk
from Tkinter import *
class MainApp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
container = tk.Frame(self)
container.pack(side="top", fill="both", expand=True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (StartPage, PageOne, PageTwo):
page_name = F.__name__
frame = F(parent=container, controller=self)
self.frames[page_name] = frame
frame.grid(row=0, column=0, sticky="nsew")
frame.grid_columnconfigure(0, weight=1)
self.show_frame("StartPage")
def show_frame(self, 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
#line 0
label0 = tk.Label(self, text = 'full row', height=3, borderwidth=1)
label0.configure(relief='raised')
label0.grid(row=0, column=0, columnspan=12)
# line 1
label1 = tk.Label(self, text='0', width=10)
label1.configure(relief='raised', bg='white')
label1.grid(row=1, column=0, sticky='w')
buttonhlp = tk.Button(self, text="HELP", command=close_window)
buttonhlp.grid(row=1, column=1, columnspan=4)
label1 = tk.Label(self, text='')
label1.grid(row=1, column=5)
label1 = tk.Label(self, text='')
label1.grid(row=1, column=6)
buttonquit = tk.Button(self, text="Quit", command=close_window)
buttonquit.grid(row=1, column=7, columnspan=4)
label1 = tk.Label(self, text='11', width=10)
label1.configure(relief='raised', bg='white')
label1.grid(row=1, column=11, 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 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()
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")
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 close_window ():
app.destroy()
if __name__ == "__main__":
app = MainApp()
app.overrideredirect(True)
app.geometry("{0}x{1}+0+0".format(app.winfo_screenwidth(), app.winfo_screenheight()))
app.focus_set() # <-- move focus to this widget
app.mainloop()
not sure is the best solution but i made it work like this
import Tkinter as tk
from Tkinter import *
class MainApp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
container = tk.Frame(self)
container.pack(side="top", fill="both", expand=True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (StartPage, PageOne, PageTwo):
page_name = F.__name__
frame = F(parent=container, controller=self)
self.frames[page_name] = frame
frame.grid(row=0, column=0, columnspan=12,sticky="nsew")
frame.grid_columnconfigure(0, weight=1)
frame.grid_columnconfigure(1, weight=1)
frame.grid_columnconfigure(2, weight=1)
frame.grid_columnconfigure(3, weight=1)
frame.grid_columnconfigure(4, weight=1)
frame.grid_columnconfigure(5, weight=1)
frame.grid_columnconfigure(6, weight=1)
frame.grid_columnconfigure(7, weight=1)
frame.grid_columnconfigure(8, weight=1)
frame.grid_columnconfigure(9, weight=1)
frame.grid_columnconfigure(10, weight=1)
frame.grid_columnconfigure(11, weight=1)
self.show_frame("StartPage")
def show_frame(self, 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
#line 0
label0 = tk.Label(self, text = '')
label0.configure(relief='raised')
label0.grid(row=0, column=0, columnspan=12, sticky="nsew")
# line 1
label1 = tk.Label(self, text='0', width=10)
label1.configure(relief='raised', bg='white')
label1.grid(row=1, column=0, sticky='w')
buttonhlp = tk.Button(self, text="HELP", command=close_window)
buttonhlp.grid(row=1, column=1, columnspan=4)
label1 = tk.Label(self, text='xx')
label1.grid(row=1, column=5)
label1 = tk.Label(self, text='tt')
label1.grid(row=1, column=6)
buttonquit = tk.Button(self, text="Quit", command=close_window)
buttonquit.grid(row=1, column=7, columnspan=4)
label1 = tk.Label(self, text='11', width=10)
label1.configure(relief='raised', bg='white')
label1.grid(row=1, column=11, 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 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()
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")
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 close_window ():
app.destroy()
if __name__ == "__main__":
app = MainApp()
app.overrideredirect(True)
app.geometry("{0}x{1}+0+0".format(app.winfo_screenwidth(), app.winfo_screenheight()))
app.focus_set() # <-- move focus to this widget
app.mainloop()