某些輸出會創建太多文本,如果不在出現的新視窗中添加滾動條,就無法查看這些文本。
例如,在下面的這段代碼中,如果視窗中要回傳的檔案很多,您將無法查看所有文本,因此需要滾動條。如何才能做到這一點?
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()
滾動條如何按預期作業?
uj5u.com熱心網友回復:
滾動條正常作業,但您將文本放入錯誤的小部件中。
def get_filenames():
filenames = sorted(os.listdir('.'))
#text.delete(0, 'end') # remove previous content
text.insert('end', "\n".join(filenames))
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/489888.html
