带有Tkinter和webbrowser的Python 3.2-搜索程序
正如标题所示,我正在尝试用GUI创建一个小的搜索工具。 我希望它如何工作:当我单击“搜索”按钮时,打开“”+我要搜索的关键字。我将输入这些关键词 全部代码:带有Tkinter和webbrowser的Python 3.2-搜索程序,python,python-3.x,tkinter,python-webbrowser,Python,Python 3.x,Tkinter,Python Webbrowser,正如标题所示,我正在尝试用GUI创建一个小的搜索工具。 我希望它如何工作:当我单击“搜索”按钮时,打开“”+我要搜索的关键字。我将输入这些关键词 全部代码: from tkinter import * import webbrowser class MainClass(): def __init__(self,master): self.parent=master self.gui() def gui(self): self.
from tkinter import *
import webbrowser
class MainClass():
def __init__(self,master):
self.parent=master
self.gui()
def gui(self):
self.Source=StringVar()
#This next line I just tried out to use 'what' instead of 'str(self.Source) in def search(self)
what=Entry(myGUI, textvariable=self.Source).grid(row=9, column=2)
label4=Label(myGUI, text='Key words:', fg= 'Black').grid(row=9, column=1)
button4=Button(myGUI, text=" Search ", command=self.search).grid(row=18, column=1)
def search(self):
webbrowser.open('http://google.com/?gws_rd=cr&ei=qr5cU8GJGMnStAao1YG4BA#q=' + str(self.Source.get))
if __name__ == '__main__':
myGUI=Tk()
app=MainClass(myGUI)
myGUI.geometry("300x100+100+200")
myGUI.title('Google search')
myGUI.mainloop()
我遇到的问题是这一行:
def search(self):
webbrowser.open('http://google.com/?gws_rd=cr&ei=qr5cU8GJGMnStAao1YG4BA#q=' + str(self.Source.get))
如果我保持原样并单击搜索按钮,它将打开google并搜索:
'位于0x0301EE90的tkinter.StringVar对象的绑定方法StringVar.get'
如果我保留该行,但使用str(self.Source.get)代替str(self.Source),它会再次打开google,但这次它会搜索:PY_VAR0
如果我只使用self.Source,当我按下搜索按钮时,它会给我一个错误“无法将'StringVar'对象隐式转换为str”
所以我有点困惑如何正确使用它,请帮助。您必须实际调用get方法
self.Source.get()
,否则,您提供给str
的是方法,而不是它的返回值
因此,整条线路将是
webbrowser.open('http://google.com/?gws_rd=cr&ei=qr5cU8GJGMnStAao1YG4BA#q=' + str(self.Source.get()))
难以置信,如此简单,但它却奏效了!非常感谢你。我本以为我的问题会更复杂一点,但只使用self.Source.get()而不是self.Source.get就能解决问题。