如何让Python Tkinter中的框架可滚动
我正在尝试制作一个框架,里面放置一些按钮,这些按钮代表不同的食材。当有人按下某个按钮时,这个按钮就会从框架中移除。我试过很多方法来实现这个功能,唯一想到的合适办法就是让框架可以滚动,因为我找不到限制框架行和列大小的方法。
我还试着按照chatgpt3的建议,做了一个弹出窗口来充当可滚动的框架,但这有两个问题:1. 不方便,2. 根本不管用,因为滚动功能也不工作。
import tkinter as tk
from tkinter import ttk
def create_popout_window(window):
popout_window = tk.Toplevel(window)
popout_window.title("Pop-out Window")
# Create a canvas
canvas = tk.Canvas(popout_window)
canvas.pack(side="left", fill="both", expand=True)
# Add a scrollbar
scrollbar = ttk.Scrollbar(popout_window, orient="vertical", command=canvas.yview)
scrollbar.pack(side="right", fill="y")
# Configure the canvas
canvas.configure(yscrollcommand=scrollbar.set)
# Create a frame inside the canvas
scrollable_frame = tk.Frame(canvas, bg="pink", height=500, width=600)
# Add widgets to the scrollable frame
# Configure the canvas to contain the frame
canvas.create_window((0, 0), window=scrollable_frame, anchor="nw")
def on_mousewheel(event):
canvas.yview_scroll(int(-1 * (event.delta / 120)), "units")
def bind_mousewheel(event):
canvas.bind_all("<MouseWheel>", on_mousewheel)
def unbind_mousewheel(event):
canvas.unbind_all("<MouseWheel>")
# Bind mousewheel events
popout_window.bind("<Enter>", bind_mousewheel)
popout_window.bind("<Leave>", unbind_mousewheel)
canvas.bind_all("<MouseWheel>", on_mousewheel)
return scrollable_frame
1 个回答
0
在你的评论中你提到:
我想让按钮排列成一个方形的列表,而且它们的大小都一样。我打算让按钮在到达每一行最后一个可见的格子时,切换到下一列,然后当方形排列完成后,再开始往下一行移动。
如果我理解得没错,你想要的其实很简单。最简单的方法就是把按钮放在一个文本小部件里。如果你想让按钮呈现网格状,就得确保所有按钮的大小都是一样的。
使用文本小部件的好处是,当你删除一个按钮时,其他按钮会自动重新排列,不需要你额外去调整。而且,它还可以实现滚动功能,非常方便。
这里有一个简单的例子:
import tkinter as tk
root = tk.Tk()
container = tk.Text(root, wrap="char")
container.pack(fill="both", expand=True)
for i in range(40):
name = f"button{i+1}"
button = tk.Button(container, name=name, text=name, width=10)
container.window_create("end", window=button)
container.configure(state="disabled")
tk.mainloop()