python(37) : 弹窗纵向排列按钮

 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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值