我试图创建一个web浏览器,但我对tkinter有问题,这是代码,但它给了我一个错误:
File "C:\Users\Fulvio\Desktop\OpenBrowser.py", line 10, in callback
b=b+x+"&oq="+x+"&gs_l=serp.3..0l10.131037.133187.0.133344.13.9.1.3.3.0.195.895.0j6.6.0....0...1c.1.52.serp..3.10.922.ssgKbcBrPr0"
NameError: global name 'x' is not defined
这是代码:
import webbrowser
from Tkinter import *
def retrieve_input():
global x
x = self.myText_Box.get("0.0", 'END-1c')
def callback():
b = "https://www.google.it/search?q="
b=b+x+"&oq="+x+"&gs_l=serp.3..0l10.131037.133187.0.133344.13.9.1.3.3.0.195.895.0j6.6.0....0...1c.1.52.serp..3.10.922.ssgKbcBrPr0"
if self.myText_Box.get("0.0", END)=="text":
webbrowser.open(b)
top = Tk()
myText_Box = Label(top, text="Cerca")
myText_Box.grid(row=0, column=0)
E1 = Entry(top, bd = 5)
E1.grid(row=0, column=1)
MyButton1 = Button(top, text="Submit", width=10, command=callback)
MyButton1.grid(row=1, column=1)
top.mainloop()
很抱歉,如果代码不是灰色的,但我不知道它是怎么做的
答案 0 :(得分:0)
修复 b
callback
的分配语法
移入课程将使您能够使用class-instance-variable而无需诉诸 global x
避免global
- s,除非非常特殊的需要确实需要' em
from Tkinter import * # just re-shaped into a Class-mode
import webbrowser # no app.logic revisions here
class aTkGuiApplication():
def __init__( self, master ): # .INIT auto-exec'd method to setup <self>
root = master
self.x = 'init' # .DEF <self>.x instance-variable
self.myText_Box = Label( root, ... # .DEF <self>.myText_Box instance
self.E1 = Entry( root,
bd = 5
)
self.MyButton1 = Button( root,
text = "Submit",
width = 10,
command = callback
)
self.E1.grid( row = 0, column = 1 )
self.myText_Box.grid( row = 0, column = 0 )
self.MyButton1.grid( row = 1, column = 1 )
def callback( self ): # .GUI Event-<control-loop>
self.b = "https://www.google.it/search?q=" # .SET <self>.b
self.b = self.b + self.x + "&og=" + self.x + "...etc...etc..."
if self.myText_Box.get( "0.0", END ) == "text":
webbrowser.open( self.b )
def retrieve_input(): # Erratum:
self.x = self.myText_Box.get( "0.0", 'END-1c' ) # .SET <self>.x a new value ...
aRootUiWINDOW = Tk() # .GUI <Tk()> context
aRootUiWINDOW.title( 'Web TkGUI... v0.0' ) # .SET w.[TITLE]
aRootUiWINDOW.geometry( '1200x600-50-50') # .SET w.size ... 1200 x 600 [px] w.right-edge -50[px] left from screen-right, w.bottom-edge -50[px] up from screen-botton
aRootUiWINDOW.configure( background = 'black' ) # .SET w.bg
app = GuiApplication( aRootUiWINDOW ) # .SET <app>
aRootUiWINDOW.lift() # .SET visible
aRootUiWINDOW.mainloop() # .GUI controller