我在从third(main)函数调用前两个函数时遇到麻烦。我相信我有正确的编码(忽略大小和x,y坐标)来显示di的五个面,但似乎无法弄清楚如何调用函数。

主要目的是展示di的五个面。

def dot(c,d):
 #draw each dot
 circDot1 = Circle(Point(50, 50), 5).setFill('black')
 circDot1.draw(win)
 circDot3 = Circle(Point(50, 100), 5).setFill('black')
 circDot3.draw(win)
 circDot5 = Circle(Point(100, 50), 5).setFill('black')
 circDot5.draw(win)
 circDot7 = Circle(Point(100, 100), 5).setFill('black')
 circDot7.draw(win)
 circDot4 = Circle(Point(75, 75), 5).setFill('black')
 circDot4.draw(win)

def dice(a,b):

 #build the dice
 rectDice = Rectangle(Point(115, 115), Point(275,275))
 rectDice.setFill('pink')
 rectDice.setOutline('pink')
 rectDice.draw(win)


def main():
 # Create window, call dice function
 win = GraphWin("Dice", 400, 400)
 win.setBackground("cyan")
 dice("a","b")

最佳答案

有几个问题:

您无需执行main()来运行程序,但也许您不是仅在有问题的情况下添加了它。



win是局部变量,函数无法访问它们。您应该在错误消息中以NameError: name 'win' is not defined的形式在rectDice.draw(win)中看到它。

Traceback (most recent call last):
  File "<pyshell#2>", line 30, in <module>
    main()
  File "<pyshell#2>", line 28, in main
    dice("a","b")
  File "<pyshell#2>", line 21, in dice
    rectDice.draw(win)
NameError: name 'win' is not defined


您可以添加win作为参数

def dice(win, a, b):
    #build the dice
    rectDice = Rectangle(Point(115, 115), Point(275,275))
    rectDice.setFill('pink')
    rectDice.setOutline('pink')
    rectDice.draw(win)

def main():
    # Create window, call dice function
    win = GraphWin("Dice", 400, 400)
    win.setBackground("cyan")
    dice(win, "a","b")


否则您必须将窗口分配给全局变量-在global中使用main()

def dice(a, b):
    #build the dice
    rectDice = Rectangle(Point(115, 115), Point(275,275))
    rectDice.setFill('pink')
    rectDice.setOutline('pink')
    rectDice.draw(win)

def main():
    global win

    # Create window, call dice function
    win = GraphWin("Dice", 400, 400)
    win.setBackground("cyan")
    dice("a", "b")


相同的问题在dot()



dot()中,您还有其他问题。您必须在下一行中使用setFill()

circDot1 = Circle(Point(50, 50), 5)
circDot1.setFill('black')
circDot1.draw(win)




完整代码:

from graphics import *

def dot(win, c, d):
    #draw each dot
    circDot1 = Circle(Point(50, 50), 5)
    circDot1.setFill('black')
    circDot1.draw(win)

    circDot3 = Circle(Point(50, 100), 5)
    circDot3.setFill('black')
    circDot3.draw(win)

    circDot5 = Circle(Point(100, 50), 5)
    circDot5.setFill('black')
    circDot5.draw(win)

    circDot7 = Circle(Point(100, 100), 5)
    circDot7.setFill('black')
    circDot7.draw(win)

    circDot4 = Circle(Point(75, 75), 5)
    circDot4.setFill('black')
    circDot4.draw(win)

def dice(win, a, b):
    #build the dice
    rectDice = Rectangle(Point(115, 115), Point(275,275))
    rectDice.setFill('pink')
    rectDice.setOutline('pink')
    rectDice.draw(win)


def main():
    # Create window, call dice function
    win = GraphWin("Dice", 400, 400)
    win.setBackground("cyan")
    dice(win, "a", "b")
    dot(win, "c", "d")

main()

10-01 19:40
查看更多