I am trying to create a simple Python 3.x GUI project with tkinter, just to learn the language better (I started learning Python not long ago), of which the only thing it does is switching between different pages as a button is clicked. The problem is that the objects are not getting in the center of the screen. What's wrong in my code?
Images:
Start Page
First Page
Second Page
import tkinter as tk
LARGE_FONT = ("verdana", 10)
class Application(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
container = tk.Frame(self)
container.grid()
self.frames = {}
for F in (StartPage, PageOne, PageTwo):
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="snew")
self.show_frame(StartPage)
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
class StartPage (tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label1 = tk.Label(self, text="Start Page", font=LARGE_FONT)
label1.grid(row=0, column=0)
button1 = tk.Button(self, text="Go to Page One",
command=lambda: controller.show_frame(PageOne))
button1.grid(row=1, column=0)
button2 = tk.Button(self, text="Go to Page Two",
command=lambda: controller.show_frame(PageTwo))
button2.grid(row=2, column=0)
class PageOne(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label2 = tk.Label(self, text="Page One", font=LARGE_FONT)
label2.grid(row=0, column=0, sticky="E")
button2 = tk.Button(self, text="Go to Page Two",
command=lambda: controller.show_frame(PageTwo))
button2.grid(row=1, column=0)
button3 = tk.Button(self, text="Go to Start Page",
command=lambda: controller.show_frame(StartPage))
button3.grid(row=2, column=0)
class PageTwo(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label2 = tk.Label(self, text="Page Two", font=LARGE_FONT)
label2.grid(row=0, column=0,sticky="E")
button2 = tk.Button(self, text="Go to Page One",
command=lambda: controller.show_frame(PageOne))
button2.grid(row=1, column=0)
button3 = tk.Button(self, text="Go to Start Page",
command=lambda: controller.show_frame(StartPage))
button3.grid(row=2, column=0)
app = Application()
app.title("Application")
app.mainloop()
I put a menu on the left with tkinter. Everything to the right of the menu is aligned in the middle. How to align to the right of the menu
There is a text on the back of the textbox, but because it is center-aligned, it crosses over the text and the text does not appear.
Tkinter program
All code:
from tkinter import *
from tkinter import messagebox
import tkinter.font as font
import tkinter as tkMessageBox
from typing import Sized
from PIL import ImageTk, Image
window = Tk()
window.title("Ogretmen+")
window.geometry("900x447")
window.configure(bg="#202020")
genelgorunumbaslik = font.Font(size=20)
menuyazilar = font.Font(size=20)
guncellemebuyuk = font.Font(size=15)
def sinifYonetimi():
sinifyonetimiaciklama.config(text="Sınıf yönetimi kısmına hoş geldiniz. Bu bölümden sınıf ekleyebilir ve silebilirsiniz. Örnek sınıf adı: 10 B")
sinifyonetimiaciklama.grid(row=1, column=2)
sinifadigir.config(text="Sınıf Adı:")
sinifadigir.grid(row=2, column=2)
sinifadientry.grid(row=2, column=2)
islemsec.grid_remove()
sinifyonetimiaciklama = Label(fg="white", bg="#202020")
sinifadigir = Label(fg="white", bg="#202020")
sinifadientry = Entry(bd=4)
menubuton2 = Button(text="Sınıf Yönetimi", fg="white", bg="#282528", height=3, command=sinifYonetimi)
menubuton3 = Button(text="Öğrenci Yönetimi", fg="white", bg="#282528", height=3)
menubuton4 = Button(text="Konu Takibi", fg="white", bg="#282528", height=3)
menubuton5 = Button(text="İletişim", fg="white", bg="#282528", height=2)
menubuton2['font'] = menuyazilar
menubuton3['font'] = menuyazilar
menubuton4['font'] = menuyazilar
menubuton5['font'] = menuyazilar
menubuton2.grid(row=1, column=1, sticky="ew")
menubuton3.grid(row=2, column=1, sticky="ew")
menubuton4.grid(row=3, column=1, sticky="ew")
menubuton5.grid(row=4, column=1, sticky="ew")
islemsec = Label(text="Lütfen sol menüden işlem seçiniz.", bg="#202020", fg="white")
islemsec.grid(row=1, column=3)
window.mainloop()
Related
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
Sorry about the layout of this question, my first time working with stackoverflow posts.
I want to make a GUI for Tic Tac Toe (Game menu). And have the abillity to put buttons where ever i want in the GUI so i used Grid.
import tkinter as tk
LARGE_FONT= ("Verdana", 12)
class SeaofBTCapp(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 (MainWindow, Game, Difficulty):
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 MainWindow(tk.Tk):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="Welcom to TIC TAC TOE", font=LARGE_FONT)
label.pack(pady=10, padx=10)
button1 = tk.Button(self, text="Start",
command=lambda: controller.show_frame(Game))
button1.pack()
button2 = tk.Button(self, text="Diffeculty",
command=lambda: controller.show_frame(Difficulty))
button2.pack()
button3 = tk.Button(self, text="Quit", command=self.Quit)
button3.pack()
label1 = tk.Label(self, text="Made by VindictaOG")
label1.pack()
def Quit(self):
exit()
class Game(tk.Tk):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
button1 = tk.Button(self, text="New Game")
button1.pack()
button2= tk.Button(self, text="Back to homescreen",
command=lambda: controller.show_frame(MainWindow))
button2.pack()
class Difficulty(tk.Tk):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
button1 = tk.Button(self, text="1V1", command=lambda: controller.show_frame(MainWindow))
button1.pack()
button2 = tk.Button(self, text="Back to homescreen",
command=lambda: controller.show_frame(Game))
button2.pack()
gui = SeaofBTCapp()
gui.mainloop()
But when i use grid i get this error:
Traceback (most recent call last):
File "/home/ivar/PycharmProjects/J1B2Afvink6/BKE.py", line 82, in <module>
gui = SeaofBTCapp()
File "/home/ivar/PycharmProjects/J1B2Afvink6/BKE.py", line 27, in __init__
frame.grid(row=0, column=0, sticky="nsew")
TypeError: wm_grid() got an unexpected keyword argument 'row'
I tried it with pack but that would not work, does someone know how to fix this?
Should inherit from tk.Frame instead of tk.Tk for MainWindow, Game and Difficulty. Also StartPage is not defined. #acw1668
Using (tk.Frame, tk.Tk) instead of just (tk.Tk) solved the problem.
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()
I would like to employ multiple frames in a GUI, where the page switches depending on the button clicked. I know that there's several threads already about this, and I've been looking at this one.
However, for my pages, I need different images on canvasses within each of my frames, so that when I raise a different frame, it comes with a new canvas and a new image on that canvas. I've tried a lot but I don't know how to get it to work so that the canvasses appear with their images.
Here's what I have so far, mostly copying from above link:
import tkinter as tk # python3
TITLE_FONT = ("Helvetica", 18, "bold")
class SampleApp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
# 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 = {}
self.frames["StartPage"] = StartPage(parent=container, controller=self)
self.frames["PageOne"] = PageOne(parent=container, controller=self)
self.frames["PageTwo"] = PageTwo(parent=container, controller=self)
self.frames["StartPage"].grid(row=0, column=0, sticky="nsew")
self.frames["PageOne"].grid(row=0, column=0, sticky="nsew")
self.frames["PageTwo"].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
self._canvas = tk.Canvas(parent, bg='white', width=900, height=3517, scrollregion=(0, 2800, 100, 800))
self._photo = tk.PhotoImage(file='images/homegraphic.gif')
self._canvas.create_image(0, 0, image=self._photo, anchor='nw')
label = tk.Label(self, text="This is the start page", font=TITLE_FONT)
label.pack(side="top", fill="x", pady=10)
button1 = tk.Button(self, text="Go to Page One",
command=lambda: controller.show_frame("PageOne"))
button2 = tk.Button(self, text="Go to Page Two",
command=lambda: controller.show_frame("PageTwo"))
button1.pack()
button2.pack()
class PageOne(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="This is page 1", font=TITLE_FONT)
label.pack(side="top", fill="x", pady=10)
button = tk.Button(self, text="Go to the start page",
command=lambda: controller.show_frame("StartPage"))
button.pack()
class PageTwo(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="This is page 2", font=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()
How do I get the canvas image to appear? I've spent a long time trying to figure this out and would appreciate any help!
The problem is here:
self._canvas = tk.Canvas(parent, ...)
Everything within a page needs to be a child of the page or one of its descendants.
It needs to be this:
self._canvas = tk.Canvas(self, ...)
i am trying out my first program and would appreciate if someone would tell me what is going on wrong. i wrote this program to pop up a screen with 4 choices and when i click on one of those choices it should switch screen to the next screen, please advice what did i wrote wrong because all what i am getting is the first screen then nothing when i click on the buttons thank you.
here is the program
import tkinter as tk
LARGE_FONT = ("Verdana", 12)
class SeaofBTCapp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
container = tk.Frame(self)
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)
btn1 = tk.Button(text="", fg="white", width=400, height=240, command=lambda : controller.show_frame(PageOne))
btn1["bg"] = "white"
mi = tk.PhotoImage(file="C:\\Python\\trials\\pic1.gif")
btn1.config(image=mi)
btn1.image = mi
btn2 = tk.Button(text="", fg="white", width=400, height=240, command=lambda: controller.show_frame(PageTwo))
btn2["bg"] = "white"
mi1 = tk.PhotoImage(file="C:\\Python\\trials\\safety.gif")
btn2.config(image=mi1)
btn2.image = mi1
btn3 = tk.Button(text="", fg="white", width=400, height=240)
btn3["bg"] = "white"
mi2 = tk.PhotoImage(file="C:\\Python\\trials\\count.gif")
btn3.config(image=mi2)
btn3.image = mi2
btn4 = tk.Button(text="", fg="white", width=400, height=240)
btn4["bg"] = "white"
mi3 = tk.PhotoImage(file="C:\\Python\\trials\\about.gif")
btn4.config(image=mi3)
btn4.image = mi3
btn1.grid(row=0, column=0, columnspan=1, sticky='EW')
btn2.grid(row=0, column=1, columnspan=1, sticky='EW')
btn3.grid(row=1, column=0, columnspan=1, sticky='EW')
btn4.grid(row=1, column=1, columnspan=1, sticky='Ew')
class PageOne(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="Page One!!!", font=LARGE_FONT)
label.grid(pady=10, padx=10)
button1 = tk.Button(self, text="Back to Home",
command=lambda: controller.show_frame(StartPage))
button1.grid()
button2 = tk.Button(self, text="Page Two",
command=lambda: controller.show_frame(PageTwo))
button2.grid()
class PageTwo(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="Page Two!!!", font=LARGE_FONT)
label.grid(pady=10, padx=10)
button1 = tk.Button(self, text="Back to Home",
command=lambda: controller.show_frame(StartPage))
button1.grid()
button2 = tk.Button(self, text="Page One",
command=lambda: controller.show_frame(PageOne))
button2.grid()
app = SeaofBTCapp()
app.mainloop()
You have 2 problems:
First, all of your Buttons need to have the first argument 'self'. You did this in some places but you forgot it in the StartPage class.
Second, you need to layout your container. Add a pack() after you initialize it:
container = tk.Frame(self)
container.pack()