I'm trying to write a program which takes the users information, like their name and stuff, on one page, and then displays these entries on another. I'm using Tkinter and I can't get their entries to display on the other page. Here's the program:
import tkinter as tk
from tkinter import ttk
#PROFILE VARS
FirstName = ('none')
#INITIALIZING
class MegaQuiz(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
tk.Tk.wm_title(self, "THE MEGA POP QUIZ")
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 (ProfilePage, MainPage):
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("ProfilePage")
def show_frame(self, page_name):
frame = self.frames[page_name]
frame.tkraise()
#PROFILE PAGE
class ProfilePage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
global FirstName
#Profile Title
profile_title = tk.Label(self, text="Create A Profile Yo")
profile_title.grid(column=0, row=2)
#FIRST NAME
Q1_title = tk.Label(self, text="First Name:")
Q1_title.grid(column=0, row=1)
FirstNameEntry = tk.Entry(self)
FirstNameEntry.grid(column=2, row=4)
FirstName = str(FirstNameEntry.get())
#NEXT BUTTON
Button1 = tk.Button(self, text="NEXT",
command = lambda: controller.show_frame("MainPage"))
Button1.grid(column=10, row=10)
#MAIN MENU PAGE
class MainPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
#Play BUTTON
PlayBTN = tk.Button(self, text="PLAY", width=40)
PlayBTN.grid(column=0, row=20, sticky="nesw")
#ProfileDisplay
FirstNameDis = tk.Label(self, text=('FirstName: ' + FirstName))
FirstNameDis.grid(column=0, row=0, sticky="w")
#RUNNING PROGRAM
app = MegaQuiz()
app.mainloop()
The problem is that it displays the "FirstName: ", but doesn't display the variables FirstName, just blankness, help.
The quickest way to fix this is to move your FirstName variable to the MegaQuiz as a class attribute and then use it from there. We can change your NEXT button command to call a class method and then from that method update the FirstName variable and then also set the FirstNameDis label text from that same method.
First move the FirstName variable into your MegaQuiz class by putting this line in the __init__ section.
self.FirstName = 'none'
Then change this:
#NEXT BUTTON
Button1 = tk.Button(self, text="NEXT", command = lambda: controller.show_frame("MainPage"))
To this:
#NEXT BUTTON
Button1 = tk.Button(self, text="NEXT", command=self.next_button)
Button1.grid(column=10, row=10)
def next_button(self):
self.controller.FirstName = self.FirstNameEntry.get()
self.controller.frames["MainPage"].FirstNameDis.config(text='FirstName: ' + self.controller.FirstName)
self.controller.show_frame("MainPage")
In your MainPage change this:
self.FirstNameDis = tk.Label(self, text='FirstName: ' + FirstName)
To this:
self.FirstNameDis = tk.Label(self, text='FirstName: ' + self.controller.FirstName)
That should be all you need to fix this.
I did notice a few PEP8 issues so here is your code rewritten to provide a fix to your problem and also to rewrite some things to better follow the PEP8 guidelines.
Not sure why you are adding () to some of your string variables but it is not needed.
variable and class attribute names should be all lower case with underscores to between words.
You do not need to provide a variable name for everything. If you have a button or a label you know you will not be updating later then you can write them without the variable names.
Code:
import tkinter as tk
class MegaQuiz(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self)
self.title("THE MEGA POP QUIZ")
self.first_name = 'none'
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 (ProfilePage, MainPage):
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("ProfilePage")
def show_frame(self, page_name):
frame = self.frames[page_name]
frame.tkraise()
class ProfilePage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
tk.Label(self, text="Create A Profile Yo").grid(column=0, row=2)
tk.Label(self, text="First Name: ").grid(column=0, row=1)
self.fn_entry = tk.Entry(self)
self.fn_entry.grid(column=2, row=4)
tk.Button(self, text="NEXT", command=self.next_button).grid(column=10, row=10)
def next_button(self):
self.controller.first_name = self.fn_entry.get()
self.controller.frames["MainPage"].fn_dis.config(text='FirstName: {}'.format(self.controller.first_name))
self.controller.show_frame("MainPage")
class MainPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
tk.Button(self, text="PLAY", width=40).grid(column=0, row=20, sticky="nesw")
self.fn_dis = tk.Label(self)
self.fn_dis.grid(column=0, row=0, sticky="w")
app = MegaQuiz()
app.mainloop()
Related
I am trying to use GPS sensor with RPI and make its GUI using Tkinter. I want to update my GPS value and shows in the GUI. But in GUI it shows only initial value. In backend GPS value is updating but unable to show in GUI.
import tkinter as tk
import serial
import time
import webbrowser as wb
ser = serial.Serial('/dev/ttyUSB0', 9600)
class IotCar(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
width=tk.Tk.winfo_screenwidth(self)
height=tk.Tk.winfo_screenheight(self)
tk.Tk.geometry(self, '{}x{}'.format(width, height))
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 each_frame in (StartPage, HomePage):
frame = each_frame(container, self)
self.frames[each_frame]=frame
frame.grid(row=0, column=0, sticky='nsew')
self.show_page(StartPage)
def show_page(self, cont):
frame=self.frames[cont]
frame.tkraise()
class StartPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
next_button = tk.Button(self, text='Next', command=lambda:
controller.show_page(HomePage)).pack(side=tk.TOP,padx=5, pady=5)
class HomePage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.gps_pos()
self.lat1 = tk.StringVar()
self.lon1=tk.StringVar(self)
self.label_lat = tk.Label(self.HomePage, text='Latitude', justify=tk.LEFT, padx=10).pack()
self.label_lat1 = tk.Label(self.HomePage, textvariable=self.lat1, justify=tk.LEFT,
borderwidth=2, relief='ridge').pack()
self.label_lon = tk.Label(self, text='Longitude', justify=tk.LEFT, padx=10).pack()
self.label_lon1 = tk.Label(self, text=self.lon1, justify=tk.LEFT,
borderwidth=2, relief='ridge').pack()
def gps_pos(self):
print('Entered into gps')
ser.flushInput()
ser.flushOutput()
ser.write(b'AT+CGPSPWR=1\r')
ser.write(b'AT+CGPSOUT=32\r')
while True:
gps=str(ser.readline())
gps=gps[2:].split(',')
if gps[0]=='$GPRMC' and gps[3]!='':
lat=gps[1]
lon=gps[1]
break;
self.after(3000,self.gps_pos)
print(lat, lon)
self.lat1.set(lat1)
app = IotCar()
app.mainloop()
Please help me to understand what is wrong in it. Thank you in advance.
I am unable to run this script as I don't have the serial module however I have modified a few things and this populates the label with text (comments in code). You need a function that will assign the "text" parameters in the labels with a value.
import tkinter as tk
import time
import webbrowser as wb
class IotCar(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
width=tk.Tk.winfo_screenwidth(self)
height=tk.Tk.winfo_screenheight(self)
tk.Tk.geometry(self, '{}x{}'.format(width, height))
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 each_frame in (StartPage, HomePage):
frame = each_frame(container, self)
self.frames[each_frame]=frame
frame.grid(row=0, column=0, sticky='nsew')
self.show_page(StartPage)
def show_page(self, cont):
frame=self.frames[cont]
frame.tkraise()
class StartPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
next_button = tk.Button(self, text='Next', command=lambda:
controller.show_page(HomePage)).pack(side=tk.TOP,padx=5, pady=5)
class HomePage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.lat1 = tk.StringVar()
self.lon1 = tk.StringVar(self)
self.label_lat = tk.Label(self, text='Latitude', justify=tk.LEFT, padx=10)
self.label_lat.pack()
self.label_lat1 = tk.Label(self, justify=tk.LEFT,
borderwidth=2, relief='ridge') # I have removed the "text" parameter because my function will update it.
self.label_lat1.pack()
self.label_lon = tk.Label(self, text='Longitude', justify=tk.LEFT, padx=10)
self.label_lon.pack()
self.label_lon1 = tk.Label(self, justify=tk.LEFT,
borderwidth=2, relief='ridge') # I have removed the "text" parameter because my function will update it.
self.label_lon1.pack()
button = tk.Button(self, text="update label", bg= "#aaaaaa", fg ="#483F44",
font=("Arial", 10, "bold"), relief="groove", command = lambda: helloworld()) # This button will run the helloworld function
button.pack()
def helloworld():
self.label_lat1["text"] = "Hello" #This will update the text parameter in label_lat1 with "Hello"
self.label_lon1["text"] = "World" #This will update the text parameter in label_lon1 with "World"
app = IotCar()
app.mainloop()
A few things to note is to pack/place/grid your labels separately from when you define its parameters i believe that the way you have currently set up the widget is giving it a None type which is why you can't assign text to it:
#You write
self.label_lat1 = tk.Label(self.HomePage, textvariable=self.lat1, justify=tk.LEFT,
borderwidth=2, relief='ridge').pack()
#My example
self.label_lat1 = tk.Label(self, justify=tk.LEFT,
borderwidth=2, relief='ridge')
self.label_lat1.pack()
You then need a command that will run a function and in that function will have a variable which will assign a text value to the label (i.e. the helloworld function in my code).
Looking at your code i believe you will need to amend the way you are packing your widgets and then in your function do something like
def gps_pos(self):
print(lat, lon)
self.label_lat1["text"] = lat
self.label_lon1["text"] = lon
Below is a very useful answer on how to layout your tkinter gui and various other FAQ. I myself found it extremely useful
Switch between two frames in tkinter
I need to update listbox when I'm changing view, but I dont know how to do it. On first page I'm adding some items to list and on second it should to show all items in listbox.
# -*- coding: utf-8 -*-
from tkinter import *
tb1 = [["Kofola", "0,5","30"]]
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 (StartPage, PageOne):
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(Frame):
def __init__(self, parent, controller):
Frame.__init__(self,parent)
label = Label(self, text="Start Page")
label.pack(pady=10,padx=10)
button = Button(self, text="Visit Page 1",
command=lambda: controller.show_frame(PageOne))
button.pack()
button2 = Button(self, text="add",
command=self.add)
button2.pack()
def add(self):
tb1.append(["Radegast", "0,5","30"])
print(tb1)
class PageOne(Frame):
def __init__(self, parent, controller):
Frame.__init__(self, parent)
label = Label(self, text="Page One!!!")
label.pack(pady=10,padx=10)
button1 = Button(self, text="Back to Home",
command=lambda: controller.show_frame(StartPage))
button1.pack()
self.bill=Listbox(self)
self.bill.pack()
for item in tb1:
co=" ".join(str(x) for x in item)
self.bill.insert(END, co)
app = SeaofBTCapp()
app.mainloop()
In the PageOne class You are reading the list tb1 only once, in __init__(). To get the changes in tb1 to be seen in the listbox you also have to update the listbox with the new altered list.
There is also an issue with the list. As it's defined in the global namespace your app will depend on this. I'd suggest you define it in the SeaofBTCapp() __init__() function and then you can access it through the controller object:
class SeaofBTCapp(Tk):
def __init__(self, *args, **kwargs):
Tk.__init__(self, *args, **kwargs)
self.tb1 = [["Kofola", "0,5","30"]]
... etc ...
class StartPage(Frame):
def __init__(self, parent, controller):
self.controller = controller
... etc ...
def add(self):
self.controller.tb1.append(["Radegast", "0,5","30"])
... etc ...
And then add an update() method to the PageOne() class which updates the listbox and calls it from the add() method. I'm calling by way of controller method update_pageone(). See full example below:
from tkinter import *
class SeaofBTCapp(Tk):
def __init__(self, *args, **kwargs):
Tk.__init__(self, *args, **kwargs)
self.tb1 = [["Kofola", "0,5","30"]] # Create instance variable tb1
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 (StartPage, PageOne):
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(StartPage)
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
def update_pageone(self):
self.frames[PageOne].update() # Call update on PageOne
class StartPage(Frame):
def __init__(self, parent, controller):
self.controller = controller # Remember the controller
Frame.__init__(self,parent)
label = Label(self, text="Start Page")
label.pack(pady=10,padx=10)
button = Button(self, text="Visit Page 1",
command=lambda: self.controller.show_frame(PageOne))
button.pack()
button2 = Button(self, text="add", command=self.add)
button2.pack()
def add(self):
self.controller.tb1.append(["Radegast", "0,5","30"])
self.controller.update_pageone() # Asking controller for an update
class PageOne(Frame):
def __init__(self, parent, controller):
self.controller = controller # Remember the controller
Frame.__init__(self, parent)
label = Label(self, text="Page One!!!")
label.pack(pady=10,padx=10)
button1 = Button(self, text="Back to Home",
command=lambda: controller.show_frame(StartPage))
button1.pack()
self.bill = Listbox(self)
self.bill.pack()
for item in controller.tb1:
co = " ".join(str(x) for x in item)
self.bill.insert(END, co)
def update(self):
# Delete all from Listbox bill
self.bill.delete(0, 'end')
# Add revised table into Listbox bill
for item in self.controller.tb1:
co = " ".join(str(x) for x in item)
self.bill.insert(END, co)
app = SeaofBTCapp()
app.mainloop()
When you select 2 duelist on the second screen the program shows a 3rd screen that should display 2 labels and 2 entry widgets for the user to enter the names of the players. But I can't seem to figure out why the widgets are not showing up. The section of code that involves this issue is the the block for the class TwoPlayer. Thank you!
import tkinter as tk
largeFont = ("Veranda", 18)
field1 = 'Duelist 1', 'Duelist 2'
names = []
class Yugioh_backEnd(tk.Tk):
#set default initializion
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
tk.Tk.wm_title(self, "YuGiOh Duel Calculator")
#containers
container = tk.Frame(self)
#set pack method for container
container.pack(side="top", fill="both", expand=True)
#set grid method for container
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
#selects which frame to show
self.frames = {}
for F in (StartPage, NumPlayers, TwoPlayer):
frame = F(container, self)
self.frames[F]=frame
frame.grid(row=0, column=0, sticky="nsew")
#show Frame
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)
#greet the user
greeting = tk.Label(self, text = "Welcome to\n YuGiOh Duel Calculator!", font = largeFont)
greeting.pack(pady=(10,40),padx=30)
#Enter the next window
lets_duel = tk.Button(self, text="Lets Duel!!!", command=lambda: controller.show_frame(NumPlayers))
lets_duel.pack(pady=(0,30),padx=30)
class NumPlayers(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
#prompt for players quantity
prompt1 = tk.Label(self, text = "How many duelist?", font = largeFont)
prompt1.pack(pady=(10,40),padx=30)
#Number of players
twoPlayers = tk.Button(self, text = "2 Duelists", command=lambda: controller.show_frame(TwoPlayer))
return1 = tk.Button(self, text="Return Home", command=lambda: controller.show_frame(StartPage))
#Add buttons to frame
return1.pack(pady=(0,30),padx=30)
twoPlayers.pack(pady=(0,10),padx=30)
#Two player mode
class TwoPlayer(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
def makeform(field1):
for field in field1:
row = tk.Frame()
lab = tk.Label(row, width=15, text=field, anchor='w')
ent = tk.Entry(row)
row.pack(side="top", padx=5, pady=5)
lab.pack(side="left")
ent.pack(side="right")
names.append((field, ent))
return names
if __name__ == ("__init__"):
ents = makeform(field1)
b1 = tk.Button(text='Show',
command=lambda: controller.show_frame(StartPage))
b1.pack(padx=5, pady=5)
app = Yugioh_backEnd()
app.mainloop()
I am trying to make a tkinter widow with multiple frames, but also the functions of notebook, like multiple widows. The problem is I am kind of unfamiliar with tkinter and am not sure how to do that. This is my current code, and it doesn't work, and would love to know what I should do to make it work. Again, the dream end result would be that I would have a first widow, which says the test text, and then the 2nd window which has multiple tabs.
from tkinter import ttk
import tkinter as tk
Font= ("Verdana", 8)
LargeFont = ("Verdana", 12)
class App(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
container = tk.Frame(self)
container.pack(side="top", fill="both", expand = True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (StartPage, PageOne):
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(StartPage)
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
class StartPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self,parent)
label = tk.Label(self, text="Info", font=LargeFont)
label.pack(pady=2,padx=10)
text = tk.Label(self, text="testtestestetetqwegfegeg\ntestwegwegwegweg", font=Font)
text.pack(pady=2,padx=2)
button = tk.Button(self, text="Go to the Card",
command=lambda: controller.show_frame(PageOne))
button.pack(fill="x")
class PageOne(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
nb = ttk.Notebook(ttk.Frame())
nb.grid(row=1, column=0, columnspan = 50, rowspan=49, sticky='nesw')
p1 = (nb)
nb.add(p1, text='test')
label = tk.Label(self, text="", font=LargeFont)
label.pack(pady=10,padx=10)
button1 = tk.Button(self, text="Back to Home",
command=lambda: controller.show_frame(StartPage))
button1.pack()
app = App()
app.mainloop()
The error that I eventually get is that it creates a third frame that is displayed with the test tab. Everything else works.
Thanks for your help
I know exactly what you mean because I'm trying the same. To me
nb = ttk.Notebook(self)
worked.
best
Pkanda
Taubate Brazil
So I have read a few posts on here and have tried them all. The current method I have attempted is storing the data in the controller:
class App(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
self.app_data = {"building": tk.StringVar()}
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()
I then have my PageOne receive input from user as to what building they want:
class PageOne(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
#buidling
bldg_label = ttk.Label(self, text="Building Name (ie. ACAD):", font=LARGE_FONT)
bldg_label.grid(row=0, column=0, padx=2, pady = 10)
self.bldg_entry =ttk.Entry(self,width = 6, textvariable = self.controller.app_data["building"])
self.bldg_entry.grid(row=0, column=1, padx=2, pady=10)
button1 = ttk.Button(self, text="next", command = lambda: controller.show_frame(PageTwo))
button1.grid(row = 1, column = 0)
Lastly I want to display the building they typed into the entry box into a label like so:
class PageTwo(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
bldg = self.controller.app_data["building"].get()
bldg_label = ttk.Label(self, text = "Building: " + str(bldg), font=LARGE_FONT)
bldg_label.grid(row = 0, column =0)
button1 = ttk.Button(self, text="Back to Home",
command=lambda: controller.show_frame(StartPage))
button1.grid(row = 1, column =0)
I know there needs to be some sort of updating but I just can't seem to get the right structure to make this work. The label prints: Building: with nothing in it. My question is how can I get the data that is stored in the dictionary to update the building label in the SecondPage? Any help would be greatly appreciated!