如何使用tkinter中的pack使Scrollbar位于最右侧
时间: 2023-03-03 14:49:49 浏览: 295
calculate.zip_calculate 在python_calculate在Python_calculator_pyth
要将`Scrollbar`位于`Tkinter`窗口的最右侧,请遵循以下步骤:
1. 创建`Scrollbar`和其它窗口部件。例如,以下代码创建一个包含`Scrollbar`、`Canvas`和一个`Button`的窗口:
```python
import tkinter as tk
root = tk.Tk()
# create scrollbar and canvas
scrollbar = tk.Scrollbar(root)
canvas = tk.Canvas(root, yscrollcommand=scrollbar.set)
scrollbar.config(command=canvas.yview)
# create some content for the canvas
for i in range(50):
tk.Label(canvas, text=f"Label {i}").pack()
# create a button
tk.Button(root, text="Button").pack()
# pack the scrollbar and canvas
scrollbar.pack(side="right", fill="y")
canvas.pack(side="left", fill="both", expand=True)
```
2. 然后,使用`pack_configure()`方法来修改`Scrollbar`的大小,以便将其放置在窗口的最右侧。这可以通过在`Scrollbar`对象上调用`pack_configure()`方法,并传递`side="right"`和`fill="y"`参数来实现。例如:
```python
# configure the scrollbar to be on the right side
scrollbar.pack_configure(side="right", fill="y")
```
完整的代码如下:
```python
import tkinter as tk
root = tk.Tk()
# create scrollbar and canvas
scrollbar = tk.Scrollbar(root)
canvas = tk.Canvas(root, yscrollcommand=scrollbar.set)
scrollbar.config(command=canvas.yview)
# create some content for the canvas
for i in range(50):
tk.Label(canvas, text=f"Label {i}").pack()
# create a button
tk.Button(root, text="Button").pack()
# pack the scrollbar and canvas
scrollbar.pack(side="right", fill="y")
canvas.pack(side="left", fill="both", expand=True)
# configure the scrollbar to be on the right side
scrollbar.pack_configure(side="right", fill="y")
root.mainloop()
```
注意:`pack_configure()`方法在`Tkinter`版本8.6及以上才可用。如果你的`Tkinter`版本比较旧,你可以使用`pack_forget()`方法将`Scrollbar`从窗口中移除,然后重新使用`pack()`方法将其添加到窗口的最右侧。例如:
```python
# remove the scrollbar from the window
scrollbar.pack_forget()
# add the scrollbar to the right side of the window
scrollbar.pack(side="right", fill="y")
```
阅读全文