Python Forum
Trouble with Tkinter labels
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Trouble with Tkinter labels
#5
You must really like typing. As far as I am concerned, this is duplicate code, and duplicate code should be avoided.
    if os.path.isdir(os.path.join(ck_root, ck_folder)):
        label = Label(root, text='exists in root : ', font=('Arial', 15))
        label.place(x=150, y=450)
        root.after(5000, label.destroy)  # 1000=1 second
 
    elif os.path.isdir(os.path.join(ck_dir1, ck_folder)):
        label = Label(root, text='exists in Program Files', font=('Arial', 15))
        label.place(x=150, y=450)
        root.after(5000, label.destroy)  # 1000=1 second
 
    elif os.path.isdir(os.path.join(ck_dir2, ck_folder)):
        label = Label(root, text='exists in Program Files (x86)', font=('Arial', 15))
        label.place(x=150, y=450)
        root.after(5000, label.destroy)  # 1000=1 second
 
    else:
        label = Label(root, text=ck_folder + ' Doesnt exist', font=('Arial', 15))
        label.place(x=150, y=450)
        root.after(5000, label.destroy)  # 1000=1 second
 
Same thing here. Nearly duplicate code.
def sel_0():
    global ck_folder  # [global-variable-undefined]
    ck_folder = 'ccleaner'  # name of folder to look for
    global dw_file_name
    dw_file_name = r'\ccsetup551.exe'  # name of executable file
 
    path_check_locations()
 
 
def sel_1():
    # this label is towards the bottom of the window
 
    label = Label(root, text='looking for: ' + ck_folder, font=('Arial', 15))
    label.place(x=150, y=420)
    root.after(5000, label.destroy)  # 1000=1 second
 
 
def sel_2():
    # this label is towards the bottom of the window
 
    label = Label(root, text="Test is this 2", font=('Arial', 15))
    label.place(x=150, y=450)
    root.after(5000, label.destroy)  # 1000=1 second
    print('Test is this 2')
 
 
def sel_3():
    # this label is towards the bottom of the window
 
    label = Label(root, text="Test is this 3", font=('Arial', 15))
    label.place(x=150, y=450)
    root.after(5000, label.destroy)  # 1000=1 second
    print('Test is this 3')
 
 
def sel_4():
    # this label is towards the bottom of the window
 
    label = Label(root, text="Test is this 4", font=('Arial', 15))
    label.place(x=150, y=450)
    root.after(5000, label.destroy)  # 1000=1 second
    print('Test is this 4')
 
 
def select():
    # this is linked to the Menu_Tkinter.py
    # this calls the functions from above
 
    selection = my_listbox.curselection()
    if selection == (0,):
        sel_0()
    elif selection == (1,):
        sel_1()
    elif selection == (2,):
        sel_2()
    elif selection == (3,):
        sel_3()
    elif selection == (4,):
        sel_4()
When I see a program where the same instructions appear over and over again, I see if I can separate the code that is the same each time from the code that is different. In this example, the methods that are performed when you select a program are the same for each program. The only thing that changes is the folder where the program files might reside. The code that executes the programs is likely very similar. Code that is the same, regardless of the selection, and code that is specific to each program.

In the code below I put the program specific stuff, dictionaries and commands, in a dictionary. This lets me use the same code to install any program.
import tkinter as tk
from tkinter import ttk
from pathlib import Path
import shutil


# Where I look for programs
program_paths = {
    "root": Path("c:/"),
    "Program Files": Path("c:/Program Files"),
    "Program Files (x86)": Path("c:/Program Files (x86)"),
}

# Programs I can install
programs = {
    "ccleaner": ["folder name", "print('Replace with command to install ccleaner')"],
    "dirtier": ["folder name", "print('Replace with command to install dirtier')"],
}


class Window(tk.Tk):
    def __init__(self):
        super().__init__()

        label = tk.Label(self, text="Select Program")
        self.program = tk.StringVar()
        selector = ttk.Combobox(self, textvariable=self.program, values=list(programs))
        selector.bind("<<ComboboxSelected>>", self.select_program)
        self.message = tk.StringVar(self, "No program Selected")
        message = tk.Label(self, textvariable=self.message, width=60)
        self.button = tk.Button(
            self,
            text="Install Program",
            command=self.install_program,
            state=tk.DISABLED,
        )

        label.grid(row=0, column=0, padx=10, pady=10, sticky="news")
        selector.grid(row=0, column=1, padx=(0, 10), pady=10, sticky="news")
        message.grid(
            row=1, column=0, columnspan=2, padx=10, pady=(0, 10), sticky="news"
        )
        self.button.grid(
            row=2, column=0, columnspan=2, padx=10, pady=(0, 10), sticky="news"
        )

    def set_message(self, message):
        self.message.set(message)
        self.update()

    def select_program(self, *_):
        program = self.program.get()
        for folder, path in program_paths.items():
            if (path / folder).is_dir():
                self.message.set(f"{program} found in {str(path)}.")
                self.button["state"] = tk.DISABLED
        else:
            self.message.set(f"{program} not found.")
            self.button["state"] = tk.NORMAL

    def install_program(self):
        program = self.program.get()
        folder, command = programs[program]
        # If command can take long time, can run this code in another thread.
        (Path(td_dest_path) / folder).mkdir(parents=True, exist_ok=True)
        self.set_message(f"Installing {program}")
        eval(command)  # <- This executes the python command from the programs directory.
        self.set_message("")


Window().mainloop()
To add another program to my program, all I have to do is add an entry to the programs dictionary.
Reply


Messages In This Thread
Trouble with Tkinter labels - by Raysz - Sep-09-2023, 11:18 PM
RE: Trouble with Tkinter labels - by menator01 - Sep-10-2023, 12:31 AM
RE: Trouble with Tkinter labels - by Raysz - Sep-10-2023, 08:34 AM
RE: Trouble with Tkinter labels - by deanhystad - Sep-10-2023, 03:46 PM
RE: Trouble with Tkinter labels - by Raysz - Sep-10-2023, 06:02 PM
RE: Trouble with Tkinter labels - by deanhystad - Sep-10-2023, 04:59 PM
RE: Trouble with Tkinter labels - by deanhystad - Sep-11-2023, 02:58 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tkinter] Trouble changing Font within tkinter frame title AnotherSam 1 6,848 Sep-30-2021, 05:57 PM
Last Post: menator01
  [Tkinter] modify the html table to include data from tkinter labels rwahdan 0 2,342 Jun-20-2021, 10:33 AM
Last Post: rwahdan
  Tkinter having problems with packing labels? wallgraffiti 0 2,231 Aug-02-2020, 09:26 AM
Last Post: wallgraffiti
  Creating and destroying dynamic labels in Tkinter MarcusRoberts 1 6,651 May-02-2020, 06:49 PM
Last Post: Yoriz
  Spacing Between two labels are very far and Top label is not in Center using Tkinter barry76 2 9,076 Jul-30-2019, 10:49 AM
Last Post: wuf

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020