PhotoImage Tkinter problem: Button not working and not displaying - python-3.x

im using Proxlight Designer to create Drag-n-drop GUI. It is a application that works with open-cv-python, but a Button is not displaying. It seems as if open-cv is the problem, because if you remove it the Button displays and works properly. Here is the code for the GUI:
cap = cv2.VideoCapture(0)
window = Tk()
window.geometry("700x800")
window.configure(bg = "#ffffff")
canvas = Canvas(
window,
bg = "#ffffff",
height = 800,
width = 700,
bd = 0,
highlightthickness = 0,
relief = "ridge")
canvas.place(x = 0, y = 0)
l1 = Label(bg = "black")
l1.place(x = 100, y = 150, width = 500, height = 500)
img0 = PhotoImage(file = f"RES/img1.png")
b0 = Button(
image = img0,
borderwidth = 0,
highlightthickness = 0,
command = save_face,
relief = "flat")
b0.place(
x = 250, y = 693,
width = 200,
height = 75)
img1 = PhotoImage(file = f"RES/img2.png")
b1 = Button(
image = img1,
borderwidth = 0,
highlightthickness = 0,
command = encryptPass,
relief = "flat")
b1.place(
x = 480, y = 693,
width = 200,
height = 75)
img2 = PhotoImage(file = f"RES/img3.png")
b2 = Button(
image = img2,
borderwidth = 0,
highlightthickness = 0,
command = generate_key,
relief = "flat")
b2.place(
x = 20, y = 693,
width = 200,
height = 75)
window.resizable(False, False)
while True:
img = cap.read()[1]
img1 = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img = ImageTk.PhotoImage(Image.fromarray(img1))
l1["image"] = img
window.update()

So thanks to the comments of #Matiiss and #acw1668 (thx alot btw) i got it to work. Basically the while loop was the problem. I fixed it using this instead of the while loop:
cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)
def show_frame():
_, frame = cap.read()
global cv2image
cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
img = Image.fromarray(cv2image)
imgtk = ImageTk.PhotoImage(image=img)
l1.imgtk = imgtk
l1.configure(image=imgtk)
l1.after(10, show_frame)
window = Tk()
window.geometry("700x800")
window.configure(bg = "#ffffff")
l1 = Label(bg = "black")
l1.place(x = 100, y = 150, width = 500, height = 500)
window.resizable(False, False)
show_frame()
window.mainloop()

Related

How can I scroll multiple frames in canvas?

I want to create a list of frames with further features like a button, label e.g.. but my issues are the size of the LabelFrame. If I put the LabelFrame in container it fits like I want to but it isn't scrollable any more. Any ideas?
from tkinter import ttk
import tkinter as tk
root = tk.Tk()
container = ttk.Frame(root)
canvas = tk.Canvas(container)
scrollbar = ttk.Scrollbar(container, orient="vertical", command=canvas.yview)
scrollable_frame = ttk.Frame(canvas)
scrollable_frame.bind(
"<Configure>",
lambda e: canvas.configure(
scrollregion=canvas.bbox("all")
)
)
canvas.create_window((0, 0), window=scrollable_frame, anchor="nw")
canvas.configure(yscrollcommand=scrollbar.set)
for i in range(50):
lf = ttk.Frame(scrollable_frame, text=i).grid(column=1, row=i)
frame_ip = tk.LabelFrame(lf, bg="white", text=i)
frame_ip.place(relwidth=0.95, relheight=0.2, relx=0.025, rely=0)
button_scroll1 = tk.Button(frame_ip, text="Start", bg="grey")
button_scroll1.place(relwidth=0.15, relx=0.025, relheight=0.15, rely=0.1)
container.pack()
canvas.pack(side="left", fill="both", expand=True)
scrollbar.pack(side="right", fill="y")
root.mainloop()
Here is your updated code with a Button, Canvas and Scrollbar inserted into each LabelFrame with grid manager.
I've also made the container resizable with row|column configure.
Seems to work fine.
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
root.rowconfigure(0, weight = 1)
root.columnconfigure(0, weight = 1)
root.geometry("341x448")
container = ttk.Frame(root)
container.rowconfigure(0, weight = 1)
container.columnconfigure(0, weight = 1)
canvas = tk.Canvas(container)
scrollbar = ttk.Scrollbar(container, orient = tk.VERTICAL, command = canvas.yview)
scrollable_frame = ttk.Frame(canvas)
scrollable_frame.bind(
"<Configure>",
lambda e: canvas.configure(
scrollregion=canvas.bbox("all")))
canvas.create_window((0, 0), window = scrollable_frame, anchor = tk.NW)
canvas.configure(yscrollcommand = scrollbar.set)
for i in range(15):
L = ttk.LabelFrame(scrollable_frame, text = "Sample scrolling label")
L.grid(row = i, column = 0, sticky = tk.NSEW)
B = ttk.Button( L, text = f"Button {i}")
B.grid(row = 0, column = 0, sticky = tk.NW)
K = tk.Canvas(
L, width = 300, height = 100,
scrollregion = "0 0 400 400", background = "#ffffff")
K.grid(row = 1, column = 0, sticky = tk.NSEW)
S = ttk.Scrollbar( L, command = K.yview)
S.grid(column = 1, row = 1, sticky = tk.NSEW)
K["yscrollcommand"] = S.set
container.grid(row = 0, column = 0, sticky = tk.NSEW)
canvas.grid(row = 0, column = 0, sticky = tk.NSEW)
scrollbar.grid(row = 0, column = 1, sticky = tk.NS)
root.mainloop()

TKinter Scrollbar - Problem with too many scrollbars

I am building a simple UI using Tkinter and running into a problem when adding scrollbars. The layout of my UI (as shown below) consists of 5 frames, with one frame having 3 sub-frames. I am trying to add scrollbars to each frame and the sub-frames, however when I add the last scroll-bar to the sub-frame, all of the frames become smaller than their designated size. This only occurs when the final scrollbar is added.
Code:
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
root.geometry("900x600")
notebook = ttk.Notebook(root)
frame1 = tk.Frame(root, width = 900, height = 600)
frame2 = tk.Frame(root, width = 900, height = 600)
frame3 = tk.Frame(root, width = 900, height = 600)
frame4 = tk.Frame(root, width = 900, height = 600)
frame5 = tk.Frame(root, width = 900, height = 600)
notebook.add(frame1, text = 'Frame 1')
notebook.add(frame2, text = 'Frame 2')
notebook.add(frame3, text = 'Frame 3')
notebook.add(frame4, text = 'Frame 4')
notebook.add(frame5, text = 'Frame 5')
canvas2 = tk.Canvas(frame2, width = 900, height = 600, scrollregion = (0, 0, 900, 600))
canvas3 = tk.Canvas(frame3, width = 900, height = 600, scrollregion = (0, 0, 900, 600))
canvas4 = tk.Canvas(frame4, width = 900, height = 600, scrollregion = (0, 0, 900, 600))
canvas5 = tk.Canvas(frame5, width = 900, height = 600, scrollregion = (0, 0, 900, 600))
canvas2.pack(side = tk.LEFT, fill = tk.BOTH, expand = 1)
canvas3.pack(side = tk.LEFT, fill = tk.BOTH, expand = 1)
canvas4.pack(side = tk.LEFT, fill = tk.BOTH, expand = 1)
canvas5.pack(side = tk.LEFT, fill = tk.BOTH, expand = 1)
et_vbar2 =tk.Scrollbar(canvas2, orient = tk.VERTICAL)
et_vbar2.pack(side = tk.RIGHT, fill = tk.Y)
et_vbar2.config(command=canvas2.yview)
canvas2.config(yscrollcommand = et_vbar2.set)
et_hbar2 =tk.Scrollbar(canvas2, orient = tk.HORIZONTAL)
et_hbar2.pack(side = tk.BOTTOM, fill = tk.X)
et_hbar2.config(command=canvas2.xview)
canvas2.config(xscrollcommand = et_hbar2.set)
et_vbar3 =tk.Scrollbar(canvas3, orient = tk.VERTICAL)
et_vbar3.pack(side = tk.RIGHT, fill = tk.Y)
et_vbar3.config(command=canvas3.yview)
canvas3.config(yscrollcommand = et_vbar3.set)
et_hbar3 =tk.Scrollbar(canvas3, orient = tk.HORIZONTAL)
et_hbar3.pack(side = tk.BOTTOM, fill = tk.X)
et_hbar3.config(command=canvas3.xview)
canvas3.config(xscrollcommand = et_hbar3.set)
et_vbar4 =tk.Scrollbar(canvas4, orient = tk.VERTICAL)
et_vbar4.pack(side = tk.RIGHT, fill = tk.Y)
et_vbar4.config(command=canvas4.yview)
canvas4.config(yscrollcommand = et_vbar4.set)
et_hbar4 =tk.Scrollbar(canvas4, orient = tk.HORIZONTAL)
et_hbar4.pack(side = tk.BOTTOM, fill = tk.X)
et_hbar4.config(command=canvas4.xview)
canvas4.config(xscrollcommand = et_hbar4.set)
et_vbar5 =tk.Scrollbar(canvas5, orient = tk.VERTICAL)
et_vbar5.pack(side = tk.RIGHT, fill = tk.Y)
et_vbar5.config(command=canvas5.yview)
canvas5.config(yscrollcommand = et_vbar5.set)
et_hbar5 =tk.Scrollbar(canvas5, orient = tk.HORIZONTAL)
et_hbar5.pack(side = tk.BOTTOM, fill = tk.X)
et_hbar5.config(command=canvas5.xview)
canvas5.config(xscrollcommand = et_hbar5.set)
notebook.pack()
notebook2 = ttk.Notebook(frame1)
tab1 = tk.Frame(frame1, width = 900, height = 600)
tab2 = tk.Frame(frame1, width = 900, height = 600)
tab3 = tk.Frame(frame1, width = 900, height = 600)
notebook2.add(tab1, text= 'Tab 1')
notebook2.add(tab2, text = 'Tab 2')
notebook2.add(tab3, text = 'Tab 3')
subcanvas1 = tk.Canvas(tab1, width = 900, height = 600, scrollregion = (0, 0, 900, 600))
subcanvas2 = tk.Canvas(tab2, width = 900, height = 600, scrollregion = (0, 0, 900, 600))
subcanvas3 = tk.Canvas(tab3, width = 900, height = 600, scrollregion = (0, 0, 900, 600))
subcanvas1.pack(side = tk.LEFT, fill = tk.BOTH, expand = 1)
subcanvas2.pack(side = tk.LEFT, fill = tk.BOTH, expand = 1)
subcanvas3.pack(side = tk.LEFT, fill = tk.BOTH, expand = 1)
subet_vbar1 =tk.Scrollbar(subcanvas1, orient = tk.VERTICAL)
subet_vbar1.pack(side = tk.RIGHT, fill = tk.Y)
subet_vbar1.config(command=subcanvas1.yview)
subcanvas1.config(yscrollcommand = subet_vbar1.set)
subet_hbar1 =tk.Scrollbar(subcanvas1, orient = tk.HORIZONTAL)
subet_hbar1.pack(side = tk.BOTTOM, fill = tk.X)
subet_hbar1.config(command=subcanvas1.xview)
subcanvas1.config(xscrollcommand = subet_hbar1.set)
subet_vbar2 =tk.Scrollbar(subcanvas2, orient = tk.VERTICAL)
subet_vbar2.pack(side = tk.RIGHT, fill = tk.Y)
subet_vbar2.config(command=subcanvas2.yview)
subcanvas2.config(yscrollcommand = subet_vbar2.set)
subet_hbar2 =tk.Scrollbar(subcanvas2, orient = tk.HORIZONTAL)
subet_hbar2.pack(side = tk.BOTTOM, fill = tk.X)
subet_hbar2.config(command=subcanvas2.xview)
subcanvas2.config(xscrollcommand = subet_hbar2.set)
subet_vbar3 =tk.Scrollbar(subcanvas3, orient = tk.VERTICAL)
subet_vbar3.pack(side = tk.RIGHT, fill = tk.Y)
subet_vbar3.config(command=subcanvas3.yview)
subcanvas3.config(yscrollcommand = subet_vbar3.set)
subet_hbar3 =tk.Scrollbar(subcanvas3, orient = tk.HORIZONTAL)
subet_hbar3.pack(side = tk.BOTTOM, fill = tk.X)
subet_hbar3.config(command=subcanvas3.xview)
subcanvas3.config(xscrollcommand = subet_hbar3.set)
notebook2.pack()
root.mainloop()
Is there a way to prevent every frame from becoming smaller after adding the scrollbars?
There's a number of problems in your code. Rather than try to fix them, I think you should cheat and use the code from someone who has abstracted this. There are many people who have made a scrolledframe in some form, including me. To use mine, download the DoubleScrolledFrame.py file from here and then:
import tkinter as tk
from tkinter import ttk
from DoubleScrolledFrame import DoubleScrolledFrame
def add_scrolled_frame(notebook, text):
"""do this in a function so that you can easily change parameters"""
frame = DoubleScrolledFrame(notebook, width = 900, height = 600)
notebook.add(frame, text = text)
return frame
root = tk.Tk()
notebook = ttk.Notebook(root)
frame1 = tk.Frame(root)
notebook.add(frame1, text = 'Frame 1')
frame2 = add_scrolled_frame(notebook, text = 'Frame 2')
frame3 = add_scrolled_frame(notebook, text = 'Frame 3')
frame4 = add_scrolled_frame(notebook, text = 'Frame 4')
frame5 = add_scrolled_frame(notebook, text = 'Frame 5')
notebook.pack()
notebook2 = ttk.Notebook(frame1)
tab1 = add_scrolled_frame(notebook2, text = 'Tab 1')
tab2 = add_scrolled_frame(notebook2, text = 'Tab 2')
tab3 = add_scrolled_frame(notebook2, text = 'Tab 3')
notebook2.pack()
# assuming you want widgets in these frames:
for i in range(30):
lbl = tk.Label(tab1, text=f'This is label number {i}')
lbl.pack()
root.mainloop()

Scrollbar not showing - tkinter

I have read threads on site to try to resolve this issue but nothing was found that I have not tried where it still does not work.
I am having a little trouble getting the scrollbar to show for my widgets. I have 2 scrollbars that have been written the same way for a Listbox and Text widget in another window and show and function perfectly but in this window the 2 scrollbars written will not display.
I have the code the same as the other functioning scrollbars in the other window but for some reason these 2 are not displaying.
They are placed at ingred and instruc
Some advice would be appreciated.
Code:
import os
import tkinter
from tkinter import *
window_3 = tkinter.Toplevel()
window_3.title('Recipes')
window_3.wm_iconbitmap('recipe.ico')
w = 1024
h = 612
ws = window_3.winfo_screenwidth()
hs = window_3.winfo_screenheight()
x = (ws/2) - (w/2)
y = (hs/2) - (h/2)
window_3.geometry('%dx%d+%d+%d' % (w, h, x, y))
window_3.title('Recipes')
Recipe_Selection = StringVar()
Dish_Type = StringVar()
Recipe = StringVar()
Cook_Time = StringVar()
Serves = StringVar()
ingred = StringVar()
instruct = StringVar()
dish_type = tkinter.Label(window_3, font=('Times 9 bold'), text='Category:', bg = "#FFD599", fg = '#9A0615')
dish_type.pack()
dish_type.place(x=210, y=125)
dish_type_entry = tkinter.Entry(window_3, textvariable=Dish_Type, width = 29, bg = "#FFD599", fg = '#9A0615', justify=CENTER)
dish_type_entry.place(x=275, y=126) recipe = tkinter.Label(window_3, font=('Times 9 bold'), text='Recipe:', bg = "#FFD599", fg = '#9A0615')
recipe.pack()
recipe.place(x=210, y=145)
recipe_entry = tkinter.Entry(window_3, textvariable=Recipe, width = 29, bg = "#FFD599", fg = '#9A0615', justify=CENTER)
recipe_entry.place(x=275, y=146)
serves = tkinter.Label(window_3, font=('Times 9 bold'), text='Serves:', bg = "#FFD599", fg = '#9A0615')
serves.pack()
serves.place(x=547, y=125)
serves_entry = tkinter.Entry(window_3, textvariable=Serves, width = 3, bg = "#FFD599", fg = '#9A0615', justify=CENTER)
serves_entry.place(x=623, y=126)
cook_time = tkinter.Label(window_3, font=('Times 9 bold'), text='Cook Time:', bg = "#FFD599", fg = '#9A0615')
cook_time.pack()
cook_time.place(x=547, y=145)
cook_time_entry = tkinter.Entry(window_3, textvariable=Cook_Time, width = 11, bg = "#FFD599", fg = '#9A0615', justify=CENTER)
cook_time_entry.place(x=623, y=146)
ingred = tkinter.Text(window_3, font=('Times 9'), height = 20, width=40, bd=1, bg = "#FFD599", fg = '#9A0615')
ingred.pack()
ingred.place(x=210, y=200)
yscroll = tkinter.Scrollbar(command=ingred.yview, orient=tkinter.VERTICAL)
yscroll.place(x=452, y=200)
ingred.configure(yscrollcommand=yscroll.set)
instruct = tkinter.Text(window_3, font=('Times 9'), height = 20, width=40, bd=1, bg = "#FFD599", fg = '#9A0615')
instruct.pack()
instruct.place(x=547, y=200)
yscroll = tkinter.Scrollbar(command=instruct.yview, orient=tkinter.VERTICAL)
yscroll.place(x=789, y=200)
instruct.configure(yscrollcommand=yscroll.set)
dish_type_entry.focus()
saveButton = tkinter.Button(window_3, text='Save Recipe', font='Times 9 bold italic', border = 1, height = 1, width = 14, bg = "#F9F8D6", fg = '#9A0615')##, command = Save)
saveButton.pack
saveButton.place(x=293, y=527)
clear1Button = tkinter.Button(window_3, text='Clear Page', font='Times 9 bold italic', border = 1, height = 1, width = 14, bg = "#F9F8D6", fg = '#9A0615')##, command = clear2)
clear1Button.pack
clear1Button.place(x=630, y=527)
backButton = tkinter.Button(window_3, text='Back', font='Times 9 bold italic', border = 1, height = 1, width = 14, bg = "#F9F8D6", fg = '#9A0615')##, command = close3)
backButton.pack
backButton.place(x=449, y=527)
window_3.mainloop()
You forgot to tell Scrollbar() about its master, so it naturally assumes it's root window. Do:
yscroll = Scrollbar(window_3, ... etc.
By the way, both ingred and instruct are associated with the same scrollbar: yscroll but I gather its just from cutting and pasting code. Also you define StringVar() instances with the same name as the text widgets.

getting a variable from one class to another class

i would like to get a variable from one of my classes to the another class.
the variable that i want to use is profile which is on line 129. i would like to use this variable outside of this class and into the class AddJob() down at the bottom of my code. it would much appreciated if anyone could possibly just give me a solution as i have been trying to get this to work for days.
import tkinter
import tkinter as tk
from tkinter import ttk
from tkinter import *
from tkinter import messagebox
from tkinter.scrolledtext import ScrolledText
import sqlite3
from sqlite3 import Error
import webbrowser
import re
Background = ("WHITE")
LARGE_FONT = ("Verdana", 9)
HOME_FONT = ("Times", 15, "bold")
EMAIL_FONT = ("times", 9)
def DataBase():
with sqlite3.connect("UserInfo.db") as db:
cursor = db.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS users(
userID INTEGER PRIMARY KEY,
username STRING,
password STRING,
firstname STRING,
surname STRING,
email STRING);
''')
cursor.execute ('''
CREATE TABLE IF NOT EXISTS jobs(
jobID INTEGER PRIMARY KEY,
userID
jobtitle STRING,
jobdescript STRING);
''')
class MsgBox(tkinter.Toplevel):
def __init__(self, title = "", message = ""):
tkinter.Toplevel.__init__(self)
self.title(title)
self.label = tkinter.Label(self, text = message)
self.label['bg'] = 'white'
self.label.pack(ipadx = 10, ipady = 10, fill = 'both', expand = True)
self.button = tkinter.Button(self, text = "OK")
self.button['command'] = self.destroy
self.button.pack(pady = 10, padx = 10, ipadx = 20, side = 'right')
class JobApp(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 = {}
#this is where you add a page to the program so you can add different functions
for F in (LoginPage, SignUp, HomePage, MenuPage, MapPage, ProfilePage, SettingsPage, JobsPage, AddJob):
frame = F(container, self)
self.frames[F] = frame
frame.grid(row = 0, column = 0, sticky = "nsew")
self.show_frame(LoginPage)
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
DataBase()
class LoginPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self,parent)
self.Logo = PhotoImage(file = "Logo.gif")
def Log_in():
with sqlite3.connect("UserInfo.db") as db:
cursor = db.cursor()
user = (self.UserEntry.get())
Pass = (self.PassEntry.get())
if user == "" or Pass == "":
msg = MsgBox("", "Make sure to fill all the boxes\nPlease try again")
msg.label['font'] = 'Verdana 10'
msg.button['text'] = 'Close'
msg.button.pack(expand = True)
else:
dictionary = {}
cursor.execute("SELECT username, password FROM users")
for pword in cursor.fetchall():
(key ,val) = tuple(pword)
dictionary[str(key)] = val
if user in dictionary:
if dictionary[user] == Pass:
sql = '''SELECT userID FROM users WHERE username = ?'''
cursor.execute(sql, (user,))
profile = cursor.fetchall()
controller.show_frame(HomePage)
self.UserEntry.delete(0, 'end')
self.PassEntry.delete(0, 'end')
else:
messagebox.showinfo("", "Enter the correct password")
self.PassEntry.delete(0, 'end')
self.logo = tk.Label(self, image = self.Logo)
self.User = tk.Label(self, text = "User Name:").place(x = 72, y = 130)
self.Pass = tk.Label(self, text = "Password:").place(x = 80, y = 155)
self.UserEntry = Entry(self)
self.PassEntry = Entry(self, show = '*')
self.login = ttk.Button(self, text = "Login", command = Log_in)
self.signup = ttk.Button(self, text = "Create account",
command = lambda:controller.show_frame(SignUp))
self.UserEntry.place(width = 100, height = 20, x = 140, y = 130)
self.PassEntry.place(width = 100, height = 20, x = 140, y = 155)
self.login.place(x = 80, y = 180)
self.signup.place(x = 160, y = 180)
self.logo.place(x = 110, y = 20)
class SignUp(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self,parent)
def Save_info():
DataBase()
with sqlite3.connect("UserInfo.db") as db:
cursor = db.cursor()
FnameEntry = self.FnameEntry.get()
SnameEntry = self.SnameEntry.get()
EmailEntry = self.EmailEntry.get()
UserNameEntry = self.UserNameEntry.get()
PassWordEntry = self.PassWordEntry.get()
RenterPasswordEntry = self.RenterPasswordEntry.get()
check = []
cursor.execute("SELECT * FROM users")
for row in cursor.fetchall():
check.append(row)
print (check)
if not re.match(r"[^#]+#[^#]+\.[^#]+", EmailEntry):
messagebox.showinfo("ERROR", "the email that you entered was not valid\nPlease try again")
if len(FnameEntry) == 0 or len(SnameEntry) == 0 or len(EmailEntry) == 0 or len(UserNameEntry) == 0 or len(PassWordEntry) == 0 or len(RenterPasswordEntry) == 0:
messagebox.showinfo("No fill", "You didn't fill all the fields")
else:
if len(UserNameEntry) < 6:
messagebox.showinfo("Not long enough", "your username wasn't long enough\nPlease try again")
else:
if len(PassWordEntry) < 6:
messagebox.showinfo("Not long enough", "Your password wasn't long enough\nPlease try again")
else:
if RenterPasswordEntry != PassWordEntry:
messagebox.showinfo("pass word match up", "Your passwords didn't seem to match up\nPlease try again")
else:
if UserNameEntry in check:
messagebox.showinfo("", "The user name that you entered already exsists\nPlease enter a different one")
self.UserNameEntry.delete(0, 'end')
self.PassWordEntry.delete(0, 'end')
self.RenterPasswordEntry.delete(0, 'end')
else:
YesNo = messagebox.askokcancel("Continue", "would you like to go back to the login page")
if YesNo == True:
self.FnameEntry.delete(0, 'end')
self.SnameEntry.delete(0, 'end')
self.EmailEntry.delete(0, 'end')
self.UserNameEntry.delete(0, 'end')
self.PassWordEntry.delete(0, 'end')
self.RenterPasswordEntry.delete(0, 'end')
cursor.execute("""
INSERT INTO users (username,password,firstname,surname,email)
VALUES (?, ?, ?, ?, ?)
""", (UserNameEntry, PassWordEntry, FnameEntry, SnameEntry, EmailEntry))
db.commit()
cursor.execute("SELECT * FROM users")
print(cursor.fetchall())
controller.show_frame(LoginPage)
self.x = ttk.Label(self, text = "fill in the information to create an account.\n\nBoxes with * next to them must be filled in.\nYour Username must be longer than 6 characters.\nYour password must be longer than 6 characters.\n", font = LARGE_FONT).grid(row = 0, column = 0, columnspan = 2)
self.Fname = ttk.Label(self, text = "First Name *:", font = LARGE_FONT).grid(row = 1, sticky = "e")
self.Sname = ttk.Label(self, text = "Surname *:", font = LARGE_FONT).grid(row = 2, sticky = "e")
self.Email = ttk.Label(self, text = "Email Address *:", font = LARGE_FONT).grid(row = 3, sticky = "e")
self.UserName = ttk.Label(self, text = "User name *:", font = LARGE_FONT).grid(row = 4, sticky = "e")
self.PassWord = ttk.Label(self, text = "Password *:", font = LARGE_FONT).grid(row = 5, sticky = "e")
self.ReneterPassword = ttk.Label(self, text = "Confirm password *:", font = LARGE_FONT).grid(row = 6, sticky = "e")
self.blank = ttk.Label(self, text = "").grid(row = 8)
Continue = ttk.Button(self, text = "Continue",
command = Save_info).grid(row = 9, rowspan = 2, stick = "e")
Cancel = ttk.Button(self , text = "Cancel",
command= lambda:controller.show_frame(LoginPage)).grid(row = 9, column = 1, stick = "w")
self.FnameEntry = Entry(self)
self.SnameEntry = Entry(self)
self.EmailEntry = Entry(self)
self.UserNameEntry = Entry(self)
self.PassWordEntry = Entry(self)
self.RenterPasswordEntry = Entry(self)
self.FnameEntry.grid(row = 1, column = 1, sticky = "w")
self.SnameEntry.grid(row = 2, column = 1, sticky = "w")
self.EmailEntry.grid(row = 3, column = 1, sticky = "w")
self.UserNameEntry.grid(row = 4, column = 1, sticky = "w")
self.PassWordEntry.grid(row = 5, column = 1, sticky = "w")
self.RenterPasswordEntry.grid(row = 6, column = 1, sticky = "w")
class HomePage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self,parent)
def on_entry_click(event):
if self.postcode.get() == 'Postcode':
self.postcode.delete(0, "end")
self.postcode.insert(0, '')
self.postcode.config(fg = 'black')
def on_focusout(event):
if self.postcode.get() == '':
self.postcode.delete(0, "end")
self.postcode.insert(0, 'Postcode')
self.postcode.config(fg = 'grey')
def on_entry_click2(event):
if self.searchjob.get() == 'Enter a job you want to search for..':
self.searchjob.delete(0, "end")
self.searchjob.insert(0, '')
self.searchjob.config(fg = 'black')
def on_focusout2(event):
if self.searchjob.get() == '':
self.searchjob.delete(0, "end")
self.searchjob.insert(0, 'Enter a job you want to search for..')
self.searchjob.config(fg = 'grey')
Homepagecanvas = Canvas(self, width = 320, height = 568)
Homepagecanvas.pack()
TopBarHome = Homepagecanvas.create_rectangle(0, 0, 320, 50, fill = 'light grey')
Home = Homepagecanvas.create_text((80, 25), text = "Home", font = HOME_FONT)
MenuButton = ttk.Button(self, text = "Menu",
command = lambda:controller.show_frame(MenuPage)).place(height = 40, width = 40, x = 5, y = 5)
self.postcode = Entry(self)
self.searchjob = Entry(self)
self.postcode.insert(0, 'Postcode')
self.postcode.bind('<FocusIn>', on_entry_click)
self.postcode.bind('<FocusOut>', on_focusout)
self.postcode.config(fg = 'grey')
self.postcode.place(width = 60, height = 30, x = 10, y = 60)
self.searchjob.insert(0, 'Enter a job you want to search for..')
self.searchjob.bind('<FocusIn>', on_entry_click2)
self.searchjob.bind('<FocusOut>', on_focusout2)
self.searchjob.config(fg = 'grey')
self.searchjob.place(width = 220, height = 30, x = 80, y = 60)
scrollbar = Scrollbar(self)
scrollbar.place(width = 10, height =
450, x = 10, y = 100)
Joblist = Listbox(self, yscrollcommand = scrollbar.set)
for line in range(100):
Joblist.insert(END, "This is line number " + str(line))
Joblist.place(height = 450, width = 280, x = 25, y = 100)
scrollbar.config(command = Joblist.yview)
class MenuPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self,parent)
Homepagecanvas = Canvas(self, width = 320, height = 568)
Homepagecanvas.pack()
TopBarHome = Homepagecanvas.create_rectangle(0, 0, 320, 50, fill = 'light grey')
Home = Homepagecanvas.create_text((40, 15), text = "Menu", font = HOME_FONT)
Home = Homepagecanvas.create_text((160, 35), text = "here you can navigate to other pages in the application")
Home = tk.Button(self,
text = "Home Page",
relief = GROOVE,
command = lambda:controller.show_frame(HomePage)).place(width = 100, height = 30, x = 10, y = 60)
Map = tk.Button(self,
text = "Map",
relief = GROOVE,
command = lambda:controller.show_frame(MapPage)).place(width = 100, height = 30, x = 10, y = 90)
Profile = tk.Button(self,
text = "Profile",
relief = GROOVE,
command = lambda:controller.show_frame(ProfilePage)).place(width = 100, height = 30, x = 10, y = 120)
Settings = tk.Button(self,
text = "Settings",
relief = GROOVE,
command = lambda:controller.show_frame(SettingsPage)).place(width = 100, height = 30, x = 10, y = 150)
Jobs = tk.Button(self,
text = "Jobs",
relief = GROOVE,
command = lambda:controller.show_frame(JobsPage)).place(width = 100, height = 30, x = 10, y = 180)
class MapPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self,parent)
MapPageCanvas = Canvas(self, width = 320, height = 568)
MapPageCanvas.pack()
TopBar = MapPageCanvas.create_rectangle(0, 0, 320, 50,
fill = 'light grey')
Home = MapPageCanvas.create_text((80, 25),
text = "Map",
font = HOME_FONT)
MenuButton = ttk.Button(self, text = "Menu",
command = lambda:controller.show_frame(MenuPage)).place(height = 40, width = 40, x = 5, y = 5)
class ProfilePage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self,parent)
def on_entry_click(event):
if self.postcode.get() == 'Postcode':
self.postcode.delete(0, "end")
self.postcode.insert(0, '')
self.postcode.config(fg = 'black')
def on_focusout(event):
if self.postcode.get() == '':
self.postcode.delete(0, "end")
self.postcode.insert(0, 'Postcode')
self.postcode.config(fg = 'grey')
ProfilePageCanvas = Canvas(self, width = 320, height = 568)
ProfilePageCanvas.pack()
TopBar = ProfilePageCanvas.create_rectangle(0, 0, 320, 50,
fill = 'light grey')
Profile = ProfilePageCanvas.create_text((80, 25), text = "Profile",
font = HOME_FONT)
MenuButton = ttk.Button(self, text = "Menu",
command = lambda:controller.show_frame(MenuPage)).place(height = 40, width = 40, x = 5, y = 5)
def logout():
result = messagebox.askokcancel("Logout", "would you like to logout")
if result == True:
controller.show_frame(LoginPage)
Logout = ttk.Button(self, text = "Logout",
command = logout).place(width = 60, height = 40, x = 255 , y = 5)
class SettingsPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self,parent)
MapPageCanvas = Canvas(self, width = 320, height = 568)
MapPageCanvas.pack()
TopBar = MapPageCanvas.create_rectangle(0, 0, 320, 50,
fill = 'light grey')
Home = MapPageCanvas.create_text((90, 25),
text = "Settings",
font = HOME_FONT)
MenuButton = ttk.Button(self, text = "Menu",
command = lambda:controller.show_frame(MenuPage)
).place(height = 40, width = 40, x = 5, y = 5)
def BG():
app.configure(background = Background)
def Toggle():
if DarkTheme.config('relief')[-1] == 'flat':
DarkTheme.config(relief = "sunken", bg = 'grey')
else:
DarkTheme.config(relief = "flat", bg = 'white')
Background = "DARK GRAY"
BG()
DarkTheme = tk.Button(self,
bg = 'white',
highlightbackground = 'black',
text = "Dark Theme",
pady = 5, padx = 5,
relief = "flat",
command = Toggle)
DarkTheme.place(x = 5, y = 60)
class JobsPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self,parent)
MapPageCanvas = Canvas(self, width = 320, height = 568)
MapPageCanvas.pack()
TopBar = MapPageCanvas.create_rectangle(0, 0, 320, 50,
fill = 'light grey')
Home = MapPageCanvas.create_text((80, 25),
text = "Jobs",
font = HOME_FONT)
MenuButton = ttk.Button(self, text = "Menu",
command = lambda:controller.show_frame(MenuPage)).place(height = 40, width = 40, x = 5, y = 5)
addjob = ttk.Button(self, text = "Add Job",
command = lambda:controller.show_frame(AddJob)).place(height = 40, width = 60, x = 255, y = 5)
class AddJob(tk.Frame, LoginPage):
def __init__(self, parent, controller):
tk.Frame.__init__(self,parent)
def dbAddJob():
JobT = self.Jt.get("1.0", 'end').rstrip('\n')
JobD = self.Jd.get("1.0", 'end').rstrip('\n')
with sqlite3.connect("UserInfo.db") as db:
cursor = db.cursor()
if JobT == "" or JobD == "":
messagebox.showinfo("Invalid","please fill in the boxes or cancel")
else:
aj = messagebox.askokcancel("Continue", "Job added click ok to continue\nor cancel or change what you have added")
if aj == True:
cursor.execute("""
INSERT INTO jobs (jobtitle, jobdescript)
VALUES (?, ?)
""", (JobT, JobD))
db.commit()
self.Jt.delete('1.0', END)
self.Jd.delete('1.0', END)
controller.show_frame(JobsPage)
cursor.execute("SELECT * FROM jobs")
print(cursor.fetchall())
MapPageCanvas = Canvas(self, width = 320, height = 568)
MapPageCanvas.pack()
TopBar = MapPageCanvas.create_rectangle(0, 0, 320, 50,
fill = 'light grey')
Home = MapPageCanvas.create_text((100, 25),
text = "Add a Job",
font = HOME_FONT)
MenuButton = ttk.Button(self, text = "Back",
command = lambda:controller.show_frame(JobsPage)).place(height = 40, width = 40, x = 5, y = 5)
self.Addjobbutton = ttk.Button(self, text = "Add",
command = dbAddJob).place(width = 60, height = 30, x = 90, y = 520)
self.Cancel = ttk.Button(self, text = "cancel",
command = lambda:controller.show_frame(JobsPage)).place(width = 60, height = 30, x = 170, y = 520)
self.Jt = ScrolledText(self)
self.Jd = ScrolledText(self)
self.Jt.place(height = 30, width = 310, x = 5, y = 60)
self.Jd.place(height = 400, width = 310, x = 5, y = 100)
app = JobApp()
app.geometry('320x568')
app.resizable(0,0)
app.mainloop()
Are you trying to make it a global variable such as ?
sound = None
class Cat(object):
global sound
"""
All your code
"""
sound = "meow"
Now if you use 'global sound' you can acces the global variable from everywhere, now sound returns:
>>> sound
'meow'
This way you can acces a variable from without a class or function.

Python 2 tkinter, a loan window appears when it has not been called for

I have come across an issue with using the tkinter message box, when a user of my application presses the English flag and then goes to Log-out in the top right hand corner a message box appears but also another box appears with the window title 'tk', I have not made or called any such window so my theory is that the window is coming from some place with the message box or maybe its something I have mistakenly done in my code which I cant see.
here is my code below;
import tkinter
from tkinter import *
from tkinter import messagebox as box
Title_Text = 25
Title_Font = "Courier"
Font = 'Ariel'
Rest_Text = 16
Background_Colour = 'Light blue'
def EngFlag():
print('Hello world')
def LogOut1():
response = box.askquestion ('?', 'Are You Sure?')
if response == 'yes':
try:
window.destroy()
except:
Eng_window.destroy()
def back1():
Home_Screen()
def Home_Screen():
global window
window = Tk()
window.geometry('1366x768')
window.configure(background = Background_Colour)
window.title('Local Languages Learning System')
window.resizable(width=False, height=False)
try:
Eng_window.destroy()
except:
pass
Title1 = Label(window, text = 'Local Languages Home Screen', bg = Background_Colour)
Title1.config(font=("Courier", Title_Text))
Title1.pack()
Title1.place(y = 1, x = 450)
Question_Label = Label(window, text = 'Please Pick The Language You Wish To Learn', bg = Background_Colour)
Question_Label.config(font=(Font, Rest_Text))
Question_Label.pack()
Question_Label.place(y = 200, x = 495)
Log_Out = Button(window, text = 'Log-Out', height = 1, width = 8, command = LogOut1)
Log_Out.pack()
Log_Out.place(y = 5, x = 1290)
help_btn = Button(window, text = 'Help', height = 1, width = 8, command = None)
help_btn.pack()
help_btn.place(y = 45, x = 1290)
English_Flag = PhotoImage(file = 'EnglishFlag.gif')
English_Flag_btn = Button(window, image = English_Flag, command = English_Home_Screen)
English_Flag_btn.pack(side = LEFT, padx = 10)
English_Flag_btn.place(y = 350, x = 300)
Polish_Flag = PhotoImage(file = 'PolishFlag.gif')
Polish_Flag_btn = Button(window, image = Polish_Flag, command = EngFlag)
Polish_Flag_btn.pack(side = LEFT, padx = 10)
Polish_Flag_btn.place(y = 350, x = 600)
Italian_Flag = PhotoImage(file = 'ItalianFlag.gif')
Italian_Flag_btn = Button(window, image = Italian_Flag, command = None)
Italian_Flag_btn.pack(side = LEFT, padx = 10)
Italian_Flag_btn.place(y = 350, x = 900)
window.mainloop()
def English_Home_Screen():
global Eng_window
Eng_window = Tk()
Eng_window.geometry('1366x768')
Eng_window.configure(background = Background_Colour)
Eng_window.title('Local Languages Learning System')
Eng_window.resizable(width=False, height=False)
window.destroy()
Title1 = Label(Eng_window, text = 'Local Languages\nEnglish Home Screen', bg = Background_Colour)
Title1.config(font=("Courier", Title_Text))
Title1.pack()
Title1.place(y = 1, x = 450)
Log_Out = Button(Eng_window, text = 'Log-Out', height = 1, width = 8, command = LogOut1)
Log_Out.pack()
Log_Out.place(y = 5, x = 1290)
Back = Button(Eng_window, text = 'Back', height = 1, width = 8, command = back1)
Back.pack()
Back.place(y = 5, x = 1210)
help_btn = Button(Eng_window, text = 'Help', height = 1, width = 8, command = None)
help_btn.pack()
help_btn.place(y = 45, x = 1290)
Play_all = Button(Eng_window, text = 'Play All Games', height = 2, width = 20, command = None)
Play_all.pack()
Play_all.place(y = 100, x = 320)
Multiple_Choice = Button(Eng_window, text = 'Play Multiple Choice Game', height = 2, width = 20, command = None)
Multiple_Choice.pack()
Multiple_Choice.place(y = 100, x = 510)
Picture = Button(Eng_window, text = 'Play Picture Game', height = 2, width = 20, command = None)
Picture.pack()
Picture.place(y = 100, x = 700)
Memory = Button(Eng_window, text = 'Play Memory Game', height = 2, width = 20, command = None)
Memory.pack()
Memory.place(y = 100, x = 890)
LeaderBoard = Button(Eng_window, text = 'LeaderBoard', height = 2, width = 20, command = None)
LeaderBoard.pack()
LeaderBoard.place(y = 160, x = 600)
Home_Screen()
Apologies for it being so long but to actually see the problem you have to have all the code. Any help or fixies would be great.
Now there are several issues with your code and some I will address.
First off what you are trying to do is very complicated when using a Non-OOP method. I have re-written your code as OOP to provide some ease of use and readability.
For the most part you should avoid using global the easiest way to do this is to use class attributes instead. This allows for you to have a variable that can be seen by any method within the class.
Some helpful tips:
Do not import tkinter twice.
Instead of doing:
import tkinter
from tkinter import *
from tkinter import messagebox as box
Do this instead:
import tkinter as tk
from tkinter import messagebox
Your Try/Except function will not work as you expect as Eng_window.destroy() will not return an error regardless of if the window is there or not. So it will always attempt to destroy Eng_window and never window
Instead do this:
# This will check if the instance of Eng_self_window exist first.
if tk.Toplevel.winfo_exists(self.Eng_self_window):
self.Eng_self_window.destroy()
else:
self.window.destroy()
Let me know if you have any questions on the class set up.
It can be done using global's but its not as clean and harder to deal with.
Here I have moved your code into a class and rearranged some stuff.
import tkinter as tk
from tkinter import messagebox
class Home_Screen(tk.Frame):
def __init__(self, parent, *args, **kwargs):
tk.Frame.__init__(self, parent, *args, **kwargs)
self.Title_Text = 25
self.Title_Font = "Courier"
self.Font = 'Ariel'
self.Rest_Text = 16
self.Background_Colour = 'Light blue'
self.window = parent
self.window.geometry('1366x768')
self.window.configure(background = self.Background_Colour)
self.window.title('Local Languages Learning System')
#self.window.resizable(width=False, height=False)
Title1 = tk.Label(self.window, text = 'Local Languages Home Screen', bg = self.Background_Colour)
Title1.config(font=("Courier", self.Title_Text))
Title1.pack()
Title1.place(y = 1, x = 450)
Question_Label = tk.Label(self.window, text = 'Please Pick The Language You Wish To Learn', bg = self.Background_Colour)
Question_Label.config(font=(self.Font, self.Rest_Text))
Question_Label.pack()
Question_Label.place(y = 200, x = 495)
Log_Out = tk.Button(self.window, text = 'Log-Out', height = 1, width = 8, command = self.LogOut1)
Log_Out.pack()
Log_Out.place(y = 5, x = 1290)
help_btn = tk.Button(self.window, text = 'Help', height = 1, width = 8, command = None)
help_btn.pack()
help_btn.place(y = 45, x = 1290)
self.English_Flag = tk.PhotoImage(file = 'EnglishFlag.gif')
self.English_Flag_btn = tk.Button(self.window, image = self.English_Flag, command = self.English_Home_Screen)
self.English_Flag_btn.pack(side = tk.LEFT, padx = 10)
self.English_Flag_btn.place(y = 350, x = 300)
self.Polish_Flag = tk.PhotoImage(file = 'PolishFlag.gif')
self.Polish_Flag_btn = tk.Button(self.window, image = self.Polish_Flag, command = self.EngFlag)
self.Polish_Flag_btn.pack(side = tk.LEFT, padx = 10)
self.Polish_Flag_btn.place(y = 350, x = 600)
self.Italian_Flag = tk.PhotoImage(file = 'ItalianFlag.gif')
self.Italian_Flag_btn = tk.Button(self.window, image = self.Italian_Flag, command = None)
self.Italian_Flag_btn.pack(side = tk.LEFT, padx = 10)
self.Italian_Flag_btn.place(y = 350, x = 900)
def English_Home_Screen(self):
self.Eng_self_window = tk.Toplevel(self.window)
self.Eng_self_window.geometry('1366x768')
self.Eng_self_window.configure(background = self.Background_Colour)
self.Eng_self_window.title('Local Languages Learning System')
#Eng_self.window.resizable(width=False, height=False)
Title1 = tk.Label(self.Eng_self_window, text = 'Local Languages\nEnglish Home Screen', bg = self.Background_Colour)
Title1.config(font=("Courier", self.Title_Text))
Title1.pack()
Title1.place(y = 1, x = 450)
Log_Out = tk.Button(self.Eng_self_window, text = 'Log-Out', height = 1, width = 8, command = self.LogOut1)
Log_Out.pack()
Log_Out.place(y = 5, x = 1290)
Back = tk.Button(self.Eng_self_window, text = 'Back', height = 1, width = 8, command = self.back1)
Back.pack()
Back.place(y = 5, x = 1210)
help_btn = tk.Button(self.Eng_self_window, text = 'Help', height = 1, width = 8, command = None)
help_btn.pack()
help_btn.place(y = 45, x = 1290)
Play_all = tk.Button(self.Eng_self_window, text = 'Play All Games', height = 2, width = 20, command = None)
Play_all.pack()
Play_all.place(y = 100, x = 320)
Multiple_Choice = tk.Button(self.Eng_self_window, text = 'Play Multiple Choice Game', height = 2, width = 20, command = None)
Multiple_Choice.pack()
Multiple_Choice.place(y = 100, x = 510)
Picture = tk.Button(self.Eng_self_window, text = 'Play Picture Game', height = 2, width = 20, command = None)
Picture.pack()
Picture.place(y = 100, x = 700)
Memory = tk.Button(self.Eng_self_window, text = 'Play Memory Game', height = 2, width = 20, command = None)
Memory.pack()
Memory.place(y = 100, x = 890)
LeaderBoard = tk.Button(self.Eng_self_window, text = 'LeaderBoard', height = 2, width = 20, command = None)
LeaderBoard.pack()
LeaderBoard.place(y = 160, x = 600)
def EngFlag(self):
print('Hello world')
def LogOut1(self):
response = messagebox.askquestion ('?', 'Are You Sure?')
if response == 'yes':
if tk.Toplevel.winfo_exists(self.Eng_self_window):
self.Eng_self_window.destroy()
else:
self.window.destroy()
def back1(self):
print("Go back")
self.Eng_self_window.destroy()
root = tk.Tk()
Home_Screen(root)
root.mainloop()
Quick fix; Don't use multiple instances of Tk. Instead, use Toplevel and hide & show the root window. Add:
...
Background_Colour = 'Light blue'
root = Tk()
root.withdraw()
...
and replace:
...
if response == 'yes':
try:
window.destroy()
except:
Eng_window.destroy()
...
global window
window = Tk()
...
global Eng_window
Eng_window = Tk()
with:
...
if response == 'yes':
root.destroy()
...
global window
window = Toplevel()
...
global Eng_window
Eng_window = Toplevel()

Resources