Python 3 tkinter insert file contents into a text box - python-3.x

Okay so I have done about 10 days of searching and I caved in so I'm turning to the community for help.
I am using python 3.6 and tkinter as a user interface.
The basic's of what I'm trying to accomplish is that I have a file that I open and search for a word within the file and insert all the lines that word falls on.
My issue is that its only inserting the first line it finds and I need it to insert all the lines it finds. Sorry for wet coding I'll dry it up once I have functionality later
here's a sample of my code (it's not the full thing but it should give you more than enough info about what I'm trying to accomplish):
import tkinter as tk
from tkinter import ttk
# i added all my imports that this class use's in case you guys think they could pose a problem but they shouldn't be a issue
class EXAMPLEapp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
tk.Tk.iconbitmap(self, default = "dlm64.ico")
tk.Tk.wm_title(self, "Example.")
self.FILE_MENU_BAR()
self.minsize(width = 360, height = 200)
container = tk.Frame(self)
container.grid(row=0,column=0, sticky="nsew")
container.grid_rowconfigure(0, weight = 1)
container.grid_columnconfigure(0, weight = 1)
self.frames = {}
for FRAME in (SearchPage):
frame = FRAME(container, self)
self.frames[FRAME] = frame
frame.grid(row = 0, column = 0, sticky = "nsew")
self.show_frame(SearchPage)
def FILE_MENU_BAR(self):
#File
self.menubar = tk.Menu()
self.configure(menu = self.menubar)
File_Menu = tk.Menu(self.menubar, tearoff = False)
self.menubar.add_cascade(label = "File", menu = File_Menu)
File_Menu.add_command(label = "EXIT" , command = self.File_EXIT)
# Edit Menu
Edit_Menu = tk.Menu(self.menubar, tearoff = False)
self.menubar.add_cascade(label = "Edit", menu = Edit_Menu)
Edit_Menu.add_command(label = "cut", underline = 2, command = self.Edit_Cut)
Edit_Menu.add_command(label = "copy", underline = 0, command = self.Edit_Copy)
def File_EXIT(self):
sys.exit(0)
def Edit_Cut(self):
print("CUT")
def Edit_Copy(self):
print("COPY")
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
class SearchPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text = "Search Inventory", font = ("Helvetica", 20, 'bold', 'underline'))
label.grid(row = 0, column = 1, sticky = "nsew", pady = (0,0), padx = (0,0))
button0 = ttk.Button(self, text = "Inventory Search")
button0.grid(row = 0, column = 0, sticky = "nsew", pady = 0, padx = (0,10))
button1 = ttk.Button(self, text = "New Inventory", command = lambda: controller.show_frame(CreatePage))
button1.grid(row = 1, column = 0, sticky = "nsew", pady = 0, padx = (0,10))
button2 = ttk.Button(self, text = "Edit Invetory", command = lambda: controller.show_frame(EditPage))
button2.grid(row = 2, column = 0, sticky = "nsew", pady = 0, padx = (0,10))
button3 = ttk.Button(self, text = "Ship", command = lambda: controller.show_frame(ShipPage))
button3.grid(row = 3, column = 0, sticky = "nsew", pady = 0, padx = (0,10))
button4 = ttk.Button(self, text = "Graph", command = lambda: controller.show_frame(PlotPage))
button4.grid(row = 4, column = 0, sticky = "nsew", pady = 0, padx = (0,10))
DATE_VAR = tk.StringVar()
def DATE_SEARCH():
USER_TEXT = DATE_VAR.get()
with open('SAMPLE.txt', 'r') as searchfile:
for line in searchfile:
if USER_TEXT == '':
LABEL = tk.Text(self, width = 30, height = 2, wrap = tk.WORD, foreground = 'red')
LABEL.grid(row = 6, column = 3, sticky = "nsew", pady = (0,0), padx = (20,0))
LABEL.insert(1.0, "PLEASE ENTER A VALUE")
LABEL.configure(state = 'disabled')
break
elif USER_TEXT in line:
LABEL = tk.Text(self, width = 100, height = 4, wrap = tk.WORD)
LABEL.grid(row = 6, column = 3, sticky = "e", pady = (0,0), padx = (20,0))
LABEL.insert(1.0, line)
LABEL.configure(state = 'disabled')
ScrollBar = tk.Scrollbar(self)
ScrollBar.config(command = LABEL.yview)
LABEL.config(yscrollcommand = ScrollBar.set)
ScrollBar.grid(row = 6, column = 4, sticky = "e")
break
else:
LABEL = tk.Text(self, width = 30, height = 2, wrap = tk.WORD, foreground = 'red')
LABEL.grid(row = 6, column = 3, sticky = "nsew", pady = (0,0), padx = (20,0))
LABEL.insert(1.0, "INVENTORY DOES NOT EXIST")
LABEL.configure(state = 'disabled')
DATE_Search_label = tk.Label(self, text = "Search by DATE", font = ("Helvetica", 9))
DATE_Search_label.grid(row = 5, column = 1, sticky = "nsew")
DATE_Search_Entry = tk.Entry(self, textvariable = DATE_VAR)
DATE_Search_Entry.grid(row = 6, column = 1, sticky = "nsew", pady = 0, padx = 2)
DATE_SEARCH_BUTTON = ttk.Button(self, text = "Search", command = DATE_SEARCH)
DATE_SEARCH_BUTTON.grid(row = 6, column = 2, sticky = "nsew")
app = EXAMPLEapp()
app.mainloop()

EDIT:
I have made several changes to your code.
There were way too many emblems with the way you had it set up.
As I am not 100% sure how what you are trying to accomplish I have made progress with your code.
Below is the edited version of your code.
I also created a text file on my end to test with and it seams to have worked so let me know if this is getting close to what you are attempting to do.
A few notes:
1st I moved everything into one class. The way you had it set up was just not going to work without some major changes.
2nd I needed to add self. to many of your variables because they are variables that we need to interact with in the class.
3rd I changed they way you get the data from the entry box. The way you were doing it was just not working so I simplified it by adding .get() function to the entry variable.
4th but probably should have been the 1st thing I mentions. The way you had your main Tk() window starting was odd. I changed how root was created and how we pass it into the class. This seams to make more sense to me.
This is much better to use IMO.
Let me know what parts you still need explanation on and I will make updates to my answer as needed.
Update:
change the while open statement a bit. You do not need to recreate the text box and reconfigure it ever for loop this is not good and will prevent you from seeing multiple items. Also I do not believe you can have a multi line label thought I have never tried. Lets change this to a text box this should do what we need.
import tkinter as tk
from tkinter import ttk
class EXAMPLEapp(tk.Frame):
def __init__(self, parent, *args, **kwargs):
tk.Frame.__init__(self, parent, *args, **kwargs)
self.root = parent
self.root.wm_title("TM Duch\'e Nut CO.")
self.FILE_MENU_BAR()
self.root.minsize(width = 360, height = 200)
self.container = tk.Frame(self.root)
self.container.grid(row=0,column=0, sticky="nsew")
self.container.grid_rowconfigure(0, weight = 1)
self.container.grid_rowconfigure(6, weight = 0)
self.container.grid_columnconfigure(0, weight = 1)
self.container.grid_columnconfigure(3, weight = 0)
self.label = tk.Label(self.root, text = "Search Inventory", font = ("Helvetica", 20, 'bold', 'underline'))
self.label.grid(row = 0, column = 1, sticky = "nsew", pady = (0,0), padx = (0,0))
self.button0 = ttk.Button(self.root, text = "Inventory Search")
self.button0.grid(row = 0, column = 0, sticky = "nsew", pady = 0, padx = (0,10))
self.button1 = ttk.Button(self.root, text = "New Inventory", command = lambda: controller.show_frame(CreatePage))
self.button1.grid(row = 1, column = 0, sticky = "nsew", pady = 0, padx = (0,10))
self.button2 = ttk.Button(self.root, text = "Edit Invetory", command = lambda: controller.show_frame(EditPage))
self.button2.grid(row = 2, column = 0, sticky = "nsew", pady = 0, padx = (0,10))
self.button3 = ttk.Button(self.root, text = "Ship", command = lambda: controller.show_frame(ShipPage))
self.button3.grid(row = 3, column = 0, sticky = "nsew", pady = 0, padx = (0,10))
self.button4 = ttk.Button(self.root, text = "Graph", command = lambda: controller.show_frame(PlotPage))
self.button4.grid(row = 4, column = 0, sticky = "nsew", pady = 0, padx = (0,10))
self.DATE_Search_label = tk.Label(self.root, text = "Search by DATE", font = ("Helvetica", 9))
self.DATE_Search_label.grid(row = 5, column = 1, sticky = "nsew")
self.DATE_Search_Entry = tk.Entry(self.root)
self.DATE_Search_Entry.grid(row = 6, column = 1, sticky = "nsew", pady = 0, padx = 2)
self.DATE_SEARCH_BUTTON = ttk.Button(self.root, text = "Search", command = lambda: self.DATE_SEARCH())
self.DATE_SEARCH_BUTTON.grid(row = 6, column = 2, sticky = "nsew")
def DATE_SEARCH(self):
with open('SAMPLE.txt', 'r') as f:
search_f = f.readlines()
self.text = tk.Text(self.root, width = 30, height = 2)
self.text.grid(row = 6, column = 3, sticky = "ew", pady = (0,0), padx = (20,0))
self.ScrollBar = tk.Scrollbar(self.root)
self.ScrollBar.config(command = self.text.yview)
self.text.config(yscrollcommand = self.ScrollBar.set)
self.ScrollBar.grid(row = 6, column = 4, sticky = "ns")
self.text.delete(1.0, "end-1c")
USER_TEXT = self.DATE_Search_Entry.get()
if USER_TEXT == '':
self.text.config(foreground = 'red')
self.text.insert(tk.END, "PLEASE ENTER A VALUE")
else:
match_in_file = False
for line in search_f:
if USER_TEXT in line:
self.text.config(foreground = 'black')
self.text.insert(tk.END, "{}".format(line))
match_in_file = True
if match_in_file == False:
self.text.config(foreground = 'red')
self.text.insert(tk.END, "INVENTORY DOES NOT EXIST")
def FILE_MENU_BAR(self):
#File
self.menu = tk.Menu(self.root)
self.root.config(menu = self.menu)
self.fileMenu = tk.Menu(self.menu, tearoff = 0)
self.menu.add_cascade(label = "File", menu = self.fileMenu)
self.fileMenu.add_separator()
self.fileMenu.add_command(label = "Exit", command = lambda: self.root.destroy())
# Edit Menu
self.Edit_Menu = tk.Menu(self.menu)
self.menu.add_cascade(label = "Edit", menu = self.Edit_Menu)
self.Edit_Menu.add_command(label = "cut", underline = 2, command = self.Edit_Cut)
self.Edit_Menu.add_command(label = "copy", underline = 0, command = self.Edit_Copy)
def File_EXIT(self):
sys.exit(0)
def Edit_Cut(self):
print("CUT")
def Edit_Copy(self):
print("COPY")
root = tk.Tk()
app = EXAMPLEapp(root)
app.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()

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()

How do I insert entries from a child window in MySQL with Python 3.6

I'm new to this site and to programming. Right now I'm facing a challenge: I have to insert the entries from a form into a MySQL table with Python 3.6.2. The window in question is dynamic, meaning that I can add or remove fields from it (obviously, the table in the database will not be modified accordingly).
What I really need is to capture some of the entries from the form (and omit repetitive ones like "Confirm password" and "Confirm email"), but also from Address 2 (which is optional).
Below I paste my code (some of it adapted from this site). I omitted the SQL query because I don't know where I should place it. The data I need are those from "def create_window2()".
Thanks in advance.
import tkinter as tk
import MySQLdb
from tkinter import *
class MainWindow(tk.Frame):
counter = 0
def create_window2(self):
t = tk.Toplevel(self)
t.focus_force()
t.wm_title("New Customer Registration")
fields = ("Username*", "Password*", "Confirm password*", "First
Name*", "Last Name*", "Address 1*", "Address 2
(optional)", "Town/City", "Telephone Number*", "Email
address*", "Confirm email*")
def fetch(entries):
for entry in entries:
field = entry[0]
text = entry[1].get()
print('%s: "%s"' % (field, text))
def makeform(t, fields):
entries = []
for field in fields:
row = Frame(t)
label = Label(row, width = 20, text = field, anchor = 'w')
entry = Entry(row, width = 25)
row.pack(side = TOP, padx = 5, pady = 5)
label.pack(side = LEFT)
entry.pack(side = LEFT)
entries.append((field, entry))
return entries
if __name__ == '__main__':
root = t
root.geometry('+520+120')
ents = makeform(root, fields)
wm_button1 = Button(root, text = "Register", width = 15,
command = t.register)
wm_button1.pack(side = LEFT, padx = 35, pady = 5)
wm_button2 = Button(root, text = "Cancel", width = 15,
command = t.destroy)
wm_button2.pack(side = LEFT, padx = 10, pady = 5)
root.bind('<Return>', (lambda event, e = ents: fetch(e)))
root.mainloop()
This should get you started, although there is obviously more to do. This program uses instance objects/variables so you don't return values from functions as instance objects are usable anywhere in the class. Also, I am using grid() instead of pack() but that is just personal preference.
import tkinter as tk
##import MySQLdb
## from tkinter import * import tkinter once only
class MainWindow():
##counter = 0
def __init__(self, root):
self.t = tk.Toplevel(root)
self.t.geometry('+1000+10')
self.t.focus_force()
self.t.wm_title("New Customer Registration")
self.fields = ("Username*", "Password*", "Confirm password*",
"First Name*", "Last Name*", "Address 1*",
"Address 2 optional)", "Town/City", "Telephone Number*",
"Email address*", "Confirm email*")
self.entries=[]
self.makeform()
wm_button1 = tk.Button(root, text = "Register", width = 15,
command = self.fetch)
wm_button1.grid(row=1, column=0)
wm_button2 = tk.Button(root, text = "Cancel", width = 15,
command = self.t.destroy)
wm_button2.grid(row=2, column=0)
def fetch(self):
for entry in self.entries:
field = entry[0]
text = entry[1].get()
print('%s: "%s"' % (field, text))
##update to MariaDB would go here
self.input_frame.destroy()
self.makeform()
print("-"*50)
def makeform(self):
##use a Frame that will be destroyed
self.input_frame=tk.Frame(self.t)
self.input_frame.grid()
self.entries=[]
this_row=0
for field in self.fields:
label = tk.Label(self.t, width = 20, text = field, anchor = 'w')
entry = tk.Entry(self.t, width = 25)
label.grid(row=this_row, column=0, sticky="nsew")
entry.grid(row=this_row, column=1, sticky="nsew")
this_row += 1
self.entries.append((field, entry))
## change "fields" so it won't ask for Name & Password
self.fields = ("First Name*", "Last Name*", "Address 1*",
"Address 2 (optional)", "Town/City", "Telephone Number*",
"Email address*", "Confirm email*")
## not necessary, entires is an instance object
## return entries
if __name__ == '__main__':
root = tk.Tk()
root.geometry('+1000+300')
MW=MainWindow(root)
root.mainloop()
import tkinter as tk
import MySQLdb
from tkinter import *
class MainWindow(tk.Frame):
counter = 0
def __init__(self, *args, **kwargs):
tk.Frame.__init__(self, *args, **kwargs)
self.background = tk.PhotoImage(file = "D:\\UoB\\Herb\\water1.png")
self.back_label = tk.Label(self, image = self.background)
self.back_label.place(x = 0, y = 0, relwidth = 1, relheight = 1)
self.button1 = tk.Button(self, text = "Customer Login", width = 20, command=self.create_window1)
self.button1.place(relx = 0.5, rely = 0.20, anchor = CENTER)
self.button2 = tk.Button(self, text = "New Customer", width = 20, command=self.create_window2)
self.button2.place(relx = 0.5, rely = 0.40, anchor = CENTER)
self.button3 = tk.Button(self, text = "Driver", width = 20,command = self.create_window3)
self.button3.place(relx = 0.5, rely = 0.60, anchor = CENTER)
self.button4 = tk.Button(self, text = "Administrator", width = 20, command=self.create_window4)
self.button4.place(relx = 0.5, rely = 0.80, anchor = CENTER)
def create_window1(self):
t = tk.Toplevel(self)
t.focus_force()
t.wm_title("Customer Login")
t.geometry("380x180+535+275")
wm_labelText = StringVar()
wm_labelText.set("Username")
wm_labelUser = Label(t, textvariable = wm_labelText)
wm_labelUser.place(x = 20, y = 30)
username = StringVar(None)
user = Entry(t, textvariable = username, width = 30)
user.place(x = 100, y = 30)
wm_passwText = StringVar()
wm_passwText.set("Password")
wm_labelPass = Label(t, textvariable = wm_passwText)
wm_labelPass.place(x = 20, y = 65)
password = StringVar(None)
passw = Entry(t, textvariable = password, width = 30, show = "*")
passw.place(x = 100, y = 65)
wm_button1 = tk.Button(t, text = "Login", width = 15)
wm_button1.place(x = 30, y = 115)
wm_button2 = tk.Button(t, text = "Cancel", width = 15, command = t.destroy)
wm_button2.place(x = 210, y = 115)
def create_window2(self):
t = tk.Toplevel(self)
t.focus_force()
t.wm_title("New Customer Registration")
fields = ("Username*", "Password*", "Confirm password*", "First Name*", "Last Name*", "Address 1*", "Address 2", "Town/City", "Telephone Number*", "Email address*", "Confirm email*")
def fetch(entries):
for entry in entries:
field = entry[0]
text = entry[1].get()
print('%s: "%s"' % (field, text))
def makeform(t, fields):
entries = []
for field in fields:
row = Frame(t)
label = Label(row, width = 20, text = field, anchor = 'w')
entry = Entry(row, width = 25)
row.pack(side = TOP, padx = 5, pady = 5)
label.pack(side = LEFT)
entry.pack(side = LEFT)
entries.append((field, entry))
return entries
if __name__ == '__main__':
root = t
root.geometry('+520+120')
ents = makeform(root, fields)
label_new = Label(root, text = "All fields marked with * are mandatory")
label_new.config(font = ('times', 10, 'bold'))
label_new.pack()
wm_button1 = Button(root, text = "Register", width = 15, command = t.register)
wm_button1.pack(side = LEFT, padx = 35, pady = 5)
wm_button2 = Button(root, text = "Cancel", width = 15, command = t.destroy)
wm_button2.pack(side = LEFT, padx = 10, pady = 5)
root.bind('<Return>', (lambda event, e = ents: fetch(e)))
root.mainloop()
def create_window3(self):
t = tk.Toplevel(self)
t.focus_force()
t.wm_title("Driver Login")
t.geometry("380x180+535+275")
wm_labelText = StringVar()
wm_labelText.set("Username")
wm_labelUser = Label(t, textvariable = wm_labelText)
wm_labelUser.place(x = 20, y = 30)
username = StringVar(None)
user = Entry(t, textvariable = username, width = 30)
user.place(x = 100, y = 30)
wm_passwText = StringVar()
wm_passwText.set("Password")
wm_labelPass = Label(t, textvariable = wm_passwText)
wm_labelPass.place(x = 20, y = 65)
password = StringVar(None)
passw = Entry(t, textvariable = password, width = 30, show = "*")
passw.place(x = 100, y = 65)
wm_button1 = tk.Button(t, text = "Login", width = 15)
wm_button1.place(x = 35, y = 115)
wm_button2 = tk.Button(t, text = "Cancel", width = 15, command = t.destroy)
wm_button2.place(x = 215, y = 115)
def create_window4(self):
t = tk.Toplevel(self)
t.focus_force()
t.wm_title("Administrator Login")
t.geometry("380x180+535+275")
wm_labelText = StringVar()
wm_labelText.set("Username")
wm_labelUser = Label(t, textvariable = wm_labelText)
wm_labelUser.place(x = 20, y = 30)
username = StringVar(None)
user = Entry(t, textvariable = username, width = 30)
user.place(x = 100, y = 30)
wm_passwText = StringVar()
wm_passwText.set("Password")
wm_labelPass = Label(t, textvariable = wm_passwText)
wm_labelPass.place(x = 20, y = 65)
password = StringVar(None)
passw = Entry(t, textvariable = password, width = 30, show = "*")
passw.place(x = 100, y = 65)
wm_button1 = tk.Button(t, text = "Login", width = 15)
wm_button1.place(x = 30, y = 115)
wm_button2 = tk.Button(t, text = "Cancel", width = 15, command = t.destroy)
wm_button2.place(x = 210, y = 115)
if __name__ == "__main__":
root = tk.Tk()
main = MainWindow(root)
root.iconphoto( root, PhotoImage( file="D:\\UoB\\Herb\\bubbles.png" ) )
root.title( "Welcome to Sky Laundry" )
root.geometry( "400x400+525+175" )
main_menu = Menu( root, tearoff=0 )
main_menu.add_command( label="Quit", command = root.destroy )
root.config( menu = main_menu )
main.pack(side = "top", fill = "both", expand = True)
root.mainloop()

tkinter report frame as well as mouse coordinates

def mouse_click(event):
#'reports' to both terminal and results text box
parent_name = Frame.winfo_parent(root)
parent = Frame._nametowidget(parent_name)
result = ("{0}: {1},{2}\n ".format('Clicked at', event.x, event.y))
print('clicked at',parent, event.x, event.y)
from tkinter import *
root = Tk()
root.title("Change Text")
root.geometry('700x500')
top=root.winfo_toplevel()
for rn in range(0,9): # rn = row number
top.rowconfigure(rn, weight=1)
top.rowconfigure(rn, weight=0)
for cn in range(0,5): # cn = column number
top.columnconfigure(cn, weight=1)
# FRAME 1
frame1 = Frame(root, borderwidth = 2, background = '#EFE0CD', relief = RIDGE,width = 25, height = 20)
frame1.bind("<Button-1>", mouse_click)
frame1.grid(column = 0, row = 0, columnspan = 2, rowspan = 3, sticky = N+S+E+W)
frame1_lbl = Label(frame1, text='Frame 1', font='comic-sans-MS 10 ', fg ='red', bg = '#EFE0CD')
frame1_lbl.grid(row=0, column =0)
# FRAME 2
frame2 = Frame(root, borderwidth = 2, background = '#CCC6B0', relief = RIDGE,width = 25, height = 20)
frame2.bind("<Button-1>", mouse_click)
frame2.grid(column = 0, row = 3, columnspan = 2, rowspan = 3, sticky = N+S+E+W)
frame2_lbl = Label(frame2, text='Frame 2', font='comic-sans-MS 10', fg ='red', bg = '#CCC6B0')
frame2_lbl.grid(row=0, column =0,)
root.mainloop()
I know that this is a really dumb question. How do I identify the Frame in which the mouse is clicked so that report prints clicked frame1 or frame2 at x y coordinates?. I found a bit about using winfo_parent but have obviously not used it properly.
Thank you
The event object that is passed in to the callback has a widget attribute which is a reference to the widget that got the event. So, event.widget is what you want to print.

Resources