from tkinter import *
from random import randrange
### def
def sqlines(x=0, y=0):
n = 0
while n < 5:
can.create_rectangle(x, y, x+sq, y+sq, fill = "purple")
x = x + sq * 2
n = n + 1
def chess():
y = 0
while y < 10:
if y % 2 == 0:
x = 0
else:
x = 1
sqlines(x*sq, y*sq)
y = y + 1
def delcircles():
can.delete(ALL)
chess()
def circle(x, y, r, color):
can.create_oval(x-r, y-r, x+r, y+r, fill=color)
def add_circle():
x = sq/2 + randrange(10) * sq
y = sq/2 + randrange(10) * sq
circle(x, y, 20/3, "red")
### main
sq = 20
win = Tk()
win.title("Chess")
can = Canvas(win, bg = "white", height = sq*10, width = sq*10)
can.pack(side = TOP, padx = 5, pady = 5)
but1 = Button(win, text="Chess", command = chess)
but1.pack(side = LEFT, padx = 3, pady = 3)
but2 = Button(win, text="Circles", command = add_circle)
but2.pack(side = RIGHT, padx = 3, pady = 3)
but3 = Button(win, text ="Delete", command = delcircles)
but3.pack(side = RIGHT, padx = 3, pady = 3)
win.mainloop()
我必须写一个包含棋盘的脚本,这没关系,但接下来的任务是在棋盘上随机创建圆圈。 我找到了这段代码,但我不明白它是如何工作的。 你能解释一下吗?我真的不明白。
def add_circle():
x = sq/2 + randrange(10) * sq
y = sq/2 + randrange(10) * sq
circle(x, y, 20/3, "red")
答案 0 :(得分:2)
randrange从0到输入数字(10)中选择一个数字,因此x等于
sq/2 + randum number between 0 and 10 * sq
和y相等
sq/2 + random number between 0 and 10 * sq
这是你的问题吗?