Python Forum

Full Version: Partial using Tkinter function
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
Hi guys! I have this program which displays the time. The time is updated via a multiprocessing Process() which is targeted at a partial. However, the partial's function is supposed to set the value of a tkinter StringVar(). But, I get this error:

Error:
Exception in Tkinter callback Traceback (most recent call last): File "C:\Users\joshu\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 1883, in __call__ return self.func(*args) File "C:/Users/joshu/Downloads/OrderLog.py", line 198, in sign_in_func main_app() File "C:/Users/joshu/Downloads/OrderLog.py", line 1074, in main_app time_process.start() File "C:\Users\joshu\AppData\Local\Programs\Python\Python38-32\lib\multiprocessing\process.py", line 121, in start self._popen = self._Popen(self) File "C:\Users\joshu\AppData\Local\Programs\Python\Python38-32\lib\multiprocessing\context.py", line 224, in _Popen return _default_context.get_context().Process._Popen(process_obj) File "C:\Users\joshu\AppData\Local\Programs\Python\Python38-32\lib\multiprocessing\context.py", line 326, in _Popen return Popen(process_obj) File "C:\Users\joshu\AppData\Local\Programs\Python\Python38-32\lib\multiprocessing\popen_spawn_win32.py", line 93, in __init__ reduction.dump(process_obj, to_child) File "C:\Users\joshu\AppData\Local\Programs\Python\Python38-32\lib\multiprocessing\reduction.py", line 60, in dump ForkingPickler(file, protocol).dump(obj) TypeError: cannot pickle '_tkinter.tkapp' object
I'm using PyCharm as my editor.

The code:

now = datetime.datetime.now()

    time_var = StringVar()

    time_set_partial = partial(time_var.set, str(now.hour) + ":" + str("%02d" % now.minute).format(1))
    time_process = Process(target = time_set_partial)
    time_process.start()

    time_of_day = Label(textvariable = time_var)
    time_of_day.pack() 
I think the issue lies somewhere within the time_set_partial = partial(time_var.set, str(now.hour) + ":" + str("%02d" % now.minute).format(1)) line but I'm not sure.

I would be grateful if anyone can help : Smile.
Here is one without using partial.
#! /usr/bin/env python3
import datetime as dt
import multiprocessing as mp
import tkinter as tk


def display(q):
    now = dt.datetime.now()
    q.put(now)


if __name__ == '__main__':
    ctx = mp.get_context('spawn')
    q = ctx.Queue()
    p = ctx.Process(target=display, args=(q,))
    p.start()
    # print(format(q.get(), '%H:%M:%S'))
    root = tk.Tk()
    label = tk.Label(root, text=format(q.get(), "%H:%M:%S"))
    label.pack()
    root.mainloop()
    p.join()
But how do I do it with a partial? I'd imagine that would use less memory

Thanks for the reply tho

In your code, where do you reference the StringVar()?
Here is one that uses all of what you want

#! /usr/bin/env python3
import datetime as dt
import multiprocessing as mp
import tkinter as tk
from datetime import datetime as dt
from functools import partial


if __name__ == '__main__':
    root = tk.Tk()
    root.geometry('200x200+150+150')
    myvar = tk.StringVar()
    ctx = mp.get_context('spawn')
    q = ctx.Queue()
    p = ctx.Process(target=partial(q.put, myvar.set(f'{format(dt.now(),"%H:%M:%S")}')))
    p.start()
    label = tk.Label(textvariable=myvar)
    label.pack()
    p.join()

    root.mainloop()
Thanks

Still doesn't work
Works for me. What does it not do?
It doesn't update. It shows the time but it's like that for eternity

Even with my original code it showed the time. It just never updated

New code. Error-free, but doesn't update

    now = datetime.datetime.now()

    time_of_day = Label(text = str(now.hour) + ":" + str("%02d" % now.minute).format(1))
    time_of_day.pack()

Full code

#change back to appicon.ico

from tkinter import *
from tkinter import messagebox
from tkinter import filedialog
from tkinter.ttk import Button, Notebook, Combobox
import os
import sys
import getpass
import smtplib
import webbrowser
import urllib.request
from statistics import multimode
import datetime

def AddCall():
    add()

def BackupCallSave():
    savefile()

def ViewCall():
    viewfile()

def PrintFileCall():
    printfile()

def ShareListCall():
    mailInstance = MailWin()

def SettingsInstance():
    settingsInstance = Settings()

def HTMLDataInstance():
    createData = HTMLRawData()

def CategoryInstance():
    newCategorySettings = SetCategory()

def ViewCategoryInstance():
    newCategoryViewer = ViewCategory()

def SearchInstance():
    newSearch = SearchWin()

def EditSelectionInstance():
    newEdit = EditSelection()

account = open("account.txt", "a+")
account.close()

login_details_user = open("loginuser.txt", "a+")
login_details_user.close()

login_details_user = open("loginuser.txt", "r")
check_char = login_details_user.read()
login_details_user.close()

login_details_passw = open("loginpassw.txt", "a+")
login_details_passw.close()

shop_name_details = open("shopnamecontainer.txt", "a+")
shop_name_details.close()

web_url = open("shopwebsite.txt", "a+")
web_url.close()

check_used = open("usedfiles.txt", "a+")
check_used.close()

save_file = open("saves.txt", "a+")
save_file.close()

if check_char == "":
    account = open("account.txt", "w")
    account.write("0")
    account.close()

window = Tk()
window.title("OrderLog")
window.iconbitmap("feather.ico")
window.resizable(0, 0)

itemsvar = Variable(value = 1)
itembox = Entry(width = 50)
itemslist = Listbox(listvariable = itemsvar)
no_items_label = Label(text = "No products")
file = ""
session = 0
no_items = True
used_file = False
shop_name = ""
validate_user = ""
validate_passw = ""
target_set = False
signed_in = False
file_was_viewed = False
url_set = False

categories = ["Food", "Confectionery", "Dairy", "Fruit & Vegetables", "Meat, Fish & Chicken", "DIY", "Other"]

food_category_list = []
confectionery_category_list = []
dairy_category_list = []
fruit_veg_category_list = []
meat_fish_chicken_category_list = []
diy_category_list = []
other_category_list = []

account = open("account.txt", "r+")

status = account.read()

menubar = Menu()
menubar.add_command(label = "Add", state = DISABLED, command = AddCall)
menubar.add_command(label = "Backup", state = DISABLED, command = BackupCallSave)
menubar.add_command(label = "Print", state = DISABLED, command = PrintFileCall)
menubar.add_command(label = "Email", state = DISABLED, command = ShareListCall)
menubar.add_command(label = "Search", state = DISABLED, command = SearchInstance)
menubar.add_command(label = "View", command = ViewCall)

edit = Button(window, text = "Edit", state = DISABLED, command = EditSelectionInstance)

def closeall():
    global signed_in
    if signed_in == False:
        try:
            sys.exit()
        except:
            raise SystemExit()
    else:
        exitq = messagebox.askquestion("Exit program", "Are you sure you want to exit OrderLog?")
        if exitq == "yes":
            try:
                sys.exit()
            except:
                raise SystemExit()
        else:
            return

def error_handle():
    messagebox.showerror("An error occured", "An error occurred while setting the target file. Please set it again")
    file = ""

def spacer(linesno):
    for i in range(0, linesno):
        space = Label(text = "")
        space.pack()

def notebookspacer(linesno, tabmaster):
    for i in range(0, linesno):
        space = Label(tabmaster, text = "")
        space.pack()

def create_account_func():
    user = username.get()
    passw = password.get()
    if len(user and passw) == 0:
        messagebox.showerror("Fields missing", "Please fill out all required fields")
        pass
    else:
        if len(user and passw) < 10:
            messagebox.showerror("Username and password", "Username and password must be 10 characters or over")
        elif passw == shopNameSet.get() and len(passw and shopNameSet.get()) > 0:
            messagebox.showerror("Security", "For security, password must be different from shop name")
        else:
            shop_name_get = shopNameSet.get()
            shop_name_details = open("shopnamecontainer.txt", "w")
            shop_name_details.write(shop_name_get)
            shop_name_details.close()
            login_details_user = open("loginuser.txt", "w")
            login_details_user.write(user)
            login_details_user.close()
            login_details_passw = open("loginpassw.txt", "w")
            login_details_passw.write(passw)
            login_details_passw.close()
            messagebox.showinfo("Account created", "Your account was created")
            account.truncate(0)
            account.close()
            main_app()

def sign_in_func():
    user_contents = ask_user.get()
    passw_contents = ask_passw.get()
    if len(user_contents and passw_contents) == 0:
        messagebox.showerror("Fields missing", "Please fill out all fields")
        return
    else:
        login_details_user = open("loginuser.txt", "r")
        validate_user = login_details_user.read()
        login_details_user.close()
        login_details_passw = open("loginpassw.txt", "r")
        validate_passw = login_details_passw.read()
    if user_contents == validate_user and passw_contents == validate_passw:
        messagebox.showinfo("Logged in", "Welcome!")
        main_app()
    else:
        messagebox.showerror("Incorrect login", "Please try again")

if "0" in status:
    create_account = Label(text = "Create account", font = ("Segoe UI", 32))
    create_account.pack()
    spacer(3)
    username_label = Label(text = "Username")
    username_label.pack()
    spacer(1)
    username = Entry(width = 50)
    username.pack()
    spacer(3)
    password_label = Label(text = "Password")
    password_label.pack()
    spacer(1)
    password = Entry(width = 50, show = "\u2022")
    password.pack()
    spacer(1)
    shop_label = Label(text = "Name of shop or storeroom (optional)")
    shop_label.pack()
    spacer(1)
    shopNameSet = Entry(width = 50)
    shopNameSet.pack()
    spacer(1)
    create = Button(text = "Create account", width = 60, command = create_account_func)
    create.pack()
else:
    sign_in = Label(text = "Sign in", font = ("Segoe UI", 32))
    sign_in.pack()
    spacer(3)
    ask_username_label = Label(text = "Username")
    ask_username_label.pack()
    spacer(1)
    ask_user = Entry(width = 50)
    ask_user.pack()
    spacer(3)
    ask_password_label = Label(text = "Password")
    ask_password_label.pack()
    ask_passw = Entry(width = 50, show = "\u2022")
    ask_passw.pack()
    spacer(1)
    validation_system_activation = Button(text = "Sign in", width = 60, command = sign_in_func)
    validation_system_activation.pack()

def settarget():
    global file
    global target_set
    if file == "":
        messagebox.showinfo("Set target file", "Please select a file")
        window.filename = filedialog.askopenfilename(initialdir = "C:/Documents", title = "Set target file", filetypes = (("text files", ".txt"), ("all files","*.*")))
        file = window.filename
        letin = open(window.filename, "r")
        get_letters = letin.read()
        letin.close()
        check_used = open("usedfiles.txt", "r")
        check = check_used.read()
        if file in check and file != "":
            fileq = messagebox.askquestion("Clear data", "This file already has already been used with OrderLog. Are you sure you want to clear it?", icon = "warning")
            if fileq == "yes":
                clearfile = open(window.filename, "w")
                clearfile.truncate(0)
                clearfile.close()
                check_used.close()
                menubar.entryconfigure(1, state = NORMAL)
                menubar.entryconfigure(2, state = NORMAL)
                menubar.entryconfigure(3, state = NORMAL)
                menubar.entryconfigure(4, state = NORMAL)
                menubar.entryconfigure(5, state = NORMAL)
                target_set = True
                window.title("OrderLog - " + window.filename)
            else:
                messagebox.showinfo("File was not used", "File was not cleared")
                check_used.close()
                file = ""
                window.filename = ""
        else:
            check_used.close()
            check_used = open("usedfiles.txt", "a")
            check_used.write(window.filename)
            menubar.entryconfigure(1, state = NORMAL)
            menubar.entryconfigure(2, state = NORMAL)
            menubar.entryconfigure(3, state = NORMAL)
            menubar.entryconfigure(4, state = NORMAL)
            menubar.entryconfigure(5, state = NORMAL)
            target_set = True
            window.title("OrderLog - " + window.filename)
        if file != "":
            itembox.pack()
    else:
        messagebox.showerror("Could not set target file", "Cannot set target file or target file already set")

class SearchWin:
    def searchList(self):
        found = False
        elements = itemslist.size()
        content = self.searchTerms.get()
        current_index = 0
        for i in range(0, elements):
            if content in itemslist.get(current_index):
                itemslist.select_set(current_index)
                current_index += 1
                found = True
            else:
                if current_index <= elements:
                    current_index += 1
                    continue

        if found == True:
            messagebox.showinfo("Results", "Results found")
        else:
            messagebox.showerror("Results", "No results found")
            return

    def __init__(self):
        searchPrompt = Tk()
        searchPrompt.title("Search list")
        searchPrompt.attributes("-topmost", 1)
        searchPrompt.iconbitmap("feather.ico")
        searchPrompt.resizable(0, 0)

        searchText = Label(searchPrompt, text = "Search terms")
        searchText.pack()

        Label(searchPrompt).pack()

        self.searchTerms = Entry(searchPrompt, width = 30)
        self.searchTerms.pack(padx = 10)

        Label(searchPrompt).pack()

        searchbtn = Button(searchPrompt, text = "Search", command = self.searchList)
        searchbtn.pack()

def resetapp():
    setaccount = open("account.txt", "w")
    setaccount.write("0")
    setaccount.close()
    clearuser = open("loguser.txt", "w")
    clearuser.truncate(0)
    clearuser.close()
    clearpassw = open("loginpassw.txt", "w")
    clearpassw.truncate(0)
    clearpassw.close()
    clearshopname = open("shopnamecontainer.txt", "w")
    clearshopname.truncate(0)
    clearshopname.close()
    clearwebaddr = open("shopwebsite.txt", "w")
    clearwebaddr.truncate(0)
    clearwebaddr.close()
    clearsaves = open("saves.txt", "w")
    clearsaves.truncate(0)
    clearused = open("usedfiles.txt", "w")
    clearused.truncate(0)
    clearused.close()
    messagebox.showinfo("Exit", "Exit required to update")
    try:
        sys.exit()
    except:
        raise SystemExit()

class MailWin:
    def __init__(self):
        if self.check_connection() == True:
            defaultprovider = "smtp-mail.outlook.com"
            defaultport = 587
            self.provider = defaultprovider
            self.port = defaultport
            sendMail = Tk()
            sendMail.title("Email list")
            sendMail.iconbitmap("feather.ico")
            sendMail.resizable(0, 0)

            sendMailHeader = Label(sendMail, text = "Email list", font = ("Segoe UI", 32))
            sendMailHeader.pack()

            defaults = Label(sendMail, text = "Default provider: smtp-mail.outlook.com\nDefault port: 587")
            defaults.pack()

            Label(sendMail).pack()

            providerHeader = Label(sendMail, text = "Provider (optional)")
            providerHeader.pack()

            self.providerBox = Entry(sendMail, width = 50)
            self.providerBox.pack()

            Label(sendMail).pack()

            portHeader = Label(sendMail, text = "Port (optional)")
            portHeader.pack()

            self.portBox = Entry(sendMail, width = 50)
            self.portBox.pack()

            Label(sendMail).pack()

            mailRecLabel = Label(sendMail, text = "Recipient's email address")
            mailRecLabel.pack()

            self.recAddr = Entry(sendMail, width = 50)
            self.recAddr.pack()

            Label(sendMail).pack()

            mailUserLabel = Label(sendMail, text = "From email address")
            mailUserLabel.pack()

            self.mailUserBox = Entry(sendMail, width = 50)
            self.mailUserBox.pack()

            Label(sendMail).pack()

            mailPasswLabel = Label(sendMail, text = "From email password")
            mailPasswLabel.pack()

            self.mailPasswBox = Entry(sendMail, width = 50, show = "\u2022")
            self.mailPasswBox.pack()

            Label(sendMail).pack()

            sendBtn = Button(sendMail, text = "Send", width = 60, command = self.send)
            sendBtn.pack()
        else:
            messagebox.showerror("No internet", "Internet connection required. Try again later")

    def check_connection(self, host = "http://google.com"):
        try:
            urllib.request.urlopen(host)
            return True
        except:
            return False

    def send(self):
        global defaultprovider
        global defaultport
        if len(self.providerBox.get()) > 0:
            self.provider = providerBox.get()
            self.port = self.portBox.get()
        mail_user = self.mailUserBox.get()
        mail_passw = self.mailPasswBox.get()
        mailRecAddr = self.recAddr.get()
        if len(mail_user and mail_passw) > 0:
            try:
                get_list = open(window.filename, "r")
                listContent = get_list.read()
                get_list.close()
                server = smtplib.SMTP(self.provider, self.port)
                server.connect(self.provider, self.port)
                server.ehlo()
                server.starttls()
                server.ehlo()
                server.login(mail_user, mail_passw)
                server.sendmail(mail_user, mailRecAddr, "\n" + listContent)
                messagebox.showinfo("Sent", "Email sent\nProvider: " + self.provider + "\n" + "Port: " + str(self.port))
            except:
                messagebox.showerror("Invalid", "Invalid information")
        else:
            messagebox.showerror("Fields missing", "Please fill out all required fields")

def add_checker():
    if target_set == True:
        AddCall()
    else:
        messagebox.showerror("No target set", "Cannot add item to no target")

class SetCategory:
    def updateNextBtn(self, evt):
        if self.itemslistDuplicate.curselection() == ():
            self.nextBtn.config(state = DISABLED)
        else:
            self.nextBtn.config(state = NORMAL)

    def SET_CATEGORY(self):
        global food_category_list
        global confectionery_category_list
        global dairy_category_list
        global fruit_veg_category_list
        global meat_fish_chicken_category_list
        global diy_category_list
        global other_category_list

        category_chosen = self.categories.get()
        selected = self.itemslistDuplicate.curselection()
        selected_items = [[self.itemslistDuplicate.get(i) for i in self.itemslistDuplicate.curselection()]]

        if category_chosen == "Food":
            for i in range(0, len(selected_items)):
                food_category_list.append(selected_items[i])
        elif category_chosen == "Confectionery":
            for i in range(0, len(selected_items)):
                confectionery_category_list.append(selected_items[i])
        elif category_chosen == "Dairy":
            for i in range(0, len(selected_items)):
                dairy_category_list.append(selected_items[i])
        elif category_chosen == "Fruit & Vegetables":
            for i in range(0, len(selected_items)):
                fruit_veg_category_list.append(selected_items[i])
        elif category_chosen == "Meat, Fish & Chicken":
            for i in range(0, len(selected_items)):
                meat_fish_chicken_category_list.append(selected_items[i])
        elif category_chosen == "DIY":
            for i in range(0, len(selected_items)):
                diy_category_list.append(selected_items[i])
        elif category_chosen == "Other":
            for i in range(0, len(selected_items)):
                other_category_list.append(selected_items[i])

        messagebox.showinfo("Category set", "The category has been set")
        self.category.destroy()

    def __init__(self):
        global itemslist

        self.categoryItems = []

        self.category = Tk()
        self.category.title("OrderLog - Set item category")
        self.category.attributes("-toolwindow", 1)
        self.category.attributes("-topmost", 1)
        self.category.geometry("300x450")

        Label(self.category, text = "Set item category", font = ("Helvetica", 23)).pack(padx = 30, pady = 30)

        self.categories = Combobox(self.category, state = "readonly", values = ("Food", "Confectionery", "Dairy", "Fruit & Vegetables", "Meat, Fish & Chicken", "DIY", "Other"))
        self.categories.current(0)
        self.categories.pack(pady = 20)

        Label(self.category, text = "Select items to place in this category").pack(pady = 20)

        self.itemslistDuplicate = Listbox(self.category, selectmode = "multiple")
        self.itemslistDuplicate.pack(pady = 20)

        for i in range(0, itemslist.size()):
            self.itemslistDuplicate.insert(i, itemslist.get(i))

        self.nextBtn = Button(self.category, text = "Set category", width = window.winfo_screenwidth(), state = DISABLED, command = self.SET_CATEGORY)
        self.nextBtn.pack()

        self.category.bind("<<ListboxSelect>>", self.updateNextBtn)

class ViewCategory:
    def viewCategoryItems(self):
        global food_category_list
        global confectionery_category_list
        global dairy_category_list
        global fruit_veg_category_list
        global meat_fish_chicken_category_list
        global diy_category_list
        global other_category_list

        self.sel_category.destroy()

        self.categoryViewer = Tk()
        self.categoryViewer.title("View category items")
        self.categoryViewer.attributes("-toolwindow", 1)
        self.categoryViewer.resizable(0, 0)

        category_items = Listbox(self.categoryViewer)
        category_items.pack()

        lastItem = self.radioButtonList[-1]

        if lastItem == "0":
            for i in range(0, len(food_category_list)):
                category_items.insert(i, str(food_category_list[i]).replace("{", "").replace("}", ""))
        elif lastItem == "1":
            for i in range(0, len(confectionery_category_list)):
                category_items.insert(i, str(confectionery_category_list[i]).replace("{", "").replace("}", ""))
        elif lastItem == "2":
            for i in range(0, len(dairy_category_list)):
                category_items.insert(i, str(dairy_category_list[i]).replace("{", "").replace("}", ""))
        elif lastItem == "3":
            for i in range(0, len(fruit_veg_category_list)):
                category_items.insert(i, str(fruit_veg_category_list[i]).replace("{", "").replace("}", ""))
        elif lastItem == "4":
            for i in range(0, len(meat_fish_chicken_category_list)):
                category_items.insert(i, str(meat_fish_chicken_category_list[i]).replace("{", "").replace("}", ""))
        elif lastItem == "5":
            for i in range(0, len(diy_category_list)):
                category_items.insert(i, str(diy_category_list[i]).replace("{", "").replace("}", ""))
        elif lastItem == "6":
            for i in range(0, len(other_category_list)):
                category_items.insert(i, str(other_category_list[i]).replace("{", "").replace("}", ""))

    def foodAppend(self):
        self.radioButtonList.append("0")

    def confectioneryAppend(self):
        self.radioButtonList.append("1")

    def dairyAppend(self):
        self.radioButtonList.append("2")

    def fruitVegAppend(self):
        self.radioButtonList.append("3")

    def meatFishChickenAppend(self):
        self.radioButtonList.append("4")

    def diyAppend(self):
        self.radioButtonList.append("5")

    def otherAppend(self):
        self.radioButtonList.append("6")

    def __init__(self):
        self.tkVariable = IntVar()
        self.radioButtonList = []

        self.sel_category = Tk()
        self.sel_category.title("Select category to view")
        self.sel_category.attributes("-toolwindow", 1)
        self.sel_category.attributes("-topmost", 1)
        self.sel_category.geometry("300x600")

        Label(self.sel_category, text = "Select item category to view", font = ("Helvetica", 23)).pack(padx = 30, pady = 30)

        self.foodOption = Radiobutton(self.sel_category, text = "Food", variable = self.tkVariable, value = 1, command = self.foodAppend)
        self.foodOption.pack()

        self.confectioneryOption = Radiobutton(self.sel_category, text = "Confectionery", variable = self.tkVariable, value = 2, command = self.confectioneryAppend)
        self.confectioneryOption.pack()

        self.dairyOption = Radiobutton(self.sel_category, text = "Dairy", variable = self.tkVariable, value = 3, command = self.dairyAppend)
        self.dairyOption.pack()

        self.fruitVegOption = Radiobutton(self.sel_category, text = "Fruit & Vegetables", variable = self.tkVariable, value = 4, command = self.fruitVegAppend)
        self.fruitVegOption.pack()

        self.meatFishChickenOption = Radiobutton(self.sel_category, text = "Meat, Fish & Chicken", variable = self.tkVariable, value = 5, command = self.meatFishChickenAppend)
        self.meatFishChickenOption.pack()

        self.diyOption = Radiobutton(self.sel_category, text = "DIY", variable = self.tkVariable, value = 6, command = self.diyAppend)
        self.diyOption.pack()

        self.otherOption = Radiobutton(self.sel_category, text = "Other", variable = self.tkVariable, value = 7, command = self.otherAppend)
        self.otherOption.pack()

        Label(self.sel_category).pack()

        self.viewCategoryBtn = Button(self.sel_category, text = "View category items", width = 65, state = NORMAL, command = self.viewCategoryItems)
        self.viewCategoryBtn.pack()

class HTMLRawData:
    def createHTML(self):
        HTMLRawData.path = self.filepath.get()
        class FileTest:
            @classmethod
            def __init__(cls):
                try:
                    test_path_file = open(HTMLRawData.path + ".txt", "a+")
                    test_path_file.close()
                    return True
                except:
                    messagebox.showerror("Invalid path", HTMLRawData.path + " is not a valid file path")
                    return False

        if FileTest.__init__() == True:
            path_file = open(HTMLRawData.path + ".txt", "a")
            path_file.write("<!DOCTYPE html>\n")
            path_file.write("<html>\n")
            path_file.write("<title>Raw data</title>\n")
            get_raw_data = open("saves.txt", "r")
            html_text = get_raw_data.read()
            get_raw_data.close()
            path_file.write("<h1>Raw data</h1>\n")
            path_file.write("<p>" + str(html_text) + "</p>\n")
            path_file.write("</html>\n")
            path_file.close()
            os.rename(HTMLRawData.path + ".txt", HTMLRawData.path + ".html")
            openwebsiteq = messagebox.askquestion("Complete", "Raw data in " + HTMLRawData.path + ".html" + "\nDo you want to open it?")
            if openwebsiteq == "yes":
                webbrowser.open(HTMLRawData.path + ".html")
            else:
                pass
        else:
            return

    def __init__(self):
        setupWebsite = Tk()
        setupWebsite.title("Setup HTML file name")
        setupWebsite.iconbitmap("feather.ico")
        setupWebsite.resizable(0, 0)

        Label(setupWebsite).pack()

        setupText = Label(setupWebsite, text = "HTML file name (to create)\nFull path required (without suffix)\nExample: C:/Users/username/Desktop/filename")
        setupText.pack(padx = 30)

        self.filepath = Entry(setupWebsite, width = 50)
        self.filepath.pack()

        Label(setupWebsite).pack()

        createHTMLbtn = Button(setupWebsite, text = "Create", command = self.createHTML)
        createHTMLbtn.pack()

        Label(setupWebsite).pack()

class Settings:
    @classmethod
    def openwebsite(cls):
        web_url = open("shopwebsite.txt", "r")
        get_addr = web_url.read()
        web_url.close()
        if len(get_addr) > 0:
            try:
                webbrowser.open(get_addr)
            except:
                messagebox.showerror("Invalid URL", get_addr + " is not a valid URL")
        else:
            messagebox.showerror("No URL set", "URL has not been set")

    def get_session_mode(self):
        global itemslist

        shop_name_details = open("shopnamecontainer.txt", "r")
        shop_name = shop_name_details.read()
        shop_name_details.close()

        for i in range(0, itemslist.size()):
            if i > 0:
                word_split = itemslist.get(i).split()

                if shop_name != "":
                    indexAmount = 3
                else:
                    indexAmount = 2

                itemContent = word_split[indexAmount]
                self.modeList.append(itemContent)
            else:
                continue

        messagebox.showinfo("Most common item in session", "The most common item in this session is " + str(multimode(self.modeList)).replace("[", "").replace("]", ""))

    def set_web_addr(self):
        global url_set
        web_addr = self.website.get()
        self.website.delete(0, "end")
        if len(web_addr) > 0:
            web_url = open("shopwebsite.txt", "w")
            web_url.truncate(0)
            web_url.write(web_addr)
            web_url.close()
            messagebox.showinfo("Web address set", "Shop web address set to: " + web_addr)
            url_set = True
            return
        else:
            messagebox.showerror("Enter web address", "Web address required")
            return

    def __init__(self):
        global target_set

        self.modeList = []

        setup = Tk()
        setup.title("Settings")
        setup.attributes("-toolwindow", 1)
        setup.attributes("-topmost", 1)
        setup.resizable(0, 0)

        setupTabs = Notebook(setup)

        itemTab = Frame(setupTabs)
        launchTab = Frame(setupTabs)
        advancedTab = Frame(setupTabs)

        setupTabs.add(itemTab, text = "Products")
        setupTabs.add(launchTab, text = "Launch")
        setupTabs.add(advancedTab, text = "Advanced")

        itemsetup_label = Label(itemTab, text  = "Add item")
        itemsetup_label.pack()

        notebookspacer(1, itemTab)

        addbtn = Button(itemTab, text = "Add", command = add_checker)
        addbtn.pack()

        notebookspacer(1, itemTab)

        createHTMLbtn = Button(itemTab, text = "Copy raw data to HTML", command = HTMLDataInstance)
        createHTMLbtn.pack()

        notebookspacer(1, itemTab)

        modeBtn = Button(itemTab, text = "Session item mode", command = self.get_session_mode)
        modeBtn.pack()

        notebookspacer(1, itemTab)

        self.set_categories = Button(itemTab, text = "Set item categories", command = CategoryInstance)
        self.set_categories.pack()

        notebookspacer(1, itemTab)

        self.view_categories = Button(itemTab, text = "View category items", command = ViewCategoryInstance)
        self.view_categories.pack()

        if target_set == False:
            self.set_categories.config(state = "disabled")
            self.view_categories.config(state = "disabled")
        else:
            self.set_categories.config(state = "normal")
            self.view_categories.config(state = "normal")

        notebookspacer(1, itemTab)

        url_label = Label(itemTab, text = "Shop website URL")
        url_label.pack()

        self.website = Entry(itemTab)
        self.website.pack()

        notebookspacer(1, itemTab)

        set_website = Button(itemTab, text = "Set website URL", command = self.set_web_addr)
        set_website.pack()

        launchlabel = Label(launchTab, text = "Launch setup")
        launchlabel.pack()

        notebookspacer(1, launchTab)

        current_username = Label(launchTab, text = "Current user: " + getpass.getuser())
        current_username.pack()

        notebookspacer(2, launchTab)

        exitbtn = Button(launchTab, text = "Exit", command = closeall)
        exitbtn.pack()

        advancedlabel = Label(advancedTab, text = "Advanced setup")
        advancedlabel.pack()

        notebookspacer(1, advancedTab)

        resetbtn = Button(advancedTab, text = "Reset app", command = resetapp)
        resetbtn.pack()

        setupTabs.pack()

def savefile():
    get_all_items = itemsvar.get()
    save_file = open("saves.txt", "r")
    letters = save_file.read()
    save_file.close()
    if len(letters) > 0:
        overq = messagebox.askquestion("Overwriting", "Are you sure you want to overwrite the existing backup file?")
        if overq == "yes":
            save_file = open("saves.txt", "w")
            save_file.truncate(0)
            save_file.write(str(get_all_items))
            save_file.close()
            messagebox.showinfo("Backed up", "Backup complete")
        else:
            messagebox.showinfo("Not overwitten", "Contents were kept")
    else:
        save_file = open("saves.txt", "w")
        save_file.write(str(get_all_items))
        save_file.close()
        messagebox.showinfo("Backed up", "Backup complete")

def viewfile():
    file_was_viewed = True
    save_file = open("saves.txt", "r")
    insert_text = save_file.read()
    save_file.close()
    viewer = Tk()
    viewer.title("View backed up raw data")
    viewer.iconbitmap("feather.ico")
    viewer.resizable(0, 0)
    file_contents = Text(viewer)
    file_contents.config(state = NORMAL)
    file_contents.insert(INSERT, insert_text)
    file_contents.config(state = DISABLED)
    file_contents.pack()

def add():
    global session
    global no_items
    global itemslist
    itemname = itembox.get()
    if len(itemname) == 0:
        messagebox.showerror("Blank item", "Cannot add blank item")
    else:
        try:
            shop_name_details = open("shopnamecontainer.txt")
            name_of_shop = shop_name_details.read()
            shop_name_details.close()
            itemfile = open(window.filename, "a")
            session += 1
            if name_of_shop != "":
                itemfile.write(name_of_shop + ": " + "Product " + str(session) + ": " + itemname + "\n")
                itemfile.close()
            else:
                itemfile.write("Product " + str(session) + ": " + itemname + "\n")
                itemfile.close()
            itembox.delete(0, "end")
            messagebox.showinfo("Product added", "Product was added to " + window.filename + "\nProduct name: " + itemname)
            if no_items == True:
                no_items = False
                window.update()
                itembox.pack_forget()
                itemslist.pack()
                spacer(1)
                itembox_label = Label(text = "Product name")
                itembox_label.pack()
                itembox.pack()
                no_items_label.pack_forget()
            if name_of_shop != "":
                itemslist.insert(session, name_of_shop + ": " + "Product " + str(session) + ": " + itemname)
            else:
                itemslist.insert(session, "Product " + str(session) + ": " + itemname)
        except:
            messagebox.showerror("Could not add", "Item could not be added to list")

def clear():
    global file
    if file != "":
        itemfile = open(file, "r")
        readfile = itemfile.read()
        itemfile.close()
        if len(readfile) == 0:
            messagebox.showerror("Could not clear file", "File could not be cleared")
            return
    if file == "":
        settargetq = messagebox.askquestion("No target", "Please set a target. Would you like to set a target now?")
        if settargetq == "yes":
            settarget()
    else:
        clearq = messagebox.askquestion("Clear file", "Clear " + file + " and list?")
        if clearq == "yes":
            itemfile = open(window.filename, "w")
            itemfile.truncate(0)
            itemfile.close()
            itemslist.delete(0, END)
            messagebox.showinfo("Cleared", "File and list was cleared")
        else:
            pass

def printfile():
    global file
    itemfile = open(window.filename, "r")
    sourcecontent = itemfile.read()
    itemfile.close()
    if len(sourcecontent) > 0:
        printq = messagebox.askokcancel("Print?", "Will print to default printer")
        if printq:
            try:
                os.startfile(file, "print")
            except:
                messagebox.showerror("Cannot print", "Could not print")
    else:
        messagebox.showerror("Cannot print", "Cannot print blank document")

def get_login():
    login_details_user = open("loginuser.txt", "r")
    get_username = login_details_user.read()
    login_details_user.close()
    login_details_passw = open("loginpassw.txt", "r")
    get_password = login_details_passw.read()
    login_details_passw.close()
    messagebox.showinfo("Login details", "Username: " + get_username + "\nPassword: " + get_password + "\nFor security, don't forget to close this message")

class EditSelection:
    def replace_line(self, file_name, line_num, text):
        lines = open(file_name, "r").readlines()
        lines[line_num] = text
        out = open(file_name, "w")
        out.writelines(lines)
        out.close()

    def updateText(self):
        global itemslist
        global shop_name

        if itemslist.curselection() != ():
            if len(self.newText.get()) > 0:
                storedSelection = int(itemslist.curselection()[0])
                itemslist.delete(int(itemslist.curselection()[0]))
                itemslist.selection_clear(storedSelection, storedSelection)

                shop_name_details = open("shopnamecontainer.txt", "r")
                shop_name = shop_name_details.read()

                if shop_name != "":
                    self.replace_line(window.filename, storedSelection - 1, shop_name + ": " + "Product " + str(storedSelection) + ": " + str(self.newText.get()))
                else:
                    self.replace_line(window.filename, storedSelection - 1, "Product " + str(storedSelection) + ": " + str(self.newText.get()))

                if shop_name != "":
                    itemslist.insert(storedSelection, shop_name + ": " + "Product " + str(storedSelection) + ": " + str(self.newText.get()))
                else:
                    itemslist.insert(storedSelection, "Product " + str(storedSelection) + ": " + str(self.newText.get()))

                shop_name_details.close()

                messagebox.showinfo("Updated", "Item " + str(storedSelection) + " has been updated")
                self.editWin.destroy()
                del storedSelection
            else:
                messagebox.showerror("Cannot edit", "Cannot replace item with blank item")
                self.editWin.destroy()

    def __init__(self):
        item_to_edit = itemslist.curselection()

        self.editWin = Tk()
        self.editWin.title("OrderLog - Edit list item")
        self.editWin.attributes("-toolwindow", 1)
        self.editWin.resizable(0, 0)

        Label(self.editWin, text = "New text").pack()
        self.newText = Entry(self.editWin)
        self.newText.pack()

        Label(self.editWin).pack()

        Button(self.editWin, text = "Set text", command = self.updateText).pack(padx = 30, pady = 20)

def updateEditBtn(evt):
    global itemslist
    global edit
    global window

    if itemslist.curselection() == ():
        edit.config(state = DISABLED)
        window.update()
    else:
        edit.config(state = NORMAL)
        window.update()

def main_app():
    global signed_in
    global itemslist

    signed_in = True
    window.title("OrderLog - No target")
    window.resizable(1, 1)

    if "0" in status:
        username.pack_forget()
        password.pack_forget()
        username_label.pack_forget()
        password_label.pack_forget()
        shop_label.pack_forget()
        shopNameSet.pack_forget()
        create_account.pack_forget()
        create.pack_forget()
    else:
        sign_in.pack_forget()
        ask_username_label.pack_forget()
        ask_user.pack_forget()
        ask_password_label.pack_forget()
        ask_passw.pack_forget()
        validation_system_activation.pack_forget()

    menubar.add_command(label = "Login", command = get_login)
    menubar.add_command(label = "Target", command = settarget)
    menubar.add_command(label = "Settings", command = SettingsInstance)
    menubar.add_command(label = "Exit", command = closeall)

    spacer(1)

    now = datetime.datetime.now()

    time_of_day = Label(text = str(now.hour) + ":" + str("%02d" % now.minute).format(1))
    time_of_day.pack()

    spacer(1)

    items_list_label = Label(text = "Products", font = ("Segoe UI", 32))
    items_list_label.pack()

    spacer(1)

    no_items_label.pack()

    spacer(1)

    clearbtn = Button(text = "Clear", width = 10, command = clear)
    clearbtn.pack(pady = 30, side = BOTTOM)

    class OpenWebsiteBtn:
        def __init__(self):
            websitebtn = Button(text = "Open website", width = 20, command = Settings.openwebsite)
            websitebtn.pack(side = BOTTOM)

    show_btn = OpenWebsiteBtn()

    spacer(15)

    edit.pack()

    spacer(3)

    window.config(menu = menubar)
    itemslist.bind("<<ListboxSelect>>", updateEditBtn)

window.protocol("WM_DELETE_WINDOW", closeall)

window.mainloop()
This may help you figure it out

The rest of it works except the time part
If all your needing is a clock, this is much easier.

#! /usr/bin/env python3

import tkinter as tk
from time import strftime
class Clock:
    def __init__(self, parent):
        self.label = tk.Label(parent)
        self.label['font'] = 'sans 16 normal'
        self.label['fg'] = 'red'
        self.label.pack()

        self.update()

    def display(self):
        self.label['text'] = strftime('%H:%M:%S')

    def update(self):
        self.display()
        self.label.after(1000, self.update)


if __name__ == '__main__':
    root = tk.Tk()
    root.title('Clock')
    root.geometry('200x200+150+150')
    Clock(root)
    root.mainloop()
I'll try that

But before I do, will that update?

Because I remember trying label.after() in the loop before and it not working
On my machine it does
Pages: 1 2