我编写了以下代码来快速抓取并显示来自维基百科的信息。除非Wiki摘要包含的信息多于框可以显示的信息,否则它的效果很好。我认为添加sticky = N + S + E + W会解决这个问题,但它似乎没有做任何事情。如果有太多信息要一次显示在文本框中,如何更新此代码以使其滚动?
在此处输入代码
import sys
from tkinter import *
import wikipedia
def search_wiki():
txt = text.get() # Get what the user entered into the box
txt = wikipedia.page(txt) # Search Wikipedia for results
txt = txt.summary # Store the returned information
lblText = Label(main, text=txt,justify=LEFT,wraplength=600, fg='black',
bg='white', font='times 12 bold').grid(row = 50,
column = 1, sticky=N+S+E+W)
main = Tk()
main.title("Search Wikipedia")
main.geometry('750x750')
main.configure(background='ivory3')
text = StringVar()
lblSearch = Label(main, text = 'Search String:').grid(row = 0, column = 0,
padx = 0, pady = 10)
entSearch = Entry(main, textvariable = text, width = 50).grid(row = 0,
column = 1)
btn = Button(main, text = 'Search', bg='ivory2', width = 10,
command = search_wiki).grid(row = 0, column = 10)
main.mainloop()
用更合适的小部件替换标签,例如
lblText = ScrolledText(main,
bg='white',
relief=GROOVE,
height=600,
#width=400,
font='TkFixedFont',).grid(row = 50,
column = 1, sticky=N+S+E+W)
如果要显示可滚动的文本,则应使用Text
小部件。你不能滚动Label
,滚动一组Labels
相对困难。 Text
小部件是目前可滚动文本的最佳选择。
感谢你的帮助。我终于想出了一切。这是我的新代码,以防任何其他人遇到此类或类似的东西。
import sys
from tkinter import *
from tkinter import scrolledtext
from wikipedia import *
def search_wiki():
txt = text.get() # Get what the user eneterd into the box
txt = wikipedia.page(txt) # Search Wikipedia for results
txt = txt.summary # Store the returned information
global texw
textw = scrolledtext.ScrolledText(main,width=70,height=30)
textw.grid(column=1, row=2,sticky=N+S+E+W)
textw.config(background="light grey", foreground="black",
font='times 12 bold', wrap='word')
textw.insert(END, txt)
main = Tk()
main.title("Search Wikipedia")
main.geometry('750x750')
main.configure(background='ivory3')
text = StringVar()
lblSearch = Label(main, text = 'Search String:').grid(row = 0, column = 0)
entSearch = Entry(main, textvariable = text, width = 50).grid(row = 0,
column = 1)
btn = Button(main, text = 'Search', bg='ivory2', width = 10,
command = search_wiki).grid(row = 0, column = 10)
main.mainloop()