问题
I have a small program that loads one or more iterations of a long string into a text field. I have set up a horizontal scrollbar to let me move across very long strings of text. I think I have everything set up between the text widget and the scrollbar (at least it looks like other code I have for a vertical scrollbar which works) but the scrollbar appears to be inactivated. No matter how long the text gets, it basically doesn't work.
Everything else about this code appears to work, except the horizontal scrollbar.
What am I doing wrong? Is something else in the code turning the scrollbar off?
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()
回答1:
You haven't specified a value for the wrap
option of the text widget, so by default the text in the widget will wrap at the edge of the window. If text is wrapped, there is never anything beyond the right margin, so scrollbars are useless.
If you want the scrollbars to work, turn wrapping off by setting the wrap
option of the widget to the string "none".
text=tk.Text(win, height=1, font='Helvetica 12', wrap="none")
来源:https://stackoverflow.com/questions/59163634/horizontal-scrollbar-on-text-widget-not-working