创建两个按钮方法Python

时间:2014-04-01 00:16:52

标签: python button

我正在用Python创建一个基于用户输入创建形状的程序。我需要创建两个函数来使用Zeller's graphic.py文件创建按钮。一个按钮需要说Quit,第二个需要说Process。这是我到目前为止,但正如你所看到的,它们不在定义的函数中:

#create Quit button
quitButton = Text(Point(70,73), "Quit")
quitButton.draw(w)
Rectangle(Point(45, 50), Point(95,97)).draw(w)

#create Process button
enterButton = Text(Point(145,73), "Process")
enterButton.draw(w)
Rectangle(Point(120, 48), Point(170,98)).draw(w)

以下是必要方法的说明

  • createButton(text, pt1button, pt2button, win)创建一个带角点pt1buttonpt2button的矩形,窗口中显示居中文字
  • 如果clickedButton(button, clickPt)在按钮中,则
  • clickPt会返回true / false。

我尝试创建该函数并收到以下错误。

这是我的功能:

def createButton(text, pt1button, pt2button, win):
    button = Text(Point(pt1button, pt2button), text)
    button.draw(win)

这是我调用函数的地方:

createButton("Process",145,73,win) 
createButton("Quit",70,73,win) 

以下是引发的错误:

Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/project4FINAL.p‌​y", line 77, in <module> main()
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/project4FINAL.p‌​y", line 27, in main buttonCreate("Process", 145,73, win)
NameError: global name 'win' is not defined 

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

因此,从查看代码看,您希望为每个按钮创建一个回调函数,然后通过setMouseHandler的{​​{1}}方法将每个按钮分配给画布。

所以从API中给出的示例:

GraphWin

除非您已经检查了回调(要查看画布上鼠标在哪个形状内),每个绘制的形状应该只有一个画布。

使用from graphics import * def example_callback(): print "I love unicorns!" def main(): # win is a Canvas with a setMouseHandler method win = GraphWin("My Circle", 100, 100) c = Circle(Point(50,50), 10) c.draw(win) #Add a callback to the canvas c.cavas.setMouseHandler(example_callback) # or win.setMouseHandler(example_callback) win.getMouse() # Pause to view result win.close() # Close window when done main() 函数后的示例:

createButton

以下是使用新Button对象的完整示例:

def createButton(text, pt1button, pt2button, win):
    button = Text(Point(pt1button, pt2button), text)
    button.draw(win)
    return button

def _callback(pt):
   print "I love unicorns!"
   print
   print "Mouse clicked at x=%d, y=%d"%(pt.x,pt.y)
   print

def test():
   win = GraphWin()
   win.setCoords(0,0,100,100)
   quitButton = createButton("Quit",70,73,win)
   Rectangle(Point(45, 50), Point(95,97)).draw(win)
   win.setMouseHandler(_callback)
   while True:
      win.getMouse()
   win.close()