本文整理汇总了Python中tkinter.Canvas.create_line方法的典型用法代码示例。如果您正苦于以下问题:Python Canvas.create_line方法的具体用法?Python Canvas.create_line怎么用?Python Canvas.create_line使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tkinter.Canvas
的用法示例。
在下文中一共展示了Canvas.create_line方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: initUI
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_line [as 别名]
def initUI(self):
self.parent.title("Colors")
self.pack(fill=BOTH, expand=1)
canvas = Canvas(self)
#bounds = canvas.bbox(canvas) # returns a tuple like (x1, y1, x2, y2)
#width = canvas.width #bounds[2] - bounds[0]
#height = canvas.height #bounds[3] - bounds[1]
size = len(self.dataXArray)
graphHeight = 100
graphOriginX = 0
graphOriginY = self.canvasHeight / 2
graphScaleX = self.canvasWidth / size
#canvas.create_line(graphOriginX, graphOriginY - int(graphHeight), graphOriginX + (graphScaleX * (size + 1)), graphOriginY - int(graphHeight), fill="black")
#canvas.create_line(graphOriginX, graphOriginY + int(graphHeight), graphOriginX + (graphScaleX * (size + 1)), graphOriginY + int(graphHeight), fill="black")
canvas.create_line(graphOriginX, graphOriginY, graphOriginX + (graphScaleX * (size + 1)), graphOriginY, fill="black")
for i in range(0, len(self.zippedDataArray) - 1):
canvas.create_line(graphOriginX + (graphScaleX * i), graphOriginY - int(graphHeight * self.dataXArray[i]), graphOriginX + (graphScaleX * (i + 1)), graphOriginY - int(graphHeight * self.dataXArray[i + 1]), fill="red")
canvas.create_line(graphOriginX + (graphScaleX * i), graphOriginY - int(graphHeight * self.dataYArray[i]), graphOriginX + (graphScaleX * (i + 1)), graphOriginY - int(graphHeight * self.dataYArray[i + 1]), fill="green")
canvas.create_line(graphOriginX + (graphScaleX * i), graphOriginY - int(graphHeight * self.dataZArray[i]), graphOriginX + (graphScaleX * (i + 1)), graphOriginY - int(graphHeight * self.dataZArray[i + 1]), fill="blue")
if i % 10 == 0 and self.drawVerticals:
canvas.create_line(graphOriginX + (graphScaleX * i), graphOriginY - int(graphHeight), graphOriginX + (graphScaleX * (i)), graphOriginY + int(graphHeight), fill="black")
# canvas.create_rectangle(270, 10, 370, 80,
# outline="#05f", fill="#05f")
canvas.pack(fill=BOTH, expand=1)
示例2: create_single_swiss
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_line [as 别名]
def create_single_swiss(players,main):
def create_plate(x,y,name):
c.create_text(x+37,y+15,text=name)
c.create_rectangle(x,y,x+75,y+25)
c.create_line(x+75,y+12,x+85,y+12)
destroy_all(main)
c = Canvas(main)
c.pack(fill=BOTH, expand=YES)
shuffle(players)
odd = False
if(len(players)%2):
odd = True
i=int(ceil(len(players)/2))
j=0;
for x in range(i):
if not odd:
create_plate(25,25+x*75,players[j])
j=j+1
create_plate(25,55+x*75,players[j])
j=j+1
c.create_line(110,37+(x*75),110,67+(x*75))
else:
if j == i:
create_plate(150,25+x*75,players[-1])
break
create_plate(25,25+x*75,players[j])
j=j+1
create_plate(25,55+x*75,players[j])
j=j+1
c.create_line(110,37+(x*75),110,67+(x*75))
示例3: show_mol
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_line [as 别名]
def show_mol( mol):
try:
from tkinter import Tk, Canvas, Frame
except ImportError:
from Tkinter import Tk, Canvas, Frame
app = Tk()
app.title( "oasa")
mainFrame = Frame( app)
mainFrame.pack( fill='both', expand=1)
paper = Canvas( mainFrame, width=640, height=480, background="white", closeenough=5)
paper.pack()
xmin, xmax, ymin, ymax = None,None,None,None
for a in mol.vertices:
if xmin is None or a.x < xmin:
xmin = a.x
if xmax is None or a.x > xmax:
xmax = a.x
if ymin is None or a.y < ymin:
ymin = a.y
if ymax is None or a.y > ymax:
ymax = a.y
dx = xmax-xmin
dy = ymax-ymin
#print("dx", dy, ymax, ymin)
range = min( (600.0/dx, 450.0/dy))/2
xp = 640-range*dx
yp = 480-range*dy
xtrans = lambda xx: range*(xx - xmin)+xp/2
ytrans = lambda xx: range*(xx - ymin)+yp/2
for b in mol.edges:
a1, a2 = b.vertices
x1 = xtrans( a1.x)
x2 = xtrans( a2.x)
y1 = ytrans( a1.y)
y2 = ytrans( a2.y)
paper.create_line( x1, y1, x2, y2, fill='black')
paper.create_text( (x1+x2)/2, (y1+y2)/2, text=str( b.order), fill="#F00")
for v in mol.vertices:
x = xtrans( v.x)
y = ytrans( v.y)
#paper.create_oval( x-5, y-5, x+5, y+5, fill="#0F0")
paper.create_text( x, y, text=v.symbol, fill="#0F0")
app.mainloop()
示例4: overview
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_line [as 别名]
def overview(self, Medikom):
# get content
tasks_results, information_results = Medikom.get_titles()
# clear screen
canvas = Canvas(self, width=self.WIN_WIDTH, height=self.WIN_HIGHT * 2)
canvas.place(x=0, y=0)
# headers
tasks_label = Label(self, text='Aufgaben', font='Liberation 14')
tasks_label.place(
x=0, y=0, width=self.WIN_WIDTH/2, height=self.ROW_HIGHT)
info_label = Label(self, text='Informationen', font='Liberation 14')
info_label.place(
x=self.WIN_WIDTH/2, y=0,
width=self.WIN_WIDTH/2, height=self.ROW_HIGHT)
self.list_entries(Medikom, tasks_results, 0)
self.list_entries(Medikom, information_results, 1)
# lower window part
canvas.create_line(
self.SPACE_ONE, (self.n + 1.5) * (self.ROW_HIGHT + self.ROW_SPACE),
self.WIN_WIDTH - self.SPACE_ONE, (self.n + 1.5) * (self.ROW_HIGHT + self.ROW_SPACE),
fill='#000001', width=1)
add_task_button = Button(self, text='+',
command=Callable(self.view_new_title, Medikom, 0))
add_task_button.place(
x=self.WIN_WIDTH / 4 - self.SPACE_TWO / 2,
y=self.n * (self.ROW_HIGHT + self.ROW_SPACE),
width=self.SPACE_TWO, height=self.ROW_HIGHT)
add_info_button = Button(self, text='+',
command=Callable(self.view_new_title, Medikom, 1))
add_info_button.place(
x=0.75 * self.WIN_WIDTH - self.SPACE_TWO / 2,
y=self.n * (self.ROW_HIGHT + self.ROW_SPACE),
width=self.SPACE_TWO, height=self.ROW_HIGHT)
if self.selected_id is None:
selection_label = Label(
self, text='Kein Eintrag ausgewählt.', font='Liberation 10')
selection_label.place(
x=self.WIN_WIDTH / 2 - 0.125 * self.WIN_WIDTH,
y=(self.n + 1) * (self.ROW_HIGHT + self.ROW_SPACE),
width=self.WIN_WIDTH / 4, height=self.ROW_HIGHT)
示例5: initUI
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_line [as 别名]
def initUI(self):
self.parent.title("Colors")
#self.grid_rowconfigure(0, weight=1)
#self.grid_columnconfigure(0, weight=1)
#xscrollbar = Scrollbar(self, orient=HORIZONTAL)
#xscrollbar.grid(row=1, column=0, sticky=E+W)
#canvas = Canvas(self, xscrollcommand=xscrollbar.set)
canvas = Canvas(self)
#xscrollbar.config(command=canvas.xview)
self.pack(fill=BOTH, expand=1)
#bounds = canvas.bbox(canvas) # returns a tuple like (x1, y1, x2, y2)
#width = canvas.width #bounds[2] - bounds[0]
#height = canvas.height #bounds[3] - bounds[1]
size = len(self.dataXArray)
graphHeight = 100
graphOriginX = 0
graphOriginY = self.canvasHeight / 2
#graphScaleX = self.canvasWidth / size
graphScaleX = 4
#canvas.create_line(graphOriginX, graphOriginY - int(graphHeight), graphOriginX + (graphScaleX * (size + 1)), graphOriginY - int(graphHeight), fill="black")
#canvas.create_line(graphOriginX, graphOriginY + int(graphHeight), graphOriginX + (graphScaleX * (size + 1)), graphOriginY + int(graphHeight), fill="black")
canvas.create_line(graphOriginX, graphOriginY, graphOriginX + (graphScaleX * (size + 1)), graphOriginY, fill="black")
for i in range(0, len(self.zippedDataArray) - 1):
canvas.create_line(graphOriginX + (graphScaleX * i), graphOriginY - int(graphHeight * self.dataXArray[i]), graphOriginX + (graphScaleX * (i + 1)), graphOriginY - int(graphHeight * self.dataXArray[i + 1]), fill="red")
canvas.create_line(graphOriginX + (graphScaleX * i), graphOriginY - int(graphHeight * self.dataYArray[i]), graphOriginX + (graphScaleX * (i + 1)), graphOriginY - int(graphHeight * self.dataYArray[i + 1]), fill="green")
canvas.create_line(graphOriginX + (graphScaleX * i), graphOriginY - int(graphHeight * self.dataZArray[i]), graphOriginX + (graphScaleX * (i + 1)), graphOriginY - int(graphHeight * self.dataZArray[i + 1]), fill="blue")
if i % 10 == 0:
canvas.create_line(graphOriginX + (graphScaleX * i), graphOriginY - int(graphHeight), graphOriginX + (graphScaleX * (i)), graphOriginY + int(graphHeight), fill="black")
# canvas.create_rectangle(270, 10, 370, 80,
# outline="#05f", fill="#05f")
canvas.pack(fill=BOTH, expand=1)
示例6: WindowInstance
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_line [as 别名]
class WindowInstance(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.parent.title("Window")
self.pack(fill=BOTH, expand=1)
self.canvas = Canvas(self)
self.doubleBuffer = False
self.fill = "#000"
self.outline = "#000"
def setColor(self, c):
self.fill = c
self.outline = c
def drawRectangle(self, x, y, w, h):
self.canvas.create_rectangle(x, y, x + w, y + h, fill=self.fill, outline=self.outline)
if not self.doubleBuffer:
self.canvas.pack(fill=BOTH, expand=1)
def drawLine(self, x, y, ex, ey):
self.canvas.create_line(x, y, ex, ey, fill=self.fill)
if not self.doubleBuffer:
self.canvas.pack(fill=BOTH, expand=1)
def drawOval(self, x, y, w, h):
self.canvas.create_oval(x, y, x + w, y + h, fill=self.fill, outline=self.outline)
if not self.doubleBuffer:
self.canvas.pack(fill=BOTH, expand=1)
def frame(self):
self.doubleBuffer = True
self.canvas.pack(fill=BOTH, expand=1)
def clear(self):
self.canvas.delete("all")
示例7: WebbCanvas
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_line [as 别名]
class WebbCanvas():
sideoffset = 25
def __init__(self):
self.root = Tk.Tk()
self.GraphicWindow = GraphicWindow(master=self.root)
self.canvas = Canvas(self.GraphicWindow, width=GraphicWindow.SCREEN_Width, height=GraphicWindow.SCREEN_Height, bg="#000")
self.canvas.pack();
def Loop(self):
self.root.mainloop()
def PaintSpiderNodes(self, spiderWebb):
NodeXCount = spiderWebb.NodeXCount
NodeYCount = spiderWebb.NodeYCount;
NodeXDistance = (GraphicWindow.SCREEN_Width - (2*WebbCanvas.sideoffset))/(NodeXCount)
NodeYDistance = (GraphicWindow.SCREEN_Height - (2*WebbCanvas.sideoffset))/(NodeYCount)
NodeXSize = NodeXDistance/4;
NodeYSize = NodeYDistance/4;
NextNodeXpos = WebbCanvas.sideoffset
NextNodeYpos = WebbCanvas.sideoffset
for yrow in spiderWebb.Webb:
NextNodeXpos = WebbCanvas.sideoffset
for SpiderNode in yrow:
color = "blue"
if(SpiderWebb.IsNodeConnected(SpiderNode)==True):
color = "green"
self.canvas.create_rectangle(NextNodeXpos, NextNodeYpos, NextNodeXpos+NodeXSize, NextNodeYpos+NodeYSize, fill=color)
self.PaintConnectionSpiderNode(SpiderNode, NextNodeXpos + math.floor(NodeXSize/2), NextNodeYpos + math.floor(NodeYSize/2), NodeXDistance, NodeYDistance)
NextNodeXpos += NodeXDistance
NextNodeYpos += NodeYDistance
self.root.update();
def PaintConnectionSpiderNode(self, SpiderNode, NodeXCenterPos, NodeYCenterPos, NodeXDistance, NodeYDistance):
'''UpRight'''
if(SpiderNode[0]==1):
self.canvas.create_line(NodeXCenterPos, NodeYCenterPos, NodeXCenterPos + NodeXDistance, NodeYCenterPos - NodeYDistance, fill="red")
'''Right'''
if(SpiderNode[1]==1):
self.canvas.create_line(NodeXCenterPos, NodeYCenterPos, NodeXCenterPos + NodeXDistance, NodeYCenterPos + 0, fill="red")
'''RightDown'''
if(SpiderNode[2]==1):
self.canvas.create_line(NodeXCenterPos, NodeYCenterPos, NodeXCenterPos + NodeXDistance, NodeYCenterPos + NodeYDistance, fill="red")
'''Down'''
if(SpiderNode[3]==1):
self.canvas.create_line(NodeXCenterPos, NodeYCenterPos, NodeXCenterPos + 0, NodeYCenterPos + NodeYDistance, fill="red")
示例8: CoordinatePlot
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_line [as 别名]
class CoordinatePlot(object):
"""
Shows the distribution of one coordinate of
a list of solutions in the complex plane.
"""
def __init__(self, wdw, dim, sols, idx):
"""
The layout is just a square canvas, of dimension dim.
The canvas represents the complex plane for the plot of
the coordinate defined by index idx of the list sols.
"""
wdw.title('complex coordinate plot')
self.cnv = Canvas(wdw, width=dim, height=dim)
self.cnv.pack()
self.sols = sols
self.idx = idx
self.dim = dim
self.plot()
def plot(self):
"""
Plots a coordinate of the list of solutions.
"""
from phcpy.solutions import coordinates
dim = self.dim
self.cnv.create_line(0, dim/2, dim, dim/2) # x coordinate axis
self.cnv.create_line(dim/2, 0, dim/2, dim) # y coordinate axis
(realmin, realmax, imagmin, imagmax) = windowsize(self.sols, self.idx)
dimreal = max(abs(realmin), abs(realmax))
dimimag = max(abs(imagmin), abs(imagmax))
factor = dim/2 - 10 # the origin is at (dim/2, dim/2)
for sol in self.sols:
(names, values) = coordinates(sol)
val = values[self.idx]
xpt = dim/2 + (val.real/dimreal)*factor
ypt = dim/2 + (val.imag/dimimag)*factor
self.cnv.create_oval(xpt-3, ypt-3, \
xpt+3, ypt+3, fill='red')
示例9: Example
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_line [as 别名]
class Example(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.x = 0
self.y = 0
self.parent = parent
parent.bind("<Motion>", self.onMove)
parent.bind("<Button-1>", self.leftClick)
parent.bind("<Button-3>", self.rightClick)
self.parent.title("Colors")
self.pack(fill=BOTH, expand=1)
self.canvas = Canvas(self)
self.canvas.create_rectangle(30, 10, 120, 80, outline="#fb0", fill="#fb0")
self.canvas.create_rectangle(150, 10, 240, 80, outline="#f50", fill="#f50")
self.canvas.create_rectangle(270, 10, 370, 80, outline="#05f", fill="#05f")
self.canvas.pack(fill=BOTH, expand=1)
self.inMotion = False
self.line = 0#Holder for temp line whilst dragging mouse around
def onMove(self, e):
if self.inMotion:
self.canvas.delete(self.line)
self.line = self.canvas.create_line(self.x, self.y, e.x, e.y)
def leftClick(self, e):
if not(self.inMotion):
self.canvas.create_line(self.x, self.y, e.x, e.y)
self.x = e.x
self.y = e.y
self.inMotion = True
def rightClick(self, e):
self.inMotion = False
示例10: mainLoop
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_line [as 别名]
def mainLoop():
gui = Tk()
MAX = 500
canvas = Canvas(gui, width = MAX, height = MAX)
o = canvas.create_line(MAX / 2, 0, MAX / 2, MAX) #Ordonnées
a = canvas.create_line(0, MAX / 2, MAX, MAX / 2) #Abscisse
nullP = canvas.create_text(243, 259, text = "0", fill = "red")
canvas.pack()
gui.mainloop()
示例11: rmap
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_line [as 别名]
#.........这里部分代码省略.........
for r in range (1,self._nr):
for c in range(1,self._nc):
self._field[r][c].text = ''
self._field[r][c].color = ''
self._field[r][c].label = ''
self._field[r][c].wUp = False
self._field[r][c].wLeft = False
self._field[r][c].v = self._v()
for c in range (1,self._nc):
self._field[1][c].wUp = True
self._field[self._nr][c].wUp = True
for r in range (1,self._nr):
self._field[r][1].wLeft = True
self._field[r][self._nc].wLeft = True
self._solve = ''
self._r = 1
self._c = 1
def _paintMap(self):
"Перерисовка по имеющимся данным"
remc = self._c
remr = self._r
size = self._size
sleep = self.sleep
self.sleep = 0
self._bg = [self._canvas.create_rectangle(1,1,(size*(self._nc+1)), (size*(self._nr+1)), fill="gray")]
# создать поле
for r in range (1, self._nr+1):
self._bg.append(self._canvas.create_line(size,r*size,self._nc*size,r*size))
if r < self._nr: self._canvas.create_text(size/2,r*size+size/2,text=r)
for c in range (1, self._nc+1):
self._bg.append(self._canvas.create_line(c*size,size,c*size,self._nr*size))
if c < self._nc: self._bg.append(self._canvas.create_text(c*size+size/2,size/2,text=c))
# клетки и номера столбцов и строк
for r in range (1,self._nr):
for c in range(1,self._nc):
self._r = r
self._c = c
if self._field[r][c].wUp: # стена сверху
self.setWall('up')
if self._field[r][c].wLeft: # стена слева
self.setWall('left')
if self._field[r][c].color != '' : # закраска
self.paint(self._field[r][c].color)
if self._field[r][c].label != '' : # метка0000
d = self._d
x1 = self._size*(c)
x2 = self._size*(c+1)
y1 = self._size*(r)
y2 = self._size*(r+1)
self._canvas.delete(self._field[r][c].v.label)
self._field[r][c].v.label = self._canvas.create_rectangle(x1+d,y1+d,x2-d,y2-d, width = d-1, outline = self._field[r][c].label)
self._canvas.lift(self._robot)
self.settext(self._field[r][c].text) # текст
for self._c in range (1,self._nc):
if self._field[self._nr][self._c].wUp: # стена сверху
self.setWall('down')
for self._r in range (1,self._nr):
示例12: __init__
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_line [as 别名]
#.........这里部分代码省略.........
#with all other balls and store that time within the ith and jth index of
#PQ.ball_collision_time
def init_ball_collision_times(self):
for i in np.arange(self.num_balls):
bi = self.balls[i]
for j in np.arange(i+1, self.num_balls):
bj = self.balls[j]
tij = bi.ball_collision_time(bj)
self.PQ.insert(i, j, tij + self.time, self.balls[i].count, self.balls[j].count)
# self.ball_collision_times[i][j] = tij
# self.ball_collision_times[j][i] = tij
return
#update collision times is meant to update collision times of ball i with all
#walls (horizontal and vertical) and all other balls within the PQ array
def update_collision_times(self, i):
bi = self.balls[i]
tix = bi.horizontal_wall_collision_time(self.min_x, self.max_x)
tiy = bi.vertical_wall_collision_time(self.min_y, self.max_y)
self.PQ.insert(i, -1, tix + self.time,self.balls[i].count, -1)
self.PQ.insert(-1, i, tiy + self.time, -1, self.balls[i].count)
for j in np.arange(self.num_balls):
bj = self.balls[j]
tij = bi.ball_collision_time(bj) + self.time
if i > j:
self.PQ.insert(j, i, tij,self.balls[j].count,self.balls[i].count)
else:
self.PQ.insert(i, j, tij,self.balls[i].count, self.balls[j].count)
return
#draw will draw the borders and all balls within self.balls
def draw(self):
#Draw walls
self.canvas.create_line((self.min_x, self.min_y), (self.min_x, self.max_y), fill = "red")
self.canvas.create_line((self.min_x, self.min_y), (self.max_x, self.min_y), fill = "red")
self.canvas.create_line((self.min_x, self.max_y), (self.max_x, self.max_y), fill = "red")
self.canvas.create_line((self.max_x, self.min_y), (self.max_x, self.max_y), fill = "red")
#Draw balls
for b in self.balls:
obj = self.canvas.create_oval(b.x - b.radius, b.y - b.radius, b.x + b.radius, b.y + b.radius, outline=b.tk_rgb, fill=b.tk_rgb)
self.ball_handles[b] = obj
self.canvas.update()
#refresh is called to update the state of the simulation
#-each refresh call can be considered one iteration of the simulation
#-all balls will be moved and if there is a collision then it will be computed
def refresh(self):
#get the next collision
i, j, t, num_collisions_i, num_collision_j = self.PQ.get_next()
#gather the current collisions of the ith and jth ball
current_collisions_i = self.balls[i].count
current_collisions_j = self.balls[j].count
#Check the difference in time between the predicted collision time and
#the current time stamp of the simulation
delta = t - self.time
#If the difference is greater than 1, then just move the balls
if delta > 1.0:
# cap delta to 1.0
for bi in self.balls:
bi.move()
self.canvas.move(self.ball_handles[bi], bi.vx, bi.vy)
self.time += 1.0
#Otherwise a collision has occurred
else:
示例13: Tk
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_line [as 别名]
can.delete(line1[int(y/50)])
can.delete(line2[int(y/50)])
line1[int(y/50)] = [can.create_line(pos1, fill='#000')]
line2[int(y/50)] = [can.create_line(pos2, fill='#f00',
dash=(3, 2))]
can.update()
"""
본문
캔버스를 선언하고 원과 선들을 초기화
"""
master = Tk()
can = Canvas(master, width=500, height=500)
obj = can.create_oval(240, 240, 260, 260, fill='#aafcdf')
can.pack()
# 라인 초기화
line1 = [can.create_line(0, 0, 1, 1)]*11
line2 = [can.create_line(0, 0, 1, 1)]*11
# 애니메이션 구동
can.after(0, web)
onTarget = False
# bind: 미리 정해져 있는 입력에 따라서 함수를 실행
# 사용자의 드래그 동작은 클릭과 클릭한 후 이동으로 구성되어 있다.
can.bind('<Button-1>', onClick)
can.bind('<B1-Motion>', onDrag)
master.mainloop()
示例14: __init__
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_line [as 别名]
class Visualize:
def __init__(self, solution):
self.solution = solution
self.time = 0
self.full = solution.full
self.shiftRight = 20
self.shiftDown = 20
self.separation = 90
self.scale = 60
self.textVShift = 10
self.root = Tk()
self.canvas = Canvas(self.root)
self.canvas.pack(fill=BOTH, expand=YES)
self.root.bind("<KeyRelease>", self.key_released)
self.timeLabel = Label(self.root, text='time_lavel')
self.timeLabel.pack(side=RIGHT)
self.setup()
self.draw()
if self.full:
mainloop()
def key_released(self, event):
if event.char == 'j':
if self.time < self.solution.maxt:
self.time = self.time + 1
self.draw()
elif event.char == 'k':
if self.time > 0:
self.time = self.time - 1
self.draw()
elif event.char == 'q':
self.root.quit()
def getBBox(self, v):
return (self.shiftRight + self.separation*v[0],
self.shiftDown + self.separation*v[1],
self.shiftRight + self.separation*v[0] + self.scale,
self.shiftDown + self.separation*v[1] + self.scale)
def getCenter(self, v):
return (self.shiftRight + self.separation*v[0] + self.scale / 2,
self.shiftDown + self.separation*v[1] + self.scale / 2)
def getStatusPos(self, v):
(x,y) = self.getCenter(v)
return (x,y - self.textVShift)
def getDecisionPos(self, v):
(x,y) = self.getCenter(v)
return (x,y + self.textVShift)
def getEdgePos(self, e):
v0 = self.getCenter(e[0])
v1 = self.getCenter(e[1])
if v0[0] == v1[0]:
if v0[1] < v1[1]:
return (v0[0], v0[1] + self.scale / 2), (v1[0], v1[1] - self.scale / 2)
else:
return (v0[0], v0[1] - self.scale / 2), (v1[0], v1[1] + self.scale / 2)
elif v0[1] == v1[1]:
if v0[0] < v1[0]:
return (v0[0] + self.scale / 2, v0[1]), (v1[0] - self.scale / 2, v1[1])
else:
return (v0[0] - self.scale / 2, v0[1]), (v1[0] + self.scale / 2, v1[1])
return v0, v1
def setup(self):
self.nodeStatus = {}
self.nodeDecision = {}
for v in self.solution.nodes:
self.canvas.create_oval(self.getBBox(v))
self.nodeStatus[v] = self.canvas.create_text(self.getStatusPos(v), text="asfs")
self.nodeDecision[v] = self.canvas.create_text(self.getDecisionPos(v), text="fs")
self.edges = {}
for e in self.solution.edges:
self.canvas.create_line(self.getEdgePos(e), fill='gray')
self.edges[e] = self.canvas.create_line(self.getEdgePos(e), arrow='last',
state=HIDDEN)
def draw(self):
# quick reference
nstat = self.solution.nstat
command = self.solution.command
self.timeLabel.config(text = '%r' % self.time)
t = self.time
for v in self.solution.nodes:
self.canvas.itemconfig(self.nodeStatus[v], text=nstat[v,self.time])
self.canvas.itemconfig(self.nodeDecision[v], text=command[v,self.time])
if not self.full:
return
occu = self.solution.occu
for e in self.solution.edges:
state = HIDDEN
#.........这里部分代码省略.........
示例15: GameUI
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_line [as 别名]
class GameUI(Frame):
def __init__(self, parent, controller):
Frame.__init__(self, parent)
self.game = Game()
self.row, self.col = 0, 0
self.init_UI()
def init_UI(self):
self.pack(fill=BOTH, expand=1)
self.canvas = Canvas(self,
width=WIDTH,
height=HEIGHT,
highlightthickness=0,
relief='ridge',
bg='gray10'
)
self.canvas.pack(fill=BOTH, side=TOP)
Button(self,
text='RESTART',
height=24,
fg='white',
bg='gray20',
activeforeground='white',
activebackground='gray15',
border=0,
font=('Arial', 12, 'bold'),
highlightthickness=0,
relief='ridge',
command=self.restart
).pack(fill=BOTH, side=BOTTOM)
self.draw_grid()
self.canvas.bind('<Button-1>', self.play)
def restart(self):
self.game = Game()
self.row, self.col = 0, 0
self.canvas.delete('all')
self.draw_grid()
def draw_grid(self):
for i in range(self.game.width + 1):
x0 = MARGIN + i * SIDE
y0 = MARGIN
x1 = MARGIN + i * SIDE
y1 = HEIGHT - MARGIN
self.canvas.create_line(x0, y0, x1, y1, fill='gray25')
x0 = MARGIN
y0 = MARGIN + i * SIDE
x1 = HEIGHT - MARGIN
y1 = MARGIN + i * SIDE
self.canvas.create_line(x0, y0, x1, y1, fill='gray25')
self.board = [ [ self.game.get_cell_value(x, y) for x in range(self.game.width + 1) ] for y in range(self.game.height + 1) ]
self.load_board(self.board)
def load_board(self, board):
for y in range(self.game.height + 1):
for x in range(self.game.width + 1):
player = self.game.get_cell_value(y, x)
if player != ' ':
self.row, self.col = (self.game.width - 1) - x, y
self.draw_player(player)
def play(self, event):
if self.game.get_winner():
return
x, y = event.x, event.y
if MARGIN < x < WIDTH - MARGIN and MARGIN < y < HEIGHT - MARGIN:
row, col = int((y - MARGIN) / SIDE), int((x - MARGIN) / SIDE)
real_x, real_y = col, (self.game.width - 1) - row
if self.game.is_cell_free(real_x, real_y):
self.row, self.col = row, col
player = self.game.get_next_players_turn()
self.game.make_move(real_x, real_y, player)
self.draw_player(player)
winner = self.game.get_winner()
if winner:
self.draw_victory(winner)
def draw_player(self, player):
if self.row >= 0 and self.col >=0:
x0 = MARGIN + self.col * SIDE + 1
y0 = MARGIN + self.row * SIDE + 1
x1 = MARGIN + (self.col + 1) * SIDE - 1
y1 = MARGIN + (self.row + 1) * SIDE - 1
self.canvas.create_rectangle(
#.........这里部分代码省略.........