I am trying to write a program that will let me print certain text when I press one of the 15 buttons. It mostly works, but I cannot get it to take the text from a specific button.
import tkinter as tk
from tkinter import ttk
import time
def quit_script(root):
root.destroy()
def write_data(floor_num, output):
floor_done = []
current_time = time.strftime("%H:%M", time.localtime())
floor_done.append(f"{current_time} {floor_num}階 復旧作業開始")
for i in floor_done:
output.insert("end", f"{i}")
def main():
root = tk.Tk()
root.title("Fusion timing register")
root.minsize(420, 340)
root.geometry("420x340")
mainframe = ttk.Frame(root, padding=(15, 15, 15, 15))
mainframe.grid(column=0, row=0, sticky=("N", "W", "S", "E"))
class FloorButton(ttk.Button):
def __init__(self, master, text, command, width):
ttk.Button.__init__(self,
master = master,
text = text,
command = command,
width = width)
floor_frame = ttk.Frame(mainframe, border=5, relief="sunken", width=200, height=300)
floor_frame.grid(column=0, row=0, columnspan=3, rowspan=5, sticky=("N", "W", "S", "E"))
floors = ["TGT 27", "TGT 26", "OLT 30", "OLT 29", "OLT 28", "OLT 27", "OLT 26", "OLT 25", "OLT 24", "OLT 23", "OLT 22", "OLT 21", "OLT 20", "OLT 19", "OLT 18",]
col = 0
row = 0
for floor_num in floors:
floor = FloorButton(master=floor_frame, text=floor_num, command=lambda: write_data(floor_num, output), width=7)
floor.grid(column=col, row=row, sticky=("N", "W", "S", "E"), padx=3, pady=3)
if col < 2:
col += 1
else:
if row < 4:
col = 0
row += 1
complete = ttk.Button(master=mainframe, text="✔", command=..., width=7)
complete.grid(column=5, row=0, sticky=("N", "W", "E"))
placeholder_label = ttk.Label(master=mainframe, width=7)
placeholder_label.grid(column=4, row=0, rowspan=7, sticky=("N", "S"))
exit = ttk.Button(master=mainframe, text="Exit", command=lambda: quit_script(root), width=7)
exit.grid(column=5, row=7, sticky=("S", "W"))
label_frame = ttk.Frame(mainframe, border=5, relief="sunken", width=700, height=100)
label_frame.grid(column=0, row=7, columnspan=3, sticky=("N", "S", "W"))
output = tk.Listbox(label_frame, width=30, height=7)
output.grid(column=0, row=0, sticky=("W", "E"))
scrollbar = ttk.Scrollbar(label_frame, orient="vertical", command=output.yview)
scrollbar.grid(column=1, row=0, sticky=("N", "S"))
output["yscrollcommand"] = scrollbar.set
tk.mainloop()
if __name__ == "__main__":
main()
I understand why it does what it does -- it uses the last result from floor_num variable. But I do not know how to query exactly the button I click, and I am not even sure it is possible, since the buttons aren't stored anywhere explicitly.
I have read other similar questions on here, but I do not really understand classes yet and I was looking for a simpler solution.