我正在尝试在应用程序内部显示B4按钮,但它没有在其中显示并产生“B4未定义”
from tkinter import *
import tkinter
top = tkinter.Tk()
B1 = tkinter.Button(top, text ="circle", relief=RAISED,\
cursor="circle")
B2 = tkinter.Button(top, text ="plus", relief=RAISED,\
cursor="plus")
B3 = tkinter.Button(top, text=u"good !",relief=RAISED,\
cursor="plus")
def initialise(self):
self.grid()
B4 = tkinter.Button(self,text=u"Click me !",
command=self.OnButtonClick)
button.grid(column=1,row=0)
def OnButtonClick(self):
print( "You clicked the button" )
B1.pack()
B2.pack()
B3.pack()
B4.pack()
initialise()
top.mainloop()
答案 0 :(得分:0)
您的问题是函数initialize
的范围不会扩展到主程序。因此,B4
未定义。
此外,您没有将任何内容传递给initialise
。
相反,您可以将B4
设为全局,也可以将其从函数中删除。
<强> global
强>:
from Tkinter import *
import Tkinter
global B4
top = Tkinter.Tk()
B1 = Tkinter.Button(top, text ="circle", relief=RAISED,\
cursor="circle")
B2 = Tkinter.Button(top, text ="plus", relief=RAISED,\
cursor="plus")
B3 = Tkinter.Button(top, text=u"good !",relief=RAISED,\
cursor="plus")
def initialise(self):
global B4
self.grid()
B4 = Tkinter.Button(self,text=u"Click me !",
command=OnButtonClick(self))
B4.grid(column=1,row=0)
def OnButtonClick(self):
print( "You clicked the button" )
initialise(top)
B1.pack()
B2.pack()
B3.pack()
B4.pack()
#initialise()
top.mainloop()
运行方式:
bash-3.2 $
You clicked the button
功能之外:
from Tkinter import *
import Tkinter
top = Tkinter.Tk()
top.grid()
def OnButtonClick(self):
print( "You clicked the button" )
B1 = Tkinter.Button(top, text ="circle", relief=RAISED,\
cursor="circle")
B2 = Tkinter.Button(top, text ="plus", relief=RAISED,\
cursor="plus")
B3 = Tkinter.Button(top, text=u"good !",relief=RAISED,\
cursor="plus")
B4 = Tkinter.Button(top,text=u"Click me !",
command=OnButtonClick(top))
B4.grid(column=1,row=0)
B1.pack()
B2.pack()
B3.pack()
B4.pack()
top.mainloop()
运行方式:
bash-3.2 $
You clicked the button
示例:
>>> def foo():
... bar = 6
...
>>> bar
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'bar' is not defined
>>>