本文整理汇总了Python中tkinter.Canvas.delete方法的典型用法代码示例。如果您正苦于以下问题:Python Canvas.delete方法的具体用法?Python Canvas.delete怎么用?Python Canvas.delete使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tkinter.Canvas
的用法示例。
在下文中一共展示了Canvas.delete方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: Wall
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import delete [as 别名]
class Wall(object):
MIN_RED = MIN_GREEN = MIN_BLUE = 0x0
MAX_RED = MAX_GREEN = MAX_BLUE = 0xFF
PIXEL_WIDTH = 50
def __init__(self, width, height):
self.width = width
self.height = height
self._tk_init()
self.pixels = [(0, 0, 0) for i in range(self.width * self.height)]
def _tk_init(self):
self.root = Tk()
self.root.title("ColorWall %d x %d" % (self.width, self.height))
self.root.resizable(0, 0)
self.frame = Frame(self.root, bd=5, relief=SUNKEN)
self.frame.pack()
self.canvas = Canvas(self.frame,
width=self.PIXEL_WIDTH * self.width,
height=self.PIXEL_WIDTH * self.height,
bd=0, highlightthickness=0)
self.canvas.pack()
self.root.update()
def set_pixel(self, x, y, hsv):
self.pixels[self.width * y + x] = hsv
def get_pixel(self, x, y):
return self.pixels[self.width * y + x]
def draw(self):
self.canvas.delete(ALL)
for x in range(len(self.pixels)):
x_0 = (x % self.width) * self.PIXEL_WIDTH
y_0 = (x / self.width) * self.PIXEL_WIDTH
x_1 = x_0 + self.PIXEL_WIDTH
y_1 = y_0 + self.PIXEL_WIDTH
hue = "#%02x%02x%02x" % self._get_rgb(self.pixels[x])
self.canvas.create_rectangle(x_0, y_0, x_1, y_1, fill=hue)
self.canvas.update()
def clear(self):
for i in range(self.width * self.height):
self.pixels[i] = (0, 0, 0)
def _hsv_to_rgb(self, hsv):
rgb = colorsys.hsv_to_rgb(*hsv)
red = self.MAX_RED * rgb[0]
green = self.MAX_GREEN * rgb[1]
blue = self.MAX_BLUE * rgb[2]
return (red, green, blue)
def _get_rgb(self, hsv):
red, green, blue = self._hsv_to_rgb(hsv)
red = int(float(red) / (self.MAX_RED - self.MIN_RED) * 0xFF)
green = int(float(green) / (self.MAX_GREEN - self.MIN_GREEN) * 0xFF)
blue = int(float(blue) / (self.MAX_BLUE - self.MIN_BLUE) * 0xFF)
return (red, green, blue)
示例2: WindowInstance
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import delete [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")
示例3: Example
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import delete [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
示例4: SudokuUI
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import delete [as 别名]
class SudokuUI(Frame):
"""
The Tkinter UI, responsible for displaying the UI.
"""
def __init__(self, parent, game):
self.game = game
self.parent = parent
Frame.__init__(self, parent)
self.row, self.col = 0, 0
self.__initUI()
def __initUI(self):
self.parent.title("Sudoku")
self.pack(fill=BOTH, expand=1) # Use all available space
self.canvas = Canvas(self, width=WIDTH, heigh=HEIGHT)
self.canvas.pack(fill=BOTH, side=TOP) # Pull board to top of frame
clear_button = Button(self, text="Clear answers", command=self.__clear_answers)
clear_button.pack(fill=BOTH, side=BOTTOM)
self.__draw_grid()
self.__draw_puzzle()
self.canvas.bind("<Button-1>", self.__cell_clicked)
self.canvas.bind("<Key>", self.__key_pressed)
def __draw_grid(self):
"""
Draws grid divided with blue lines into 3 x 3 grid
:return:
"""
for i in range(10):
color = 'blue' if i % 3 == 0 else "gray"
x0 = MARGIN + i * SIDE
y0 = MARGIN
x1 = MARGIN + i * SIDE
y1 = HEIGHT - MARGIN
self.canvas.create_line(x0, y0, x1, y1, fill=color)
x0 = MARGIN
y0 = MARGIN + i * SIDE
x1 = WIDTH - MARGIN
y1 = MARGIN + i * SIDE
self.canvas.create_line(x0, y0, x1, y1, fill=color)
def __draw_puzzle(self):
self.canvas.delete("numbers")
for i in xrange(9):
for j in xrange(9):
answer = self.game.puzzle[i][j]
if answer != 0:
x = MARGIN + j * SIDE + SIDE / 2
y = MARGIN + i * SIDE + SIDE / 2
original = self.game.start_puzzle[i][j]
color = "black" if answer == original else "sea green"
self.canvas.create_text(x, y, text=answer, tags="number", fill=color)
def __clear_answers(self):
self.game.start()
self.canvas.delete("victory")
self.__draw_puzze()
def __cell_clicked(self, event): # event has x, y coords of mouse click
if self.game.game_over:
return
x, y = event.x, event.y
if (MARGIN < x < WIDTH - MARGIN) and (MARGIN < Y < HEIGHT - MARGIN):
self.canvas.focus_set()
# get row and col numbers from x, y coords
row, col = (y - MARGIN) / SIDE, (x - MARGIN) / SIDE
# if cell already selected then deselect it
if (row, col) == (self.row, self.col):
self.row, self.col = -1, -1 # outside the grid
elif self.game.puzzle[row][col] == 0:
self.row, self.col = row, col
self.__draw_cursor()
def __draw_cursor(self):
self.canvas.delete("cursor")
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(
x0, y0, x1, y1,
outline ="red", tags ="cursor"
)
示例5: __init__
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import delete [as 别名]
class Gem:
def __init__(self):
self.frame = Tk();
self.frame.resizable(False, False)
self.status = 1
self.scorePlayerA = 0
self.scorePlayerB = 0
self.scoreRoundA = 0
self.scoreRoundB = 0
self.countRound = 0
self.quitMatch = 0
self.isQuitRound = 0
self.canvas_after_2 = 0
self.canvas_after_1 = 0
self.isPause = 0
#register event
self.frame.bind("<F4>", self.quitGame)
self.frame.bind("<F5>", self.pauseGame)
self.frame.protocol("WM_DELETE_WINDOW", self.on_closing)
self.registerKeyboard()
def setName(self, title):
self.frame.title(title)
def setBall(self, ball):
self.ball = ball
def setLeftBar(self, bar):
self.leftBar = bar
def setRightBar(self, bar):
self.rightBar = bar
def run(self):
self.frame.mainloop()
def getFrame(self):
return self.frame;
def getCanvas(self):
return self.canvas
def setSize(self, size):
self.frame.geometry(("%dx%d")%(size[0], size[1]))
self.frame.update()
def getSize(self):
return (self.frame.winfo_width(), self.frame.winfo_height())
def setBackground(self, color):
self.background = color
def setPlayers(self, players):
self.players = players
def setScoreBoard(self):
players = self.players
size = self.getSize()
mid = round(size[0]/2)
# Board
self.canvas.create_rectangle(mid - 100, 0, mid + 100, 35, fill="grey58", outline="white", tag="boarda")
# Player name 1
self.canvas.create_text(mid - 80, 15, text=players[0], fill="magenta2", tag="boardb")
# Round score 1
r1 = players[0]+"a"
self.canvas.create_text(mid - 80, 28, text="0", fill="pale green", tag="scoreplayera")
# Player name 2
self.canvas.create_text(mid + 80, 15, text=players[1], fill="magenta2", tag="boardc")
# Round score 2
self.canvas.create_text(mid + 80, 28, text="0", fill="pale green", tag="scoreplayerb")
# Box score 1
self.canvas.create_rectangle(mid - 50, 5, mid - 10, 25, fill="thistle3", outline="white", tag="boardd")
# Score 1
self.canvas.create_text(mid - 30, 15, text="000", fill="cyan", tag=players[0])
# Box score 2
self.canvas.create_rectangle(mid + 10, 5, mid + 50, 25, fill="thistle3", outline="white", tag="boarde")
# Score 2
self.canvas.create_text(mid + 30, 15, text="000", fill="cyan", tag=players[1])
self.canvas.pack()
self.frame.update()
def clearScoreBoard(self):
self.canvas.delete(self.players[0])
self.canvas.delete(self.players[1])
self.canvas.delete("boarda")
#.........这里部分代码省略.........
示例6: TKinterDisplay
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import delete [as 别名]
#.........这里部分代码省略.........
def renderTextInId(self, tagTocentreOn, tagsToAddTo, content, funcContent):
id1tuple = self.__getCoords(tagTocentreOn)
x1 = id1tuple[0] + ((id1tuple[2] - id1tuple[0]) / 2)
y1 = id1tuple[1] + ((id1tuple[3] - id1tuple[1]) / 2)
txt = self.__renderText(x1, y1, (id1tuple[2] - id1tuple[0]), content, tagsToAddTo)
def handler(event, self=self, content=funcContent):
return self.__eventOnClick(event, content)
self.localCanvas.tag_bind(txt, "<ButtonRelease-1>", handler)
return txt
@abstractmethod
def move(self, tag, xamount, yamount):
self.localCanvas.move(tag, xamount, yamount)
@abstractmethod
def runDisplay(self):
self.localCanvas.mainloop()
def __hideId(self, objectId):
self.localCanvas.itemconfigure(objectId, state="hidden")
pass
def __showId(self, objectId):
self.localCanvas.itemconfigure(objectId, state="normal")
pass
def __sampleDraw(self):
self.localCanvas.create_oval(0, 0, 0, 0, width=0)
def __renderText(self, x, y, width, content, tag):
val = self.localCanvas.create_text(x, y, width=width, text=content, tags=tag, justify="center", font="Helvetica 8 bold", anchor="center")
self.localCanvas.tag_raise(val)
return val
def __drawLine(self, x1, y1, x2, y2, tags=None, colour="black"):
line = self.localCanvas.create_line(x1, y1, x2, y2, tags=tags, width=self.lineThickness, arrow="first", arrowshape=(16,20,6),fill=colour, smooth=True)
self.localCanvas.tag_lower(line)
return # line
def __remove(self, num):
self.localCanvas.delete(num)
def __getCoords(self, ident):
return self.localCanvas.coords(ident)
def __eventOnFrameConfigure(self, event):
'''Reset the scroll region to encompass the inner frame'''
assert self.localCanvas
coord_tuple = self.localCanvas.bbox("all")
if not coord_tuple:
logging.error("Frame reconfigure error on coordinate acquire.")
else:
reconWidth = coord_tuple[2] - coord_tuple[0]
reconHeight = coord_tuple[3] - coord_tuple[1]
self.localCanvas.configure(width=reconWidth)
self.localCanvas.configure(height=reconHeight)
self.localCanvas.configure(scrollregion=self.localCanvas.bbox("all"))
self.localCanvas.update_idletasks()
def __eventOnClick(self, event, content):
self.__createWindowOnId(self.localCanvas.find_withtag(CURRENT), content)
def __createWindowOnId(self, itemId, content):
if self.currentlyRenderedWindow != None:
self.currentlyRenderedWindow()
# self.__remove(self.currentlyRenderedWindow)
idtuple = self.localCanvas.coords(itemId)
if idtuple:
x = idtuple[0]
y = idtuple[1]
frm = Frame(self.localCanvas)
frm.grid(row=0, column=0)
canv = Canvas(frm)
vscroll = Scrollbar(frm, orient="vertical", command=canv.yview)
vscroll.grid(row=0, column=1, sticky=N + S)
canv.grid(row=0, column=0)
canv["yscrollcommand"] = vscroll.set
aframe = Frame(canv)
aframe.grid(row=0, column=0)
Label(aframe, text=content, anchor="center", background="#CCFFCC", borderwidth=6, relief="ridge", justify="left").grid(row=1, column=0)
canvWindow = canv.create_window(x, y, window=aframe)
canv.coords(canvWindow, x, y)
self.localCanvas.update_idletasks()
canv["scrollregion"] = canv.bbox("all")
def destroyAll():
self.__remove(canvWindow)
canv.destroy()
aframe.destroy()
vscroll.destroy()
frm.destroy()
self.currentlyRenderedWindow = destroyAll
Button(frm, text="Close", command=lambda : destroyAll()).grid(row=2, column=0)
示例7: View
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import delete [as 别名]
class View():
def __init__(self, root, controller):
self.__controller = controller
root.wm_title("Bomber")
self.__windowsystem = root.call('tk', 'windowingsystem')
self.__frame = root
self.__canvas = Canvas(self.__frame, width=int(CANVAS_WIDTH),
height=int(CANVAS_HEIGHT), bg="white")
self.__canvas.pack(side=LEFT, fill=BOTH, expand=TRUE)
self.__init_fonts()
self.__init_arena()
self.__init_score()
self.__block_views = [] # type: List[BlockView]
self.__blockfield_view = BlockfieldView()
self.__messages = []
def __init_fonts(self):
self.bigfont = font.nametofont("TkDefaultFont")
self.bigfont.configure(size=int(48))
self.scorefont = font.nametofont("TkDefaultFont")
self.scorefont.configure(size=int(20))
def __init_score(self):
self.score_text = self.__canvas.create_text(5, 5, anchor="nw")
self.__canvas.itemconfig(self.score_text, text="Score:", font=self.scorefont)
def __init_arena(self):
self.__canvas.create_rectangle(LEFT_OFFSET, TOP_OFFSET,
LEFT_OFFSET + MAXCOL*GRID_SIZE,
TOP_OFFSET+MAXROW*GRID_SIZE, fill="black")
nextblocktext = self.__canvas.create_text(GRID_SIZE,
TOP_OFFSET + GRID_SIZE * 4, anchor="nw")
self.__canvas.itemconfigure(nextblocktext, text="Next:",
font=self.bigfont, fill="black")
self.__autoplay_text = self.__canvas.create_text(LEFT_OFFSET + GRID_SIZE * 5,
TOP_OFFSET - GRID_SIZE, anchor="c")
self.__canvas.itemconfigure(self.__autoplay_text, text="Play mode",
font=self.bigfont, fill="black")
def register_block(self, block):
block_view = BlockView(block)
self.__block_views.append(block_view)
def unregister_block(self, block):
for block_view in self.__block_views:
if block_view.block is block:
block_view.erase(self.__canvas)
self.__block_views.remove(block_view)
def update_blockfield(self, blockfield):
self.__blockfield_view.redraw(self.__canvas, blockfield)
def display_score(self):
self.__canvas.itemconfig(self.score_text, text="Score: " + str(self.__controller.score),
font=self.scorefont)
def show_autoplay(self, autoplay):
if autoplay:
self.__canvas.itemconfig(self.__autoplay_text, text="Auto-play mode",
font=self.scorefont, fill="black")
else:
self.__canvas.itemconfig(self.__autoplay_text, text="Manual mode",
font=self.scorefont, fill="black")
def game_over(self):
text1 = self.__canvas.create_text(LEFT_OFFSET + GRID_SIZE*MAXCOL//2,
CANVAS_HEIGHT/2, anchor="c")
text2 = self.__canvas.create_text(LEFT_OFFSET + GRID_SIZE*MAXCOL//2,
CANVAS_HEIGHT/2 + 100, anchor="c")
text1_shadow = self.__canvas.create_text(2 + LEFT_OFFSET + GRID_SIZE*MAXCOL//2,
2 + CANVAS_HEIGHT/2, anchor="c")
text2_shadow = self.__canvas.create_text(2 + LEFT_OFFSET + GRID_SIZE*MAXCOL//2,
2 + CANVAS_HEIGHT/2 + 100, anchor="c")
self.__messages.append(text1)
self.__messages.append(text2)
self.__messages.append(text1_shadow)
self.__messages.append(text2_shadow)
self.__canvas.itemconfig(text1, text="GAME OVER!",
font=self.bigfont, fill="white")
self.__canvas.itemconfig(text2, text="Press r to play again.",
font=self.scorefont, fill="white")
self.__canvas.itemconfig(text1_shadow, text="GAME OVER!",
font=self.bigfont, fill="black")
self.__canvas.itemconfig(text2_shadow, text="Press r to play again.",
font=self.scorefont, fill="black")
self.__canvas.tag_raise(text1)
self.__canvas.tag_raise(text2)
def clear_messages(self):
for txt in self.__messages:
self.__canvas.delete(txt)
self.__messages.clear()
def update(self):
for block_view in self.__block_views:
block_view.redraw(self.__canvas)
self.display_score()
示例8: __init__
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import delete [as 别名]
class KlicketyGUI:
"""Interface pour le jeu Klickety."""
def __init__(self):
# initialisation des structures de données ----------------------------
self.dim_plateau = (10, # nombre de colonnes du plateau
16) # nombre de lignes du plateau
self.cote_case = 32 # la longueur du côté d'un bloc à dessiner
self.largeur_plateau = self.cote_case * self.dim_plateau[0]
self.hauteur_plateau = self.cote_case * self.dim_plateau[1]
self.plateau = []
self.compteur_de_coups = 0
# initialisation des éléments graphiques ------------------------------
self.window = Tk() # la fenêtre principale
self.window.resizable(0, 0) # empêcher les redimensionnements
self.partie_haut = Frame(self.window, width=self.largeur_plateau,
height=self.hauteur_plateau)
self.partie_haut.pack(side=TOP)
self.partie_bas = Frame(self.window)
self.partie_bas.pack(side=BOTTOM)
# le canevas affichant le plateau de jeu
self.plateau_affiche = Canvas(self.partie_haut,
width=self.largeur_plateau,
height=self.hauteur_plateau)
self.plateau_affiche.pack()
self.plateau_affiche.bind('<ButtonPress-1>', self.clicPlateau)
# le bouton "Réinitialiser"
self.btn = Button(self.partie_bas, text='Réinitialiser',
command=self.reinitialiserJeu)
self.btn.pack(fill=BOTH)
# Zone d'affichage du nombre de coups
self.nb_coups_affiche = Canvas(self.partie_bas,
width=self.largeur_plateau, height=32)
self.nb_coups_affiche.create_text(
self.largeur_plateau // 2, self.cote_case // 2,
text="Coups effectués: 0", fill="black"
)
self.nb_coups_affiche.pack(fill=BOTH)
# affichage du nombre de blocs restants
self.nb_blocs_affiche = Canvas(self.partie_bas,
width=self.largeur_plateau, height=32)
self.nb_blocs_affiche.pack(fill=BOTH)
self.reinitialiserJeu()
self.window.title('Klickety')
self.window.mainloop()
def rafraichirNombreBlocs(self, piece=None):
"""Rafraîchit l'affichage du nombre de blocs restants, sur base de la
pièce que l'on vient de retirer."""
self.nb_blocs_affiche.delete(ALL)
if piece is None: # appel initial, tous les blocs sont encore présents
self.nb_blocs = self.dim_plateau[0] * self.dim_plateau[1]
else: # soustraire du nombre de blocs celui de la pièce retirée
self.nb_blocs -= len(piece)
self.nb_blocs_affiche.create_text(
self.largeur_plateau // 2, self.cote_case // 2,
text="Blocs restants: " + str(self.nb_blocs), fill="black"
)
def compteCoups(self, compteur_de_coups):
"""Compte le nombre de coups effectués durant cette partie."""
self.nb_coups_affiche.delete(ALL)
self.nb_coups_affiche.create_text(
self.largeur_plateau // 2, self.cote_case // 2,
text="Coups effectués: " + str(compteur_de_coups), fill="black"
)
def rafraichirPlateau(self):
"""Redessine le plateau de jeu à afficher."""
# tracer les blocs
self.plateau_affiche.delete(ALL)
couleur_fond = "black"
for i in range(self.dim_plateau[0]): # par défaut 10
for j in range(self.dim_plateau[1]): # par défaut 16
case = self.plateau[i][j]
if case is not None: # afficher le pion
self.plateau_affiche.create_rectangle(
i * self.cote_case, j * self.cote_case,
(i + 1) * self.cote_case, (j + 1) * self.cote_case,
outline=case, fill=case
)
else:
self.plateau_affiche.create_rectangle(
i * self.cote_case, j * self.cote_case,
(i + 1) * self.cote_case, (j + 1) * self.cote_case,
outline=couleur_fond, fill=couleur_fond
)
# tracer le contour des pièces
# 1) tracer les séparations entre deux pièces adjacentes de
# couleurs différentes dans la même colonne
for i in range(0, self.dim_plateau[0]): # par défaut 10
#.........这里部分代码省略.........
示例9: Window
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import delete [as 别名]
class Window(Frame):
def __init__(self, parent):
Frame.__init__(self, parent, background="dark gray")
self.parent = parent
self.initUI()
self.initPuzzles()
self.run()
def initUI(self):
self.parent.title("Block")
self.pack(fill=BOTH, expand=1)
self.initCanvas()
self.initInterfaceZone()
def initCanvas(self):
self.canvas = Canvas(self, background="dark gray")
self.canvas.pack(expand=1,fill=BOTH,padx=1,pady=1)
def initInterfaceZone(self):
# Draw the play, step and loading buttons
self.interfaceFrame = Frame(self, background="dark gray")
self.playFrame = Frame(self.interfaceFrame, background="dark gray")
self.loadFrame = Frame(self.interfaceFrame, background="dark gray")
self.isPlaying = False
#Do the run buttons
playButton = Button(self.playFrame, text=">", command=self.playPress)
playButton.grid(row=0,column=0)
pauseButton = Button(self.playFrame, text="||", command=self.pausePress)
pauseButton.grid(row=0,column=1)
stepBackButton = Button(self.playFrame, text="|<", command=self.stepBackPress)
stepBackButton.grid(row=1,column=0)
stepForwardButton = Button(self.playFrame, text=">|", command=self.stepForwardPress)
stepForwardButton.grid(row=1,column=1)
self.playFrame.pack(side=LEFT, expand=1, fill=BOTH)
#Do the load-y stuff
self.boardInputField = Entry(self.loadFrame)
self.boardInputField.grid(row=0, column=0)
boardInputButton = Button(self.loadFrame, text="Load Board", command=self.loadBoardPress)
boardInputButton.grid(row=0, column=1)
self.moveInputField = Entry(self.loadFrame)
self.moveInputField.grid(row=1,column=0)
moveInputButton = Button(self.loadFrame, text="Load Moves", command=self.loadMovesPress)
moveInputButton.grid(row=1, column=1)
self.loadFrame.pack(side=LEFT, expand=1, fill=BOTH)
self.interfaceFrame.pack(side=BOTTOM)
def initPuzzles(self):
self.pieces = [] # Once a puzzle's loaded, will be a list of drawnBlocks
self.boardWidth = 100
self.boardHeight = 100
self.blockWidth = 30
self.blockHeight = 30
self.rosterBlockWidth = 0
self.rosterBlockHeight = 0
self.rosterStartX = 0
self.moveList = []
self.atMove = 0
def run(self):
self.after(DELAY,self.onTimer)
def loadPuzzle(self, puzzle):
# Accept a puzzle and load it into the GUI
# First clear memory
self.pieces = []
self.canvas.delete("all")
self.moveList = []
self.atMove = 0
#Set up the board and piece roster
squareSize = min(maxBoardWidth/puzzle.cols, maxBoardHeight/puzzle.rows)
self.blockWidth = squareSize
self.blockHeight = squareSize
self.boardWidth = self.blockWidth*puzzle.cols
self.boardHeight = self.blockHeight*puzzle.rows
self.rosterStartX = boardStartX + self.boardWidth + extRosterPadding
rosterX = self.rosterStartX
rosterY = boardStartY + intRosterPadding
maxHeight = 0
#Start creating pieces, filling roster as we go
for piece in puzzle.universe:
label = piece.getLabel()
if rosterX + intRosterPadding + piece.cols*self.blockWidth + intRosterPadding - self.rosterStartX <= rosterWidth:
self.pieces.append(drawnBlock(self.canvas,piece,rosterX+intRosterPadding,rosterY,label=label, colour = colourDict[label], boxSize = self.blockWidth))
rosterX += intRosterPadding + piece.cols*self.blockWidth
if piece.rows*self.blockHeight>maxHeight:
maxHeight = piece.rows*self.blockHeight
#.........这里部分代码省略.........
示例10: World
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import delete [as 别名]
#.........这里部分代码省略.........
return
flag = (x, y) not in list(self.beepers.keys()) or \
self.beepers[(x, y)] is 0
if flag:
self.beepers[(x, y)] = 1
else:
self.beepers[(x, y)] += 1
text = str(self.beepers[(x, y)])
a = self.t + x * self.t
b = self.n - (self.t + y * self.t)
t = self.t / 3
if flag:
self.ovals[(x, y)] = self.canvas.create_oval(a-t, b-t, a+t, b+t,
fill="black")
self.numbers[(x, y)] = self.canvas.create_text(a, b, text=text,
fill="white",
font=("Times",
max(-self.t/2,
-20),
""))
else:
self.canvas.itemconfig(self.numbers[(x, y)], text=text)
if (x, y) in list(self.robots.keys()):
for robot in self.robots[(x, y)]:
robot.lift()
def remove_beeper(self, x, y):
if self.beepers[(x, y)] is INFINITY:
return
self.beepers[(x, y)] -= 1
flag = self.beepers[(x, y)] is 0
text = str(self.beepers[(x, y)])
if flag:
self.canvas.delete(self.ovals[(x, y)])
self.canvas.delete(self.numbers[(x, y)])
else:
self.canvas.itemconfig(self.numbers[(x, y)], text=text)
if (x, y) in list(self.robots.keys()):
for robot in self.robots[(x, y)]:
robot.lift()
def add_wall(self, x1, y1, x2, y2):
if not x1 == x2 and not y1 == y2:
return
if x1 == x2:
y1, y2 = min(y1, y2), max(y1, y2)
if y1 == -1:
y1 = y2
for k in range(y1, y2+1):
self.walls.setdefault((x1, k), []).append((x1+1, k))
a = self.t + x1 * self.t+self.t / 2
b = self.n - (self.t + k * self.t) + self.t / 2
c = self.t + x1 * self.t + self.t / 2
d = self.n - (self.t + k * self.t) - self.t / 2
self.canvas.create_line(a, b+1, c, d-1, fill="black", width=3)
else:
x1, x2 = min(x1, x2), max(x1, x2)
if x1 == -1:
x1 = x2
for k in range(x1, x2+1):
self.walls.setdefault((k, y1), []).append((k, y1+1))
a = self.t + k * self.t - self.t / 2
b = self.n - (self.t + y1 * self.t) - self.t / 2
c = self.t + k * self.t + self.t / 2
d = self.n - (self.t + y1 * self.t) - self.t / 2
self.canvas.create_line(a-1, b, c+1, d, fill="black", width=3)
示例11: SkylineUI
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import delete [as 别名]
class SkylineUI(Frame):
"""
GUI for the skyline game
"""
def __init__(self, parent, game):
self.game = game
self.parent = parent
Frame.__init__(self, parent)
self.row, self.col = 0, 0
self.__initUI()
def __initUI(self):
self.parent.title("Skyline")
self.pack(fill=BOTH, expand=1)
self.canvas = Canvas(self,
width=WIDTH,
height=HEIGHT)
self.canvas.pack(fill=BOTH, side=TOP)
clear_button = Button(self,
text="Reset",
command=self.__clear_answers)
clear_button.pack(fill=BOTH, side=BOTTOM)
self.__draw_grid()
self.__draw_game()
self.canvas.bind("<Button-1>", self.__cell_clicked)
self.canvas.bind("<Key>", self.__key_pressed)
def __draw_grid(self):
"""
Draws grid divided with blue lines into 3x3 squares
"""
for i in range(self.game.size + 3):
color = "blue" if i % 6 == 0 else "gray"
if i == 1 or i == self.game.size + 1:
color = "red"
x0 = MARGIN + i * SIDE
y0 = MARGIN
x1 = MARGIN + i * SIDE
y1 = HEIGHT - MARGIN
self.canvas.create_line(x0, y0, x1, y1, fill=color)
x0 = MARGIN
y0 = MARGIN + i * SIDE
x1 = WIDTH - MARGIN
y1 = MARGIN + i * SIDE
self.canvas.create_line(x0, y0, x1, y1, fill=color)
def __draw_game(self):
self.canvas.delete("numbers")
for i in range(0, self.game.size):
for j in range(0, self.game.size):
answer = self.game.board[i][j]
#if answer != 0:
x = MARGIN + (j+1) * SIDE + SIDE / 2
y = MARGIN + (i+1) * SIDE + SIDE / 2
original = self.game.board_object.empty_board[i][j]
color = "black" if answer == 0 else "sea green"
self.canvas.create_text(
x, y, text=answer, tags="numbers", fill=color
)
self.__draw_hints()
def __clear_answers(self):
self.game.start()
self.canvas.delete("victory")
self.__draw_game()
def __draw_cursor(self):
self.canvas.delete("cursor")
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(
x0, y0, x1, y1,
outline="red", tags="cursor"
)
def __cell_clicked(self, event):
if self.game.hasWon:
return
x, y = event.x, event.y
if (MARGIN < x < WIDTH - MARGIN and MARGIN < y < HEIGHT - MARGIN):
self.canvas.focus_set()
# get row and col numbers from x,y coordinates
row, col = (y - MARGIN) / SIDE, (x - MARGIN) / SIDE
#.........这里部分代码省略.........
示例12: margin
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import delete [as 别名]
#.........这里部分代码省略.........
return # not on the grid
self.lastPosition = (x, y)
self.paintBackground(x, y, self.checkFree(x, y))
def mouseClick(self, event):
"""Catch mouse click to confirm the insertion or removal (if in
Edit mode) of a pentomino on the cell under the mouse pointer
"""
if self.editMode:
self.applyEditing(event)
self.clearEditCursor(event)
return
x = (event.y - self.margin) // self.cellSize
y = (event.x - self.margin) // self.cellSize
if self.checkFree(x, y) == self.colors['busy']:
return # clicked busy position
self.onBoard += 1
self.refreshScore()
self.history.append((
self.setBusy(x, y),
self.addPentomino(x, y)
))
if self.onBoard == self.expectedBest:
self.gameOver()
def goBackInTime(self):
"""Removes the most recently inserted pentomino
"""
if (len(self.history) == 0):
return
notBusy, notVisible = self.history.pop()
for cell in notVisible:
for item in cell[0] + cell[1]:
self.canvas.delete(item)
for x, y in notBusy:
self.gridBusy[x][y] = 0
self.onBoard -= 1
self.refreshScore()
def setBusy(self, x, y):
"""Sets as "busy" the cells occupied by a pentomino centered at
(x, y) rotated as the current rotation stored in self.rotation
"""
changes = []
for i in range(self.numPieces):
new_x = x + self.pos[self.rotation][i][0]
new_y = y + self.pos[self.rotation][i][1]
changes.append((new_x, new_y))
self.gridBusy[new_x][new_y] = self.onBoard
self.correctPending()
return changes
def addPentomino(self, x, y):
"""Adds a new pentomino with its center in the position (x, y)
of the grid and returns the list of changes done. Each element
of the list returned is a cell (that is the list of IDs of the
new drawn items)
"""
changes = []
for i in range(self.numPieces):
new_x = x + self.pos[self.rotation][i][0]
new_y = y + self.pos[self.rotation][i][1]
changes.append(self.drawCell(
new_x, new_y, self.colors['pentomino'], self.info[self.rotation][i]
))
return changes
示例13: __init__
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import delete [as 别名]
class GameScreen:
def __init__(self, master, params, model=None):
self.master = master
self.controller = GameScreenController(params, model=model)
self.width = self.controller.model.width
self.height = self.controller.model.height
self.graphic_init()
self.is_run = True
self.run()
def draw(self):
# Сделать 4 солнца
model = self.controller.model
x, y = model.sun_x, model.sun_y
suns = [(x, y), (x - self.width, y), (x, y - self.height), (x - self.width, y - self.height)]
for x, y in suns:
self.canvas.create_rectangle(
max(0, x),
max(0, y),
min(x + model.sun_size, self.width + 1),
min(y + model.sun_size, self.height + 1),
fill="yellow",
)
for coord, creature in model.creatures.items():
color = "#00{:0>2}00".format(hex(int(creature.life * 255))[2:])
if not creature.alive:
color = "red"
func = self.canvas.create_oval
func(coord[0], coord[1], coord[0] + 6, coord[1] + 6, fill=color)
def graphic_init(self):
self.frame = Frame(self.master, bd=2)
self.button_frame = Frame(self.frame, bd=2)
self.button_frame.grid_bbox(row=1, column=4)
self.start_stop_button = Button(self.button_frame, text="Пауза", command=self.start_stop_pressed)
self.start_stop_button.grid(row=1, column=2)
self.save_button = Button(self.button_frame, text="Сохранить", command=self.save_pressed)
self.save_button.grid(row=1, column=1)
self.info_button = Button(self.button_frame, text="Инфо", command=self.info_pressed, state=DISABLED)
self.info_button.grid(row=1, column=4)
self.add_button = Button(self.button_frame, text="Добавить существо", command=self.add_pressed)
self.add_button.grid(row=1, column=3)
self.canvas = Canvas(self.frame, width=self.width, height=self.height)
self.canvas.pack(side=TOP)
self.button_frame.pack()
self.frame.pack()
def start_stop_pressed(self):
self.is_run = not self.is_run
self.start_stop_button.config(text="Пауза" if self.is_run else "Старт")
self.info_button.config(state=DISABLED if self.is_run else ACTIVE)
self.run()
def save_pressed(self):
filename = asksaveasfilename(title="Сохранить мир")
if filename:
try:
self.controller.save_pressed(filename)
except Exception as e:
messagebox.showerror("Не удалось сохранить файл", str(e))
def info_pressed(self):
InfoWindow(self.controller.model)
def add_pressed(self):
self.controller.add_pressed()
def run(self):
if self.is_run:
self.canvas.delete("all")
self.controller.run()
self.draw()
self.master.after(1, self.run)
示例14: simpleGui
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import delete [as 别名]
class simpleGui(tkinter.Tk):
def __init__(self, parent):
tkinter.Tk.__init__(self, parent)
self.parent = parent
self.initialize()
def initialize(self):
self.grid()
self.config(bg="white")
self.geometry("600x500")
self.algo = ACAlgo()
self.wordFrames=[]
self.path=""
self.lastCanvasIndex=0
rowLine=0
self.entryPath = tkinter.Entry(self, width=75)
self.entryPath.grid(column=0, row=rowLine,columnspan=3, sticky='NEW')
self.entryPath.bind("<Return>", self.setPath)
buttonSetPath = tkinter.Button(self, text="Set path", width=21, height=1, command=self.setPath)
buttonSetPath.grid(column=3, row=rowLine, sticky='EWN')
rowLine=rowLine+1
self.entry = tkinter.Entry(self, width=75)
self.entry.grid(column=0, row=rowLine,columnspan=2, sticky='NEWS')
self.entry.bind("<Return>", self.addWords)
buttonAddWords = tkinter.Button(self, text="Add words", width=21,height=1, command=self.addWords)
buttonAddWords.grid(column=3, row=rowLine, sticky='EWNS')
rowLine=rowLine+1
self.grid_rowconfigure(rowLine, weight=1)
self.textBox = tkst.ScrolledText(self, width=20, height=10)
self.textBox.grid(column=0, row=rowLine, columnspan=3, sticky='NWES')
self.textBox.config(state=DISABLED)
self.canvas= Canvas(master=self,width=150)
self.vscroll = Scrollbar(self)
self.vscroll.config(command=self.canvas.yview)
self.canvas.config(yscrollcommand=self.vscroll.set)
self.canvas.grid( row=rowLine, column=3, sticky='NES')
self.vscroll.grid(padx=1, pady=1, row=rowLine, column=4, sticky='NEWS')
rowLine=rowLine+1
buttonClearHighlight = tkinter.Button(self, text="Clear highlight", width=20, command=self.removeHighlightsBtn)
buttonClearHighlight.grid(column=0, row=rowLine, sticky="WS")
buttonDeleteWords = tkinter.Button(self, text="Delete words", width=20, command=self.resetAll)
buttonDeleteWords.grid(column=3, row=rowLine, sticky="ES")
self.grid_columnconfigure(0, weight=1)
self.grid_columnconfigure(1, weight=1)
def setPath(self):
try:
open(self.entryPath.get())
except:
return
self.path=self.entryPath.get()
self.textBox.config(state=NORMAL)
self.textBox.insert(tkinter.INSERT, open(self.path).read())
self.textBox.config(state=DISABLED)
def removeHighlights(self):
for wordFrame in self.wordFrames:
wordFrame.removeHighLight()
def removeHighlightsBtn(self, entry=""):
for wordFrame in self.wordFrames:
wordFrame.removeHighLight()
self.update_idletasks()
def resetAll(self, entry=""):
self.removeHighlights()
self.algo.resetTree()
self.lastCanvasIndex=0;
self.wordFrames=[]
self.canvas.delete("all")
self.update_idletasks()
#.........这里部分代码省略.........
示例15: Scene
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import delete [as 别名]
class Scene(object):
def __init__(self, master, device, mouse_tracking=False):
self.master = master
self.device = device
self.frame = tk.Frame(master)
self.feedbackButton = tk.Button(
self.frame,
text="Feedback window",
width=25,
command=self.open_feedback
)
self.feedbackButton.pack()
self.explore_canvas = Canvas(master, width=500, height=500)
self.explore_canvas.pack()
if mouse_tracking:
self.explore_canvas.bind(
'<Motion>', lambda event, device=device: motion(event, device))
self.enable_position_feedback()
self.network_drawings = []
self.frame.pack()
self.app = None
self.update()
def activate_key_listening(self, listener):
# Will focus frame, needed for key binding
self.explore_canvas.bind(
"<Button-1>",
lambda event,
frame=self.explore_canvas: focus(event, frame)
)
self.explore_canvas.bind(
"<Key>",
lambda event: listener.update_pressed_key(str(event.char))
)
def desactivate_key_listening(self):
self.explore_canvas.unbind("<Button-1>")
self.explore_canvas.unbind("<Key>")
def enable_position_feedback(self):
self.device_cursor = self.explore_canvas.create_oval(
self.device.position.x - 2.5, self.device.position.y - 2.5,
self.device.position.x + 2.5, self.device.position.y + 2.5)
def draw_network(self, network):
self.explore_canvas.delete('all')
self.enable_position_feedback()
for node in network.nodes:
pos_x = node.x - 5
pos_y = node.y - 5
self.explore_canvas.create_oval(
pos_x, pos_y, pos_x + 10, pos_y + 10, fill="blue")
for link in network.links:
pt_a = link.first
pt_b = link.sec
self.explore_canvas.create_line(
pt_a.x, pt_a.y, pt_b.x, pt_b.y)
def update(self):
coords = self.explore_canvas.coords(self.device_cursor)
if len(coords) <= 3:
self.master.after(50, self.update)
return
center = ((coords[0] + coords[2]) / 2, (coords[1] + coords[3]) / 2)
self.explore_canvas.move(
self.device_cursor,
self.device.position.x - center[0],
self.device.position.y - center[1])
if self.app and not self.app.closed:
self.app.update()
self.master.after(50, self.update)
def open_feedback(self):
self.feedbackWindow = tk.Toplevel(self.master)
self.app = Feedback(self.feedbackWindow, self.device)