使用Python Tkinter开发GUI搜索引擎遇问题,求解决方法
问题分析与解决
问题1:找不到Search按钮
你的代码里有两个导致按钮不显示/无法正常工作的问题:
- 窗口尺寸设置错误:
structure.geometry("1280*1280")里的*要改成小写的x,tkinter的geometry方法只识别x作为宽高分隔符,用*会导致窗口使用默认尺寸,按钮放在x=100,y=200可能超出可视范围。 - 按钮的
command参数写错了:你定义的搜索函数是searches(),但按钮里写的是command=search,少了末尾的s,就算按钮显示,点击也会触发报错。
问题2:按下回车键无搜索结果
你没给输入框绑定回车键触发搜索的事件,需要添加绑定逻辑,让回车键按下时调用搜索函数。
额外优化:谷歌搜索请求被拦截
直接用requests.get请求谷歌搜索大概率会被识别为爬虫拦截,需要给请求添加User-Agent头伪装成浏览器请求,否则拿不到正确的搜索结果。
修正后的完整代码
import requests import webbrowser from bs4 import BeautifulSoup from tkinter import * structure = Tk() # 修正窗口尺寸分隔符为x structure.geometry("1280x1280") structure.title("Cgo Engine") label = Label(structure, text="Cgo Engine", bg="dark grey", fg="Gold", font=("ComicSans", 60, "italic")) label.pack(side=TOP) structure.config(background="dark grey") text = StringVar() def searches(): # 添加User-Agent头,避免被谷歌拦截 headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36" } # 用f-string拼接URL更清晰 url = f"https://www.google.com/search?q={text.get()}" data = requests.get(url, headers=headers) soup = BeautifulSoup(data.content, "html.parser") result = soup.select(".kCrYT a") for ans in result[:6]: search = ans.get("href") if search.startswith("/url?q="): search = search[7:] search = search.split("&")[0] webbrowser.open(search) # 微调标签位置,避免太靠右 label = Label(structure, font=("Times", 15, "bold"), text="Enter here to search", bg="black", fg="yellow") label.place(x=400, y=350) # 微调输入框位置,让布局更合理 enter = Entry(structure, font=("Times", 15, "bold"), textvar=text, width=60, bd=2, bg="white") enter.place(x=300, y=500) # 修正command参数,同时调整按钮位置到输入框下方居中 button = Button(structure, text="Search", font=("Times", 15, "bold"), width=10, bd=2, bg="white", command=searches) button.place(x=580, y=600) # 绑定回车键触发搜索 enter.bind("<Return>", lambda event: searches()) structure.mainloop()
内容的提问来源于stack exchange,提问作者user20578619
相关产品推荐
相关产品推荐

