Python Forum
Making my way back into programming and need a little help.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Making my way back into programming and need a little help.
#2
Some things to think about.
import tkinter as tk


relays = []
setup_file = "switches.txt"


def set_relay_state(relay, state):
    """Set relay button value."""
    relay.state = state
    relay["text"] = relay.name + (" ON" if state else " OFF")
    relay["bg"] = "red" if state else "green"


def set_relay_name(relay, name):
    """Set the name of the relay"""
    relay.name = name
    set_relay_state(relay, relay.state)


def toggle_relay(relay):
    """Toggle a relay button."""
    set_relay_state(relay, not relay.state)


def set_relays(state):
    """Set all relays to some state."""
    for relay in relays:
        set_relay_state(relay, state)


def submit(window, entries):
    """Callback for set_relays Commit button.  Set relay
    names and save names in config file.
    """
    with open(setup_file, "w") as file:
        for switch, relay in zip(entries, relays):
            print(switch.get(), file=file)
            set_relay_name(relay, switch.get())
    window.destroy()


def edit_relays():
    """Create setup window for entering relay names"""
    window = tk.Toplevel()
    window.title("SETUP")
    entries = []
    for i, relay in enumerate(relays):
        row = i % 4
        col = (i // 4) * 2
        label = tk.Label(window, text="Switch #" + str(i + 1))
        label.grid(row=row, column=col, padx=5, pady=5)
        var = tk.StringVar(window, relay.name)
        entries.append(var)
        entry = tk.Entry(window, textvariable=var, width=15)
        entry.grid(row=row, column=col + 1, padx=5, pady=5)
    button = tk.Button(window, text="Submit", command=lambda: submit(window, entries))
    button.grid(row=5, column=0, columnspan=2, padx=5, pady=5, sticky="news")
    button = tk.Button(window, text="Cancel", command=window.destroy)
    button.grid(row=5, column=2, columnspan=2, padx=5, pady=5, sticky="news")


# Opening files may fail.  Don't let that crash the program.
try:
    with open(setup_file, "r") as file:
        names = [line.strip() for line in file]
except FileNotFoundError:
    pass

# If the file is messed up or missing provide some default names.
if len(names) != 8:
    names = ["Switch #" + str(i) for i in range(1, 9)]

root = tk.Tk()
menubar = tk.Menu(root)
menu = tk.Menu(menubar, tearoff=False)
menubar.add_cascade(label="Options", menu=menu)
menu.add_command(label="Edit Relays", command=edit_relays)
menu.add_command(label="All Off", command=lambda: set_relays(False))
menu.add_command(label="All On", command=lambda: set_relays(True))
root.config(menu=menubar)

for i, name in enumerate(names):
    row = i % 4
    col = i // 4
    relay = tk.Button(root, width=15)
    relay.configure(command=lambda arg=relay: toggle_relay(arg))
    relay.grid(row=i % 4, column=i // 4, padx=5, pady=5)
    relay.name = name
    set_relay_state(relay, False)
    relays.append(relay)

root.mainloop()
I know I left things out (where are the LED's?). This is not meant to replace your code, only to provide some ideas on how you could organize your code,

Notice that global() is nowhere to be seen. Lots of global variables make it difficult to track what your program is doing.

Notice there are no functions that do the same thing. Write generic functions and make them specific by passing arguments.

Do not use wildcard imports (from tkinter import *). When doing a wildcard import you import all the names from the module. Some of those names may be the same as names for variables or functions in your code. This can lead to really odd behaviors that are difficult to track down. Wildcard imports also make it difficult to find where a name was defined. The wildcard provides no clues. tk.Button leaves no doubt where the Button comes from.

If this is on a small screen, you should think about making it a single window/full screen application that has interchangeable frames that appear in root window instead of independent toplevel windows.. 

I have no idea how to force a program to run on a raspberry pi. That sounds like a good question for a raspberry pi forum.
Reply


Messages In This Thread
RE: Making my way back into programming and need a little help. - by deanhystad - Oct-12-2023, 10:09 PM

Forum Jump:

User Panel Messages

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