本文整理汇总了Python中tkinter.Canvas.tag_bind方法的典型用法代码示例。如果您正苦于以下问题:Python Canvas.tag_bind方法的具体用法?Python Canvas.tag_bind怎么用?Python Canvas.tag_bind使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tkinter.Canvas
的用法示例。
在下文中一共展示了Canvas.tag_bind方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import tag_bind [as 别名]
def __init__(self: 'PlatformView',
width: float,
click_handler: (lambda Event: None),
canvas: Canvas,
thickness: float,
x_center: float, y_center: float):
"""
Initialize a new PlatformView.
click_handler - function to react to mouse clicks
width - width in pixels of the displayed representation
canvas - space to draw a representation of this platform
thickness - vertical extent of this platform
x_center - center of this platform horizontally
y_center - center of this platform vertically
"""
self.canvas = canvas
self._width = width
self.x_center = x_center
self.y_center = y_center
self.thickness = thickness
# Create a rectangle on the canvas, and record the index that tkinter
# uses to refer to it.
self.index = canvas.create_rectangle(0, 0, 0, 0)
self.canvas.itemconfigure(self.index)
# Initial placement.
self.place(x_center, y_center)
# Tell the canvas to report when the rectangle is clicked.
# The report is a call to click_handler, passing it this CheeseView
# instance so the controller knows which one was clicked.
canvas.tag_bind(self.index,
'<ButtonRelease>',
lambda _: click_handler(self))
示例2: GPIOSim
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import tag_bind [as 别名]
#.........这里部分代码省略.........
self.phOutLeft = PhotoImage(data=bytes(imgOutLeft, 'latin1'))
self.phOutRight = PhotoImage(data=bytes(imgOutRight, 'latin1'))
self.updateUI()
# Method that updates the current status, getting info from the file
# Shall be called on receivment of SIGIUSR (sent by the GPIO class)
def updateUI(self):
self.canvas.delete("all")
c = RawConfigParser()
c.read(self.WORK_FILE)
x = self.START_X
y = self.START_Y
for i in range(0,40):
state = c.getint("pin"+str(i),"state")
value = c.getint("pin"+str(i),"value")
ident = 2*state+value
self.currState[i] = state
self.currValue[i] = value
e_x = x + self.PIN_SIZE
e_y = y + self.PIN_SIZE
self.canvas.create_oval(x, y, e_x, e_y, outline="black", fill=self.PIN_COLORS[ident], width=2, tags='pin'+str(i))
self.canvas.tag_bind('pin'+str(i),'<Button>', self.click_cb(i) )
if i%2==0: #LEFT COLUMN GPIOS
self.canvas.create_window(x-70, y+10, window=Label(self.canvas, text=self.GPIO_NAMES[i], fg=self.TEXT_COLOR, bg= self.BG_COLOR))
if ident==2: #IN_LOW
self.canvas.create_window(x - 20, y+8, window=Label(self.canvas, image=self.phInLeft, bd=0))
#freccia e cliccabile(?)
elif ident==3: #IN_HIGH
self.canvas.create_window(x - 20, y+8, window=Label(self.canvas, image=self.phInLeft, bd=0))
#freccia e cliccabile(?)
elif state==self.STATE_GPIO_OUT: #OUT
self.canvas.create_window(x - 20, y+8, window=Label(self.canvas, image=self.phOutLeft, bd=0))
x = e_x + self.PIN_DISTANCE
else: #RIGHT COLUMN GPIOS
self.canvas.create_window(e_x + 70, y+10, window=Label(self.canvas, text=self.GPIO_NAMES[i], fg=self.TEXT_COLOR, bg= self.BG_COLOR))
if ident==2: #IN_LOW
self.canvas.create_window(e_x + 22, y+8, window=Label(self.canvas, image=self.phInRight, bd=0))
#freccia e cliccabile(?)
elif ident==3: #IN_HIGH
self.canvas.create_window(e_x + 22, y+8, window=Label(self.canvas, image=self.phInRight, bd=0))
#freccia e cliccabile(?)
elif state==self.STATE_GPIO_OUT: #OUT
self.canvas.create_window(e_x + 22, y+8, window=Label(self.canvas, image=self.phOutRight, bd=0))
示例3: Game
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import tag_bind [as 别名]
class Game(object):
"""
"""
def __init__(self, wnd, w, h):
"""
"""
Database.init()
self.hexa_size = 80
self.width = w
self.height = h
self.canvas = Canvas(
wnd, width=self.width, height=self.height,
bg='#0080FF', highlightthickness=0, bd=0)
self.canvas.pack()
wnd.resizable(False, False)
self.player = Player(1)
self.inventory = Inventory()
self.hexagons = []
self.defaultBoardArgs = (2, 3, True)
self.canvas.tag_bind('hexagon', "<Button-1>", self.hexAction)
# TODO : Remove these tests
self.player.debug()
Database.debug_items()
self.inventory.addItem(0)
self.inventory.addItem(1)
self.inventory.addItem(0)
self.inventory.addItem(2)
self.inventory.addItem(0)
self.inventory.debug()
Database.debug_enemies()
def hexAction(self, event):
tmp = self.canvas.find_withtag(CURRENT)
if tmp:
id = tmp[0]
index = self.getHexIndexByID(id)
if self.hexagons[index].hasTag('Player'):
print("Action: Open Inventory")
elif self.hexagons[index].hasTag('Enemy'):
print("Action: Attack")
else:
print("Action: Move")
movePos = self.hexagons[index].position
if movePos[0] == 0 and movePos[1] == 0:
return
def move(t, nIndex):
self.hexagons[nIndex].setEntity(t.entity)
t.unsetEntity()
move(self.hexagons[self.getPlayerHexIndex()], index)
doneIDs = []
def moveUtil(t):
nPos = [t.position[0] - movePos[0], t.position[1] - movePos[1]]
if nPos[0] % 2 and not t.position[0] % 2:
nPos[1] -= 1
nPos = tuple(nPos)
nIndex = self.getHexIndexByPosition(nPos)
if nIndex == -1:
if not((nPos[0] < t.position[0] and nPos[1] < t.position[0]) or (nPos[0] > t.position[0] and nPos[1] == t.position[1])):
t.unsetEntity()
doneIDs.append(t.id)
return
if not nIndex in doneIDs:
moveUtil(self.hexagons[nIndex]) # Bad recursion... but works with small boards
move(t, nIndex)
doneIDs.append(t.id)
for t in self.hexagons:
if t.id in doneIDs:
continue
moveUtil(t)
def getBoardWidth(self, row=-1):
return self.defaultBoardArgs[1]
def getBoardHeight(self, column):
# This code is a bit tricky
# Since the board is composed of hexagons
# The height isn't the same on every row
# (at least that's how we handled everything)
# We use the self.defaultBoardArgs
# Basically, it'll handle the board's form
# If self.defaultBoardArgs[2] is True, then the first
# column will have the lowest number
# of rows, eg. if self.defaultBoardArgs[0] is set to 2
# then the first column will have 2 rows
# The other columns have 1 more row
# The best way to understand is to try it x)
n = 0
if column % 2 :
if self.defaultBoardArgs[2]:
n = self.defaultBoardArgs[0] + 1
else:
n = self.defaultBoardArgs[0]
else:
if self.defaultBoardArgs[2]:
n = self.defaultBoardArgs[0]
else:
n = self.defaultBoardArgs[0] + 1
#.........这里部分代码省略.........
示例4: GUI
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import tag_bind [as 别名]
class GUI(Frame):
def __init__(self, game, size, margin, colors=('black', 'white'), master=None):
color = '#333333'
Frame.__init__(self, master, bg=color)
self.game = game
self.cell_size = (size - 2*margin) / self.game.size
self.coordinates = lambda position: self.cell_size * (np.array(position) + 1/2) + margin
self.player_move = lambda event: self.move(pause=1000, event=event)
self.grid()
self.master.title("Pythello")
self.colors = colors[::-1] # Flip color order so that the first color input corresponds to player 1
max_turns = self.game.size**2 - 4
figure = Figure(figsize=(size/100, size/100), dpi=100, facecolor=color)
axes = figure.add_subplot(111, axisbg=color)
self.line = axes.plot(0, 0, 'w-', [0, max_turns], [0, 0], 'w--')[0]
axes.grid(True, color='w')
axes.set_xlim(0, max_turns)
axes.set_ylim(-max_turns, max_turns)
[tick.set_color('w') for axis in [axes.xaxis, axes.yaxis] for tick in axis.get_ticklines()]
[label.set_color('w') for axis in [axes.xaxis, axes.yaxis] for label in axis.get_ticklabels()]
[axes.spines[side].set_color('w') for side in ['top', 'bottom', 'left', 'right']]
self.canvas = Canvas(self, width=size, height=size, background=color, highlightthickness=0)
self.canvas.create_rectangle(margin, margin, size - margin, size - margin, outline='white')
self.canvas.grid(row=0, column=1, rowspan=50)
self.figure = FigureCanvasTkAgg(figure, master=self)
self.figure.get_tk_widget().grid(row=0, column=2, rowspan=50)
self.refresh()
if all([isinstance(player, AI) for player in self.game.players]):
self.play_button = Button(self, text='Play', highlightbackground=color, command=self.play)
self.move_button = Button(self, text='Move', highlightbackground=color, command=self.move)
self.reset_button = Button(self, text='Reset', highlightbackground=color, command=self.reset)
self.play_button.grid(row=0, column=0)
self.move_button.grid(row=1, column=0)
self.reset_button.grid(row=2, column=0)
self.running = False
else:
Button(self, text='Reset', highlightbackground=color, command=self.reset).grid(row=0, column=0)
self.running = True
for i in range(self.game.size):
line_shift = self.cell_size * (i+1) + margin
self.canvas.create_text(margin-10, line_shift - self.cell_size/2, text=str(i+1), fill='white')
self.canvas.create_text(line_shift - self.cell_size/2, margin-10, text=chr(97+i), fill='white')
self.canvas.create_line(margin, line_shift, size - margin, line_shift, fill='white')
self.canvas.create_line(line_shift, margin, line_shift, size - margin, fill='white')
def configure_buttons(self):
(state, text, command) = ('disabled', 'Pause', self.pause) if self.running else ('normal', 'Reset', self.reset)
self.play_button.config(state=state)
self.move_button.config(state=state)
self.reset_button.config(text=text, command=command)
def draw_piece(self, position, radius, color):
(y, x) = self.coordinates(position)
return self.canvas.create_oval(x-radius, y-radius, x+radius, y+radius, fill=color, tags='circle')
def move(self, pause=10, event=None):
if event is None:
move = self.game.player.move(self.game)
else:
move = eval(self.canvas.gettags(event.widget.find_withtag("current"))[-2])
self.game.move(move)
is_over = self.game.is_over()
self.refresh()
if not is_over and isinstance(self.game.player, AI) and self.running:
self.after(pause, self.move)
elif is_over:
self.reset_button.config(text='Reset', command=self.reset)
def pause(self):
self.running = False
self.configure_buttons()
def play(self):
self.running = True
self.configure_buttons()
self.move()
def refresh(self):
self.line.set_data(range(len(self.game.score)), self.game.score)
self.figure.draw()
[self.canvas.delete(tag) for tag in ['circle', 'text']]
for position in zip(*np.nonzero(self.game.board)):
color = self.colors[int((self.game.board[position] + 1) / 2)]
self.draw_piece(position, (self.cell_size-2) / 2, color)
if not isinstance(self.game.player, AI):
for position in self.game.valid:
(y, x) = self.coordinates(position)
turned = len(self.game.valid[position]) - 1
valid = self.draw_piece(position, self.cell_size / 4, 'green')
self.canvas.addtag(str(position), 'withtag', valid)
text = self.canvas.create_text(x+1, y+1, text=str(turned), tags=('text', str(position)))
[self.canvas.tag_bind(tag, "<Button-1>", self.player_move) for tag in [valid, text]]
#.........这里部分代码省略.........
示例5: TKinterDisplay
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import tag_bind [as 别名]
class TKinterDisplay(Display):
'''
classdocs
'''
'''
Constructor
'''
def __init__(self, lineThickness=3, maxH=1920, maxW=1080):
master = Tk()
master.maxsize(maxH, maxW)
self.localCanvas = Canvas(master, width=400, height=400)
self.currentlyRenderedWindow = None
self.lineThickness = lineThickness
self.vsb = Scrollbar(master, orient="vertical", command=self.localCanvas.yview)
self.hsb = Scrollbar(master, orient="horizontal", command=self.localCanvas.xview)
self.localCanvas.configure(yscrollcommand=self.vsb.set)
self.localCanvas.configure(xscrollcommand=self.hsb.set)
master.bind("<Configure>", self.__eventOnFrameConfigure)
self.hsb.pack(side="bottom", fill="x")
self.vsb.pack(side="right", fill="y")
self.localCanvas.pack()
self.__sampleDraw()
''''''
@abstractmethod
def drawSquare(self, xywhTuple, tags=None, colour=None, content=None):
x2 = xywhTuple[0] + xywhTuple[2]
y2 = xywhTuple[1] + xywhTuple[3]
square = self.localCanvas.create_rectangle(xywhTuple[0], xywhTuple[1], x2, y2, width=self.lineThickness, tags=tags, fill=colour, activeoutline="white")
def handler(event, self=self, content=content):
return self.__eventOnClick(event, content)
self.localCanvas.tag_bind(square, "<ButtonRelease-1>", handler)
return square
@abstractmethod
def drawCircle(self, xywhTuple, tags=None , colour=None, content=None):
x2 = xywhTuple[0] + xywhTuple[2]
y2 = xywhTuple[1] + xywhTuple[3]
circle = self.localCanvas.create_oval(xywhTuple[0], xywhTuple[1], x2, y2, width=self.lineThickness, tags=tags, fill=colour, activeoutline="white")
def handler(event, self=self, content=content):
return self.__eventOnClick(event, content)
self.localCanvas.tag_bind(circle, "<ButtonRelease-1>", handler)
return circle
@abstractmethod
def connectIdWithLine(self, id1, id2, tags=None, colour=None):
# Gets the coordinates of id1 and then calulates centre point
id1tuple = self.__getCoords(id1)
x1 = id1tuple[0] + ((id1tuple[2] - id1tuple[0]) / 2)
y1 = id1tuple[1] + ((id1tuple[3] - id1tuple[1]) / 2)
# Gets the coordinates of id2 and then calulates centre point
id2tuple = self.__getCoords(id2)
x2 = id2tuple[0] + ((id2tuple[2] - id2tuple[0]) / 2)
y2 = id2tuple[1] + ((id2tuple[3] - id2tuple[1]) / 2)
# Calculates, using trig, the angle of the line at shape id1. This gives the radius of the ellipse
opposite = y1 - y2
adjacent = x1 - x2
x1angle = 0
x2angle = 0
hyp = 0
if adjacent != 0 and opposite != 0:
hyp = math.sqrt(math.pow(opposite, 2) + math.pow(adjacent, 2))
x1angle = math.tan(opposite / adjacent)
x2angle = math.tan(adjacent / opposite)
else:
if opposite == 0:
hyp = adjacent
else:
hyp = opposite
x1angle = math.radians(90)
x2angle = math.radians(270)
a1 = (id1tuple[2] - id1tuple[0]) / 2
b1 = (id1tuple[3] - id1tuple[1]) / 2
a2 = (id2tuple[2] - id2tuple[0]) / 2
b2 = (id2tuple[3] - id2tuple[1]) / 2
r1 = a1 * b1 / (math.sqrt(((a1 * a1) * (math.pow(math.sin(x1angle), 2))) + ((b1 * b1) * math.pow(math.cos(x1angle), 2))))
r2 = a2 * b2 / (math.sqrt(((a2 * a2) * (math.pow(math.sin(x2angle), 2))) + ((b2 * b2) * math.pow(math.cos(x2angle), 2))))
x1 = x1 + ((r1 / hyp) * (x2 - x1))
y1 = y1 + ((r1 / hyp) * (y2 - y1))
#x2 = x2 + ((r2 / hyp) * (x1 - x2))
#y2 = y2 - ((r2 / hyp) * (y1 - y2))
return self.__drawLine(x1, y1, x2, y2, tags, colour)
#.........这里部分代码省略.........
示例6: main
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import tag_bind [as 别名]
def main():
parser = ArgumentParser(prog="YandereLauncher")
parser.add_argument("-d", "--dryrun", help="Don't change anything on the filesystem, just print what's going on", action="store_true")
parser.add_argument("-s", "--cdn", help="Specify a different server URL, with trailing slash")
parser.add_argument("-e", "--skip-extract", help="Skip extraction of zip", action="store_false")
parser.add_argument("-v", "--verbose", help="Print full traceback for all exceptions", action="store_true")
parser.add_argument("--redownload", help="Redownload game files (DELETES ALL DIRECTORIES AND ZIPS MATCHING YandereSim* IN CURRENT DIR)", action="store_true")
parser.add_argument("--gui", help="Show GUI (defaults to true if frozen)", action="store_true")
args = parser.parse_args()
if args.cdn:
global CDN
CDN = args.cdn
if args.dryrun:
global DRYRUN
DRYRUN = True
if args.verbose:
global VERBOSE
VERBOSE = True
if args.redownload:
from glob import glob
for a in glob(os.path.join(ROOT, "YandereSim*")):
if os.path.isdir(a):
rmtree(a)
elif a[-4:] == ".zip":
unlink(a)
if getattr(sys, 'frozen', False) or args.gui:
# init tkinter
root = Tk()
root.title("YandereLauncher")
# background image
with open(path_to("YandereLauncher.gif"), "rb") as f:
photo = PhotoImage(data=base64.encodestring(f.read()))
cv = Canvas(width=635, height=355)
cv.pack(side='top', fill='both', expand='yes')
cv.create_image(0, 0, image=photo, anchor=NW)
def start_game(event):
try:
with open(getcfg()) as f:
Popen(["start", f.read()])
except:
print("You need to run an update")
play = cv.create_rectangle(88, 260, 244, 323, fill="", outline="")
cv.tag_bind(play, "<ButtonPress-1>", start_game)
update = cv.create_rectangle(400, 260, 555, 323, fill="", outline="")
cv.tag_bind(update, "<ButtonPress-1>", lambda event: Thread(target=get_latest_zip))
global GUI_LOGSTR
GUI_LOGSTR = (cv, cv.create_text(166, 199, text="Ready to update...", width=311, justify=CENTER, anchor=NW))
# close = cv.create_rectangle(622, 5, 640, 22, fill="", outline="")
# cv.tag_bind(close, "<ButtonPress-1>", lambda root=root:root.destroy())
root.mainloop()
else:
if get_latest_zip(extract=args.skip_extract):
print("Download was successful")
return 0
else:
print("Download was unsuccessful")
return 1