首页 > 解决方案 > 文本小部件上的水平滚动条不起作用

问题描述

我有一个小程序,可以将长字符串的一个或多个迭代加载到文本字段中。我设置了一个水平滚动条,让我可以在很长的文本字符串中移动。我想我已经在文本小部件和滚动条之间设置了所有东西(至少它看起来像我为垂直滚动条工作的其他代码),但滚动条似乎未激活。无论文本获得多长时间,它基本上都不起作用。

除了水平滚动条之外,有关此代码的其他所有内容似乎都可以正常工作。

我究竟做错了什么?代码中是否还有其他内容关闭滚动条?

    import tkinter as tk
    from tkinter import messagebox

    win=tk.Tk()

    text=tk.Text(win, height=1, font='Helvetica 12')
    text.pack(side='top', padx=5, pady=5,fill='x')
    text.tag_configure('bold', font='Helvetical 12 bold', foreground='red')
    hscroll=tk.Scrollbar(win, orient='horizontal',command=text.xview)
    hscroll.pack(side='top',fill='x')
    text.configure(xscrollcommand=hscroll.set)
    text.configure(state='normal')


    x='(<data field> == <literal>) and ((<data field> == <data field>) or (<data field> == <data field>))'

   def insert_characters():
        global x
        text.configure(state='normal')
        text.insert('end', x) 
        content=text.get("1.0","end-1c")
        messagebox.showinfo('',len(content))

    def delete_characters():
        text.configure(state='normal')
        text.delete('1.0','1.500')
        text.configure(state='disabled')

    def get_field_list(string):
        field_list=[]
        for i in range(len(string)):
            if string[i]=='<':
                start=i
            elif string[i]=='>':
                stop=i
                field_list.append((start, stop))
            else:
                continue
         return field_list

    def highlight_fields(field_list):
        for f in field_list:
            start='1.{0}'.format(f[0])
            stop='1.{0}'.format(f[1]+1)

            text.tag_add('highlight', start, stop)
            text.tag_configure('highlight',background='yellow',
                       font='Helvetica 12 bold')
            messagebox.showinfo('',start+'\n'+stop)
            text.tag_delete('highlight')

    def do_highlights():
        global x
        field_list=get_field_list(x)
        highlight_fields(field_list)


    insertButton=tk.Button(win, text='Insert',
                           command=insert_characters)
    insertButton.pack(side='bottom', padx=5, pady=5)

    deleteButton=tk.Button(win, text='Delete',
                           command=delete_characters)
    deleteButton.pack(side='bottom', padx=5, pady=5)

    highlightButton=tk.Button(win, text='Highlight',
                              command=do_highlights)
    highlightButton.pack(side='bottom', padx=5, pady=5)

    win.mainloop()

标签: python-3.xtkinterscrollbartext-widget

解决方案


您尚未为wrap文本小部件的选项指定值,因此默认情况下小部件中的文本将在窗口边缘换行。如果文本被换行,则永远不会超出右边距,因此滚动条是无用的。

wrap如果您希望滚动条起作用,请通过将小部件的选项设置为字符串“none”来关闭换行。

text=tk.Text(win, height=1, font='Helvetica 12', wrap="none")

推荐阅读