Skip to main content
 首页 » 编程设计

Python 3.2 with Tkinter with webbrowser之搜索程序

2024年11月01日32kerrycode

如标题所示,我正在尝试使用 GUI 创建小型搜索工具。 我希望它如何工作:当我单击“搜索”按钮时,打开“https://www.google.com/?gws_rd=cr&ei=qr5cU8GJGMnStAao1YG4BA#q=” ' + 我要搜索的关键词。这些关键词我会输入。

完整代码:

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 对象的绑定(bind)方法 StringVar.get'

如果我保留该行,但我使用 str(self.Source) 而不是 str(self.Source.get),它会再次打开 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()))