python tkinter frame滚动条_Tkinter,Python中框架的垂直滚动条

My aim is to have a scrollbar that stays at the right-side of a full-screen window, allowing the user to scroll up and down through various different widgets (such as labels & buttons).

From other answers I've seen on this site, I've come to the conclusion that a scrollbar has to be assigned to a canvas in order for it to function properly, which I have tried to include in my code but have not had much success with.

The below code shows a simplified version of what I've managed to accomplish so far:

from tkinter import *

root = Tk()

root.state("zoomed")

root.title("Vertical Scrollbar")

frame = Frame(root)

canvas = Canvas(frame)

Label(canvas, text = "Test text 1\nTest text 2\nTest text 3\nTest text 4\nTest text 5\nTest text 6\nTest text 7\nTest text 8\nTest text 9", font = "-size 100").pack()

scrollbar = Scrollbar(frame)

scrollbar.pack(side = RIGHT, fill = Y)

canvas.configure(yscrollcommand = scrollbar.set)

canvas.pack()

frame.pack()

root.mainloop()

I'm facing two issues when running this code:

One is that the scrollbar is inactive, and doesn't allow for the user to scroll down to view the rest of the text.

The other is that the scrollbar is attached to the right-side of the text, rather than the right-side of the window.

So far, none of the other answers I've found on this site have enabled me to amend my code to support a fully-functioning scrollbar for my program. I'd be very grateful for any help anyone reading this could provide.

解决方案

It shows how to create scrolled frame - and then you can add all widgets in this frame.

import tkinter as tk

def on_configure(event):

# update scrollregion after starting 'mainloop'

# when all widgets are in canvas

canvas.configure(scrollregion=canvas.bbox('all'))

root = tk.Tk()

# --- create canvas with scrollbar ---

canvas = tk.Canvas(root)

canvas.pack(side=tk.LEFT)

scrollbar = tk.Scrollbar(root, command=canvas.yview)

scrollbar.pack(side=tk.LEFT, fill='y')

canvas.configure(yscrollcommand = scrollbar.set)

# update scrollregion after starting 'mainloop'

# when all widgets are in canvas

canvas.bind('', on_configure)

# --- put frame in canvas ---

frame = tk.Frame(canvas)

canvas.create_window((0,0), window=frame, anchor='nw')

# --- add widgets in frame ---

l = tk.Label(frame, text="Hello", font="-size 50")

l.pack()

l = tk.Label(frame, text="World", font="-size 50")

l.pack()

l = tk.Label(frame, text="Test text 1\nTest text 2\nTest text 3\nTest text 4\nTest text 5\nTest text 6\nTest text 7\nTest text 8\nTest text 9", font="-size 20")

l.pack()

# --- start program ---

root.mainloop()

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值