我无法从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")
答案 0 :(得分:1)
有几个问题:
您没有执行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()
答案 1 :(得分:-1)
我认为您的main()函数甚至都没有被调用。
尝试使用此:
def main():
# Create window, call dice function
win = GraphWin("Dice", 400, 400)
win.setBackground("cyan")
dice("a","b")
if __name__== "__main__":
main()
参考:this link