First lets fix your imports.
You are importing * and you should do import tkinter as tk
so you don't overwrite anything.
You are also importing DISABLED
and that is already imported from * so on the very next line you are already overwriting imports.
Next did major PEP8 clean up. This includes proper spacing between qualifiers, classes, functions, comments and so on as well as working on the max line length for coding.
Next we got rid of a lot of unneeded self
prefixes. You only need self when you have a class attribute or method you will need to use again in the code down the line.
Then we need to replace all you concatenation with format()
as format is the current correct method of concatenation.
One big save on rows is to build your Check Buttons into a list and then reference that list when writing your data.
One last change was to convert your Window1 class to be the root window through inheritance as well as convert Window2 to a Toplevel class. This allows us to use self.master
to work with the parent window.
I got your code down to 147 lines of code and I could probably get it down lower if I could do some testing. Take a look at the below and let me know if you have any questions.
I do have a question on this line:
account_list = [line.split(":", maxsplit=1) for line in open("passwords.txt")]
I am a fan of one liners however I think (I may be wrong) this remains open as you never tell it to close. I would instead load the file using a with open()
statement instead and then take the data and throw that into your one liner. The benefit to using with open()
is that once the work is complete it will auto close the connection/file.
I will be adding more detail to this answer when I get home but for now this should be a good start.
import tkinter as tk
import tkinter.ttk as ttk
from tkinter import messagebox
from PIL import Image, ImageTk, ImageGrab
from pathlib import Path
import pyautogui
import glob
import time
import os
def main():
Window1().mainloop()
def manual_open():
os.startfile('//SERVER/shared_data/Technical/Food Safety & Quality Manual/Section 21 -'
' Process Control/21.LABL.02 - Labelling notes.docx')
class Window1(tk.Tk):
def __init__(self):
super().__init__()
self.title("User Log In")
self.geometry('400x150')
frame = tk.Frame(self)
frame.pack(fill="both", expand=True)
tk.Label(frame, text="Username: ", font=("bold", 16)).pack()
self.entry_username = tk.Entry(frame, font=("bold", 14))
self.entry_username.pack()
tk.Label(frame, text="Password: ", font=("bold", 16)).pack()
self.entry_password = tk.Entry(frame, show="*", font=("bold", 14))
self.entry_password.pack()
tk.Button(frame, text="Login", font=("bold", 10), command=self._login_btn_clicked).pack()
def on_closing(self):
self.destroy()
def _login_btn_clicked(self):
username = self.entry_username.get()
password = self.entry_password.get()
account_list = [line.split(":", maxsplit=1) for line in open("passwords.txt")]
accounts = {key: value.rstrip() for key, value in account_list}
if accounts[username] == password:
self.withdraw()
self.app = Window2()
self.app.protocol("WM_DELETE_WINDOW", self.on_closing)
else:
messagebox.showinfo("User message", "Invalid username or password specified please try again")
class Window2(tk.Toplevel):
def __init__(self):
super().__init__()
notebook = ttk.Notebook(self.master)
notebook.pack(expand=1, fill="both")
main = ttk.Frame(notebook)
manual = ttk.Frame(notebook)
notebook.add(main, text='Main-Screen')
notebook.add(manual, text='Manual')
self.clock()
self.display_time = tk.Label(main)
self.display_time.grid(column=3, row=0)
self.username = self.master.entry_username.get()
tk.Label(main, text='User: {}'.format(self.username), font='15').grid(column=4, row=0)
self.checkbutton_list = []
checkbutton_verb = ["Ingredients present in full (any allergens in bold with allergen warning if necessary)",
"May Contain Statement.", "Cocoa Content (%).", "Vegetable fat in addition to Cocoa butter",
"Instructions for Use.", "Additional warning statements (pitt/stone, hyperactivity etc)",
"Nutritional Information Visible", "Storage Conditions", "Best Before & Batch Information",
"Net Weight & Correct Font Size.", "Barcode - Inner", "Address & contact details correct"]
for ndex, i in enumerate(checkbutton_verb):
x = tk.IntVar()
self.checkbutton_list.append([tk.Checkbutton(main, text=i, variable=x), x])
self.checkbutton_list[-1].grid(column=2, row=ndex+1, sticky='w')
directory = "//SERVER/shared_data/Technical/Label Sign Off Sheets/sign off project/To Sign"
choices = glob.glob(os.path.join(directory, "*- to sign.jpg"))
tk.Label(main, text="Choose here").grid(column=0, row=0)
tk.OptionMenu(main, self.tkvar, *choices, command=self.func).grid(row=1, column=0)
self.label2 = tk.Label(main, image=None)
self.label2.grid(row=2, column=0, rowspan=500)
tk.Button(main, text="Open", command=self.change_dropdown).grid(row=502, column=0)
self.dataSend = tk.Button(main, text="Send", command=self.var_states, state='disabled')
self.dataSend.grid(column=1, row=13, sticky='w')
self.CaptureScreen = tk.Button(main, text="PrintScreen", command=self.PrintScreen, state='disabled')
self.CaptureScreen.grid(column=1, row=14, sticky='w')
self.tkvar = tk.StringVar()
self.tkvar.set('...To Sign Off...')
self.manualBtn = tk.Button(manual, text="open doc", command=manual_open)
self.manualBtn.pack()
def clock(self):
t = time.strftime('%d/%m/%Y, %H:%M:%S, ', time.localtime())
if t != '':
self.display_time.config(text=t, font='times 15')
main.after(100, self.clock)
def print_screen(self):
pyautogui.keyDown('alt')
pyautogui.keyDown('printscreen')
pyautogui.keyUp('printscreen')
pyautogui.keyUp('alt')
self.dataSend['state'] = 'normal'
def var_states(self):
text_file = open("logfile.txt", "a")
formatted_string = 'Username: {}'.format(self.username)
for ndex, sub_list in enumerate(self.checkbutton_list):
formatted_string = '{}, Option {}: '.format(formatted_string, ndex+1, sub_list[1].get())
text_file.write(formatted_string)
text_file.close()
self.img = ImageGrab.grabclipboard()
self.img.save('//SERVER/shared_data/Technical/Label Sign Off Sheets/sign off project/Signed/{} {} .jpg'
.format(os.path.basename(self.p).strip('- to sign.jpg'), self.username), 'JPEG')
ed = '//SERVER/shared_data/Technical/Label Sign Off Sheets/sign off project/Signed/{} ed.jpg'\
.format(os.path.basename(self.p).strip('- to sign.jpg'))
nb = '//SERVER/shared_data/Technical/Label Sign Off Sheets/sign off project/Signed/{} Nb.jpg'\
.format(os.path.basename(self.p).strip('- to sign.jpg'))
jj = '//SERVER/shared_data/Technical/Label Sign Off Sheets/sign off project/Signed/{} jj.jpg'\
.format(os.path.basename(self.p).strip('- to sign.jpg'))
kl = '//SERVER/shared_data/Technical/Label Sign Off Sheets/sign off project/Signed/{} kl.jpg'\
.format(os.path.basename(self.p).strip('- to sign.jpg'))
if os.path.exists(ed) and os.path.exists(nb) or os.path.exists(jj) or os.path.exists(kl):
os.remove('//SERVER/shared_data/Technical/Label Sign Off Sheets/sign off project/To sign/{}'
.format(os.path.basename(self.p)))
else:
print("False")
def change_dropdown(self):
img = Image.open(self.tkvar.get())
photo = ImageTk.PhotoImage(img)
self.label2.image = photo
self.label2.configure(image=photo)
self.CaptureScreen['state'] = 'normal'
self.p = None
def func(self, value):
self.p = Path(value)
print(self.p)
if __name__ == '__main__':
main()