from tkinter import *
import requests
from lxml import etree
def post_word(word):
url = 'http://dict.youdao.com/search?q=%s&keyfrom=new-fanyi.smartResult' % word
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36 Edg/87.0.664.66'}
res = requests.get(url,headers=headers)
tree = etree.HTML(res.text)
result = tree.xpath('//div[@class="trans-container"]/ul/li/text()')
return result[0:4]
def creat_windows():
root = Tk()
root.title('单词查询器.by1784013953')
v1 = StringVar()
Label(root,text='输入单词').grid(row=0,column=0)
Label(root,text='翻译结果').grid(row=1,column=0)
Entry(root,textvariable=v1).grid(row=0,column=1)
text = Text(root,width=40,height=5)
text.grid(row=1,column=1, sticky=S + W + E + N)#加了个定位
def show():
word = v1.get()
for each in (post_word(word)):
text.insert(END,each)
text.insert(END,'\n')
def brea():
root.destroy()
Button(root,text='翻译',width=10,command=show).grid(row=2,column=0,sticky=W,ipadx=10,ipady=5)
Button(root,text='退出',width=10,command=brea).grid(row=2,column=3,sticky=E,ipadx=10,ipady=5)
#这以下三行捋一捋关系,关键还是在定位,你那样是滚动条的位置覆盖了文本框位置
sb = Scrollbar(command=text.yview)
text.config(yscrollcommand = sb.set)
sb.grid(row=1,column=2, sticky=S + W + E + N)#加了个定位
#给个建议最好还是不要def下面再def,class就好多了。
mainloop()
if __name__ == '__main__':
creat_windows()
|