1.python代码
import tkinter as tk
def on_button_click(number):
global selected_button
if selected_button:
selected_button.config(bg="SystemButtonFace")
buttons[number - 1].config(bg="#B284C1") # 使用中等紫色
selected_button = buttons[number - 1]
print("选中按钮:", number)
# 自定义列区间
RANGES = [
(1, 20),
(21, 34)
]
# 初始化主窗口
root = tk.Tk()
root.title("")
root.attributes('-topmost', True)
font_style = ("Helvetica", 8)
main_frame = tk.Frame(root)
main_frame.pack(padx=10, pady=10)
buttons = []
selected_button = None
# 动态生成列
for col_index, (start, end) in enumerate(RANGES):
column_frame = tk.Frame(main_frame, borderwidth=1, relief="groove")
column_frame.grid(row=0, column=col_index, padx=5, sticky="n") # 列顶部对齐
# 标题
#title = tk.Label(column_frame, text=f"{start}-{end}", font=font_style)
#title.pack(pady=2)
# 按钮
for num in range(start, end + 1):
btn = tk.Button(
column_frame,
text=str(num),
font=font_style,
width=5,
height=1,
command=lambda n=num: on_button_click(n)
)
btn.pack(pady=1)
buttons.append(btn)
# 操作按钮
last_column_index = len(RANGES) # 最后一列的索引
bottom_up_buttons = ["A", "B", "C", "D"] # 添加的按钮文本
bottom_up_frame = tk.Frame(main_frame, borderwidth=1, relief="groove")
## last_column_index-1表示在最后一列, 不减会新开一列
bottom_up_frame.grid(row=0, column=last_column_index - 1, padx=5, sticky="s") # 列底部对齐
## 计算最后一个区间的最大行数
max_row = max([end for _, end in RANGES])
## 处理函数
def operate(type):
print(type)
## 在最后一列底部往上添加按钮
for i, label in enumerate(bottom_up_buttons):
btn = tk.Button(
bottom_up_frame,
text=label,
font=font_style,
width=5,
height=1,
command=lambda l=label: operate(l)
)
btn.grid(row=max_row - len(bottom_up_buttons) + i + 1, column=0, pady=1) # 行号从底部开始递减
# 启动主循环
root.mainloop()