Home > Mobile >  Add a scrollbar in the text that appears after a button
Add a scrollbar in the text that appears after a button

Time:06-12

Some outputs create too much text that cannot be viewed without adding a scrollbar in the new window that appears.

For example, in this code below, if there are many files to be returned in the window, you will not be able to view all the text and therefore a scrollbar is needed. How can this be done?

import os
import tkinter as tk


def get_filenames():
    filenames = sorted(os.listdir('.'))
    text = "\n".join(filenames)
    label['text'] = text # change text in label

root = tk.Tk()
    
# create the text widget
text = tk.Text(root, height=10)
text.grid(row=0, column=0, sticky=tk.EW)

text.grid_columnconfigure(0, weight=1)
text.grid_rowconfigure(0, weight=1)
tk.Button(root, text="OK", command=get_filenames).grid()

# create a scrollbar widget and set its command to the text widget
scrollbar = ttk.Scrollbar(root, orient='vertical', command=text.yview)
scrollbar.grid(row=0, column=1, sticky=tk.NS)

#  communicate back to the scrollbar
text['yscrollcommand'] = scrollbar.set
label = tk.Label(root) # empty label 
label.grid()

root.mainloop()

How can the scrollbar work as expected?

CodePudding user response:

Scrollbar works correctly but you put text in wrong widget.

def get_filenames():
    filenames = sorted(os.listdir('.'))
    #text.delete(0, 'end')  # remove previous content
    text.insert('end', "\n".join(filenames))
  • Related