Python制作百度UI版
Python制作简易百度不是UI版本,是一个黑框,整体效果不佳。所以这一期我们把它改造成UI版。
大致思路
我们已经掌握简易百度的核心代码,现在只是增加一个窗口,所以问题不大。
- 先导入tkinter库(老熟人了)
- 然后建构一个窗口
- 再把核心代码打包进函数
- 制作输入框和搜索按钮,当按下按钮触发函数
分析代码
前3步都不难,第4步需要简单说一下
因为tkinter的输入框没有灰色初始字体,只能用Label标题的形式。但这就需要两个控件进行连接,但也不难,代码如下:
bt = tk.Label(root, text="百度一下:")
bt.grid(row=0)
sr = tk.Entry(root,width=33)
sr.grid(row=0, column=1)
bt是标题的缩写,sr是输入的缩写
完整代码
上一步做完了就完成了,可以上代码了:
import webbrowser
import requests
import tkinter as tk
root=tk.Tk()
root.title("百度搜索")
x = root.winfo_screenwidth()
y = root.winfo_screenheight()
xx = 300
yy = 70
xxx = (x - xx) / 2
yyy = (y - yy) / 2
root.geometry("%dx%d+%d+%d" % (xx, yy, xxx, yyy))
def core():
wd=sr.get()
url = 'https://www.baidu.com/s?wd=' + wd
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:92.0) Gecko/20100101 Firefox/92.0', }
response = requests.get(url=url, headers=headers)
fileName = 'baidu.html'
with open(fileName, 'w', encoding='utf-8') as fp:
fp.write(response.text)
webbrowser.open(fileName)
bt = tk.Label(root, text="百度一下:")
bt.grid(row=0)
sr = tk.Entry(root,width=33)
sr.grid(row=0, column=1)
search = tk.Button(root, text="搜索",command=core)
search.grid(row=2, column=0, sticky=tk.W, padx=20)
root.mainloop()
具体core函数意思见上一期详解。