我的以下代码要求用户导入文件,然后它将显示在标签上。一旦标签显示大的内容(即大文本文件),就会显示AutoScrollbar。我尝试过代码,但导入大文本文件时不会出现AutoScrollbar:
import tkinter
from tkinter import *
from tkinter.filedialog import askopenfile
from tkinter.filedialog import askopenfilename
class AutoScrollbar(Scrollbar):
def set(self, lo, hi):
if float(lo) <= 0.0 and float(hi) >= 1.0:
self.tk.call("grid", "remove", self)
else:
self.grid()
Scrollbar.set(self, lo, hi)
def pack(self, **kw):
raise TclError ("cannot use pack with this widget")
def place(self, **kw):
raise TclError ("cannot use place with this widget")
def import_txt():
global import_list
file_name = askopenfilename(filetypes=[("Text files","*.txt")])
import_list = []
with open(file_name, 'r') as f:
go.grid()
import_list = f.readlines()
f.close()
def display():
go.grid_forget()
start.grid_forget()
global import_list
new = "".join(import_list)
canvas.create_text(100,10, anchor=NW, text=str(new))
canvas.grid()
window = tkinter.Tk()
vscrollbar = AutoScrollbar(window)
vscrollbar.grid(row=0, column=1, sticky=N+S)
hscrollbar = AutoScrollbar(window, orient=HORIZONTAL)
hscrollbar.grid(row=1, column=0, sticky=E+W)
canvas = Canvas(window,
yscrollcommand=vscrollbar.set,
xscrollcommand=hscrollbar.set)
canvas.grid(row=0, column=0, sticky=N+S+E+W)
vscrollbar.config(command=canvas.yview)
hscrollbar.config(command=canvas.xview)
window.grid_rowconfigure(0, weight=1)
window.grid_columnconfigure(0, weight=1)
frame = Frame(canvas)
frame.rowconfigure(1, weight=1)
frame.columnconfigure(1, weight=1)
canvas.create_window(0, 0, anchor=NW, window=frame)
frame.update_idletasks()
canvas.config(scrollregion=canvas.bbox("all"))
disp = tkinter.Label(window)
start = tkinter.Button(window, text="Import", command=import_txt)
start.grid()
go = tkinter.Button(window, text="GO", command=display)
window.mainloop()
我也尝试过使用:
disp.config(text=str(new))
disp.grid()
但AutoScrollbar仍然不会出现。