附加带有 google 搜索结果的 tkinter 文本小部件

appending a tkinter text widget with google search results

早上好, 现在我正在努力使用一个小程序,它可以让你在 tkinter GUI 中搜索 google。按下按钮后,它应该会显示该结果的所有链接(对我而言,我将其限制为 10 个)。 我的程序可以运行,但它不会附加文本框,而只会显示查询的最后结果。 我代码的重要部分从 def clicked() 开始。

import tkinter
import PIL.Image, PIL.ImageTk
import cv2
from googlesearch import search

window = tkinter.Tk()

window.title("Google Search")
window.geometry('1000x1000')

img = "pics1/dt.jpg"
img2 = "pics2/donald.jpg"
cv_img = cv2.imread(img)
cv_img2 = cv2.imread(img2)
height, width, no_channels = cv_img.shape
height, width, no_channels = cv_img2.shape
canvas = tkinter.Canvas(window, width = 300, height = 300)
canvas.grid(row=0, column=2)
photo = PIL.ImageTk.PhotoImage(image = PIL.Image.fromarray(cv_img))
canvas.create_image(0, 0, image=photo, anchor=tkinter.NW)

######


txt = tkinter.Entry(window,width=10)
txt.grid(column=0, row=1)
lbl = tkinter.Label(window, text="Who do you want to search?")
lbl.grid(column=0, row=0)


canvas2 = tkinter.Canvas(window, width = 300, height = 300)
canvas2.grid(row=0, column=1)
photo2 = PIL.ImageTk.PhotoImage(image = PIL.Image.fromarray(cv_img2))
canvas2.create_image(0, 0, image=photo2, anchor=tkinter.NW)

query = ""

def clicked():
    res = "Thanks"
    global query
    query = txt.get()
    lbl.configure(text=res)

    for j in search(query, tld='com', lang='en', num=10, start=0, stop=10, pause=2):
        final = tkinter.Text(window, text=j)

btn = tkinter.Button(window, text="Search", command=clicked)
btn.grid(column=0, row=3)





window.mainloop()

谢谢

解决方案是从函数中删除文本小部件的创建,而是在脚本的主要部分创建它。然后,调用 insert 方法插入文本小部件。

window = tkinter.Tk()
...
text = tkinter.Text(window)
# this is just guessing where you want it; put
# it wherever you want. 
text.grid(row=2, column=0, columnspan=3)
...

def clicked():
    ...
    for j in search(query, tld='com', lang='en', num=10, start=0, stop=10, pause=2):
        text.insert("end", j)

如果结果未以换行符结尾,您将需要添加一个。例如:

text.insert("end", j+"\n")