Python GUI 编程:tkinter 初学者入门指南——滚动条

发布时间:2024-10-19 02:25  浏览量:10

在本文中,将介绍 tkinter Scrollbar 滚动条小部件以及如何将其链接到其他可滚动的小部件。

Scrollbar 滚动条小部件允许用户浏览窗口中显示不完整的内容,通常与文本框、列表框和画布等小部件一起使用,以处理大量数据。

要使用滚动条小部件,需要创建一个滚动条小部件,将滚动条与可滚动小部件链接起来。

使用构造函数创建滚动条。

scrollbar = tk.Scrollbar(
master,
orient='vertical',
command=widget.yview
)

在此语法中,orient 参数指定滚动条是水平滚动还是垂直滚动。command 参数允许滚动条与可滚动小部件的关联的过程。

文本小部件添加滚动条

import tkinter as tk
root = tk.Tk
root.geometry('600x400+200+200')
root.title('Scrollbar 滚动条演示')
# 创建文本小部件
text = tk.Text(root, height=17, width=53, font=("Arial", 14), wrap="none")

# 创建垂直滚动条
scrollbar1 = tk.Scrollbar(root, orient='vertical', command=text.yview)
scrollbar1.pack(side=tk.RIGHT, fill="y")
# 创建水平滚动条
scrollbar2 = tk.Scrollbar(root, orient="horizontal", command=text.xview)
scrollbar2.pack(side=tk.BOTTOM, fill="x")
# 将滚动条与文本小部件关联
text['yscrollcommand'] = scrollbar1.set
text['xscrollcommand'] = scrollbar2.set

text.pack(side=tk.LEFT, fill="both")

for i in range(1,50):
position = f'{i}.0'
text.insert(position,f'Line {i}\n');
root.mainloop

列表框添加滚动条

import tkinter as tk
root = tk.Tk
root.geometry('600x400+200+200')
root.title('Scrollbar 滚动条演示')
# 创建列表框小部件
listbox = tk.Listbox(root, width=83, height=20)
listbox.pack(side=tk.LEFT)
# 创建垂直滚动条
scrollbar1 = tk.Scrollbar(root, orient='vertical', command=listbox.yview)
scrollbar1.pack(side=tk.RIGHT, fill="y")
# 将滚动条与列表框小部件关联
listbox['yscrollcommand'] = scrollbar1.set
for i in range(1,50):
listbox.insert(tk.END,f'Line {i}\n');
root.mainloop

画布添加滚动条

import tkinter as tk
root = tk.Tk
root.geometry('600x400+200+200')
root.title('Scrollbar 滚动条演示')

# 创建canvas 画布
canvas = tk.Canvas(root, bg='white', scrollregion=(0,0,500,500))

#创建垂直滚动条
scrollbar1 = tk.Scrollbar(root, orient='vertical', command=canvas.yview)
scrollbar1.pack(side=tk.RIGHT, fill="y")
# 创建水平滚动条
scrollbar2 = tk.Scrollbar(root, orient="horizontal", command=canvas.xview)
scrollbar2.pack(side=tk.BOTTOM, fill="x")
# 将滚动条与列表框小部件关联
canvas['yscrollcommand'] = scrollbar1.set
canvas['xscrollcommand'] = scrollbar2.set
canvas.pack(side=tk.LEFT, expand = True, fill = 'both')

canvas.create_rectangle(50, 50, 150, 150, fill="blue")
root.mainloop

Scrollbar 滚动条常用选项

标签: 滚动条 tkinter gui

外部推荐