How to get a horizontal scrollbar in Tkinter?

限于喜欢 提交于 2021-02-19 04:08:45

问题


I'm learning Tkinter at the moment. From my book, I get the following code for producing a simple vertical scrollbar:

from tkinter import * # Import tkinter

class ScrollText:
    def __init__(self):
        window = Tk() # Create a window
        window.title("Scroll Text Demo") # Set title

        frame1 = Frame(window)
        frame1.pack()
        scrollbar = Scrollbar(frame1)
        scrollbar.pack(side = RIGHT, fill = Y)
        text = Text(frame1, width = 40, height = 10, wrap = WORD,
                    yscrollcommand = scrollbar.set)
        text.pack()
        scrollbar.config(command = text.yview)

        window.mainloop() # Create an event loop

ScrollText() # Create GUI

which produces the following nice output: enter image description here

However, when I then try to change this code in the obvious way to get a horizontal scrollbar, it's producing a weird output. Here's the code I'm using

from tkinter import * # Import tkinter

class ScrollText:
    def __init__(self):
        window = Tk() # Create a window
        window.title("Scroll Text Demo") # Set title

        frame1 = Frame(window)
        frame1.pack()
        scrollbar = Scrollbar(frame1)
        scrollbar.pack(side = BOTTOM, fill = X)
        text = Text(frame1, width = 40, height = 10, wrap = WORD,
                    xscrollcommand = scrollbar.set)
        text.pack()
        scrollbar.config(command = text.xview)

        window.mainloop() # Create an event loop

ScrollText() # Create GUI

and here's what I get when I run this: enter image description here


回答1:


You're assigning horizontal scrolling, xscrollcommand, to a vertical scrollbar. You need to modify Scrollbar's orient option to 'horizontal' which is by default 'vertical'.

Try replacing:

scrollbar = Scrollbar(frame1)

with:

scrollbar = Scrollbar(frame1, orient='horizontal')


来源:https://stackoverflow.com/questions/47954758/how-to-get-a-horizontal-scrollbar-in-tkinter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!