Python Forum
[Tkinter] Updating Label After Button Press - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: GUI (https://python-forum.io/forum-10.html)
+--- Thread: [Tkinter] Updating Label After Button Press (/thread-12269.html)



Updating Label After Button Press - malonn - Aug-16-2018

First off, I admit that I haven't really searched for an answer on these forums. I'm kind of impatient. Here's my question:

I have a simple practice GUI that has a couple labels that describe a task and buttons that do specific tasks. These buttons are tied to functions where the magic happens. I want to know how to update the labels associated with them to show that the task is complete. So, label is "you have 10 files that can be deleted", button deletes them, how can I update the label to say "you now have 0 files to delete"? Preferably, I want to run the function that checks for the files to delete first--that way I'm sure all is good--then update the label. Working code:
import os
import winreg
import tkinter
from tkinter import ttk
import ctypes
import sys

def scan_dumps():
    '''Walks the OS drive and returns
    a dict with the path to and size of
    each .DMP file found on the drive.'''
    dumps = {}
    k = 0
    for dpath, dname, fname in os.walk('C:\\'):
        for f_n in fname:
            if f_n.endswith('.dmp'):
                dumps[k] = [os.path.join(dpath, f_n), os.stat(os.path.join(dpath, f_n)).st_size]
                k += 1
    return dumps

def get_size(dmp_dict_in):
    '''Takes the dict created by
    "scan_dumps()" and gets total
    size of all .DMP files to
    display in the GUI.'''
    i = 0
    tsize = 0
    while i < len(dmp_dict_in):
        tsize += dmp_dict_in[i][1]
        i += 1
    tsize /= 1024
    tsize = round(tsize)
    return format(tsize, ',')

def get_profile_keys():
    '''Opens a specific registry key
    and creates a list of key + sub-key.'''
    reg_key = 'SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\NetworkList\\Profiles'
    with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, reg_key, 0, winreg.KEY_ALL_ACCESS) as k:
        ns = winreg.QueryInfoKey(k)[0]
        subs = []
        for i in range(ns):
            subs.append(reg_key + '\\' + winreg.EnumKey(k, i))
    return subs

def get_newest_keys(keys_in):
    '''Takes "get_profile_keys" and decodes the
    "DateCreated" registry value.  Next finds the
    newest values per "DateCreated"and returns a
    list of the full registry key for the newest
    key(s).'''
    stamp = []
    stamps = {}
    for i in range(len(keys_in)):
        reg_key = keys_in[i]
        with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, reg_key, 0, winreg.KEY_ALL_ACCESS) as k:
            val = winreg.QueryValueEx(k, 'DateCreated')
            stamp.append(int.from_bytes(val[0][:2], 'little'))
            stamp.append(int.from_bytes(val[0][2:4], 'little'))
            stamp.append(int.from_bytes(val[0][6:8], 'little'))
            stamp.append(int.from_bytes(val[0][8:10], 'little'))
            stamp.append(int.from_bytes(val[0][10:12], 'little'))
            stamp.append(int.from_bytes(val[0][12:14], 'little'))
            stamps[i] = stamp
            stamp = []
    if len(stamps) == 1:
        return None
    elif len(stamps) == 2:
        z = 0
        for x in stamps[0]:
            if x > stamps[1][z]:
                return [keys_in[0]]
            elif x < stamps[1][z]:
                return [keys_in[1]]
            z += 1
    #add condition for more than two keys

def delete_dmps(mem_dict_in):
    '''Walks the dict and removes each
    file stored.  "mem_dict_in" must be
    the dict created by "scan_dumps()"'''
    i = 0
    while i < len(mem_dict_in):
        p, s = mem_dict_in[i]
        os.remove(p)
        i += 1

def delete_keys(delete_in):
    '''Takes the list returned by
    "get_newest_keys" and deletes
    each key.'''
    if delete_in is None:
        return None
    else:
        for x in delete_in:
            winreg.DeleteKey(winreg.HKEY_LOCAL_MACHINE, x)

if ctypes.windll.shell32.IsUserAnAdmin():
    MEM_DUMPS = scan_dumps()
    SIZE = get_size(MEM_DUMPS)
    KEYS = get_profile_keys()
    DEL = get_newest_keys(get_profile_keys())

    BASE = tkinter.Tk()
    BASE.title('GUI Practice GUI')

    MEM_EXISTS = tkinter.StringVar()
    REG_SCAN = tkinter.StringVar()
    MEM_EXISTS.set('{} KB of memory dumps found!'.format(SIZE))
    if len(KEYS) > 1:
        NUM = len(KEYS) - 1
        REG_SCAN.set('{} unwanted key(s) found!'.format(NUM))
    else:
        REG_SCAN.set('No unwanted keys found!')

    ROOT_FRAME = ttk.Frame(BASE)
    ROOT_FRAME.grid(column=0, row=0, sticky=('N', 'E', 'S', 'W'))
    ROOT_FRAME.columnconfigure(0, weight=1)
    ROOT_FRAME.rowconfigure(0, weight=1)
    MEM_FRAME = ttk.Frame(ROOT_FRAME, relief='raised', borderwidth=2)
    MEM_LABL1 = ttk.Label(MEM_FRAME, text='Memory Dumps:')
    MEM_LABL2 = ttk.Label(MEM_FRAME, textvariable=MEM_EXISTS)
    MEM_BUTON = ttk.Button(MEM_FRAME, text='Delete', command=delete_dmps(MEM_DUMPS))
    REG_FRAME = ttk.Frame(ROOT_FRAME, relief='raised', borderwidth=2)
    REG_LABL1 = ttk.Label(REG_FRAME, text='Registry:')
    REG_LABL2 = ttk.Label(REG_FRAME, textvariable=REG_SCAN)
    REG_BUTON = ttk.Button(REG_FRAME, text='Delete', command=delete_keys(DEL))

    MEM_FRAME.grid(column=0, row=0)
    MEM_LABL1.grid(column=0, row=0)
    MEM_LABL2.grid(column=0, row=1)
    MEM_BUTON.grid(column=0, row=2)
    REG_FRAME.grid(column=1, row=0)
    REG_LABL1.grid(column=1, row=0, sticky='N')
    REG_LABL2.grid(column=1, row=1)
    REG_BUTON.grid(column=1, row=2)

    BASE.mainloop()
else:
    ctypes.windll.shell32.ShellExecuteW(None, 'runas', sys.executable, 'practice_gui.py', None, 1)
I suppose I could tie in label stuff into the functions that the buttons call? I don't know. I'm just hoping for a little insight.

-malonn


RE: Updating Label After Button Press - Larz60+ - Aug-16-2018

you can use (for example):
MEM_LABL1.configure(text = 'My New Text')



RE: Updating Label After Button Press - malonn - Aug-16-2018

Okay, but how is the script processed then is my next question? It's read from top to bottom, once, so how can I manipulate flow control to allow certain sections to be read after the button is pressed? Or would I have to put it in a function? If so, how can I tie more than one function to a button? Those questions are really drilling down into the bedrock. Not so much syntax of Tkinter--I can look that up easily.


RE: Updating Label After Button Press - woooee - Aug-17-2018

> so how can I manipulate flow control to allow certain sections to be read after the button is pressed?

See "command=" option (first example) at http://effbot.org/tkinterbook/button.htm


RE: Updating Label After Button Press - Larz60+ - Aug-17-2018

Quote:so how can I manipulate flow control to allow certain sections to be read after the button is pressed
In addition to looking at what wooee suggests, rewriting your code as a class would allow all methods to be available, regardless of the code order. Then you can bind events to widgets and know that you will be able to access the methods needed regardless of where they were located.


RE: Updating Label After Button Press - malonn - Aug-17-2018

(Aug-17-2018, 01:35 AM)woooee Wrote: See "command=" option (first example) at http://effbot.org/tkinterbook/button.htm
Okay, thanks. I'll take a look at the info.

(Aug-17-2018, 02:41 AM)Larz60+ Wrote: In addition to looking at what wooee suggests, rewriting your code as a class would allow all methods to be available, regardless of the code order. Then you can bind events to widgets and know that you will be able to access the methods needed regardless of where they were located.
Uh oh. Uncharted territory for me. You wouldn't happen to have a link to a nice read-up about classes, would you? I have a pretty nice collection of bookmarks but an experienced Pythonista's idea of a good read could be different than what I have...


RE: Updating Label After Button Press - Larz60+ - Aug-17-2018

there's one here: https://python-forum.io/Thread-Classes-Class-Intermediate-Inheritance?highlight=classes
and: https://python-forum.io/Thread-Classes-Class-Intermediate-Inheritance?highlight=classes
and: https://python-forum.io/Thread-Classes-Class-Intermediate-Operator-Overloading?highlight=classes

and this looks like a good one(short and to the point): https://www.pythoncentral.io/introduction-to-python-classes/


RE: Updating Label After Button Press - malonn - Aug-23-2018

Little late here, but thanks, @Larz60+! In the meantime I've explored Google some and, armed with your links and what I've found, I should be able to figure this out. Thanks again all.

-malonn