水平滚动条在Tkin中不起作用

2024-09-25 00:25:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我想创建一个基于tkinter的GUI程序。其中一个小部件是Text。我想在其中添加一个水平滚动条,但它不起作用。

我错在哪里了?

from Tkinter import *
import tkFont


class DpWin(object):

    def run(self):
        root=Tk()
        root.geometry('768x612')
        title='dp'
        root.title(title)

        xscrollbar = Scrollbar(root, orient=HORIZONTAL)
        xscrollbar.pack(side=BOTTOM, fill=X)

        yscrollbar = Scrollbar(root)
        yscrollbar.pack(side=RIGHT, fill=Y)

        text = Text(root,xscrollcommand=xscrollbar.set,yscrollcommand=yscrollbar.set)
        text.pack()

        xscrollbar.config(command=text.xview)
        yscrollbar.config(command=text.yview)
        text.insert(END,'a'*999)
        mainloop()

    def start(self):
        self.b_start.config(state=DISABLED)
        self.b_stop.config(state=ACTIVE)

    def stop(self):
        self.b_stop.config(state=DISABLED)
        self.b_start.config(state=ACTIVE)


if __name__=='__main__':
    win=DpWin()
    win.run()

Tags: textimportselfconfigtitledefrootstart
2条回答

我已经根据here修改了您的代码。主要有两个不同点。

  1. 我这样做是为了不让文本框包装起来。如果换行文本,则水平滚动条没有可滚动的内容。

  2. 我使用框架上的网格几何管理器将滚动条和文本小部件放在一起。使用.grid的好处是您实际上得到了正确宽度/高度的滚动条(这是使用pack无法实现的)。

。。。

from Tkinter import *
import tkFont

class DpWin(object):
    def run(self):
        root=Tk()
        root.geometry('768x612')
        title='dp'
        root.title(title)

        f = Frame(root)
        f.pack()

        xscrollbar = Scrollbar(f, orient=HORIZONTAL)
        xscrollbar.grid(row=1, column=0, sticky=N+S+E+W)

        yscrollbar = Scrollbar(f)
        yscrollbar.grid(row=0, column=1, sticky=N+S+E+W)

        text = Text(f, wrap=NONE,
                    xscrollcommand=xscrollbar.set,
                    yscrollcommand=yscrollbar.set)
        text.grid(row=0, column=0)

        xscrollbar.config(command=text.xview)
        yscrollbar.config(command=text.yview)
        text.insert(END, 'a'*999)
        mainloop()

    def start(self):
        self.b_start.config(state=DISABLED)
        self.b_stop.config(state=ACTIVE)

    def stop(self):
        self.b_stop.config(state=DISABLED)
        self.b_start.config(state=ACTIVE)

if __name__=='__main__':
    win=DpWin()
    win.run()

有一条关于让x和y滚动条在pack框架中工作的评论。下面是一个简单的例子:

import tkinter as tk
from tkinter import X, Y, BOTTOM, RIGHT, LEFT, Y, HORIZONTAL
class TextExample(tk.Frame):
    def __init__(self, master=None):
        super().__init__()

        sy = tk.Scrollbar(self)
        sx = tk.Scrollbar(self,  orient=HORIZONTAL)
        editor = tk.Text(self, height=500, width=300, wrap='none')
        sx.pack(side=BOTTOM, fill=X)
        sy.pack(side=RIGHT, fill=Y)
        editor.pack(side=LEFT, fill=Y)
        sy.config(command=editor.yview)
        sx.config(command=editor.xview)
        self.pack()
def main():
    root = tk.Tk()
    root.geometry("800x500+0+0")
    app = TextExample(master=root)
    root.mainloop()  
if __name__ == '__main__':
    main()   

相关问题 更多 >