本文整理汇总了Python中tkinter.Canvas.create_rectangle方法的典型用法代码示例。如果您正苦于以下问题:Python Canvas.create_rectangle方法的具体用法?Python Canvas.create_rectangle怎么用?Python Canvas.create_rectangle使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tkinter.Canvas
的用法示例。
在下文中一共展示了Canvas.create_rectangle方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: Wall
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_rectangle [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: set_view
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_rectangle [as 别名]
def set_view(self, root_view: tk.Canvas=None, _x=0, _y=0):
if isinstance(root_view, tk.Canvas):
self.__Rect = RegionRect(root_view, self.__name, self.__current_price)
self.__Rect.grid(column=_x, row=2*_y)
frame = tk.Frame(root_view, height=38, width=0)
frame.grid(column=_x, row=2*_y+1)
x,y=_x*90, _y*80
root_view.create_rectangle(x,y, x+90, y+80, width=1, fill="white")
示例3: draw
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_rectangle [as 别名]
def draw(self,matrix, colours):
canvas = Canvas(self, background="white")
row = len(matrix)
col = len(matrix[0])
for i in range(0,row):
for j in range(0,col):
canvas.create_rectangle(i*boxWidth, j*boxHeight, (i+1)*boxWidth, (j+1)*boxHeight, fill=colours[matrix[i][j]],
outline=outlineColour, width=outlineWidth)
canvas.pack(fill=BOTH, expand=1)
示例4: WebbCanvas
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_rectangle [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")
示例5: draw
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_rectangle [as 别名]
def draw(self, canvas, fromX, fromY, toX, toY):
return Canvas.create_rectangle(canvas.getDrawArea(),
fromX,
fromY,
toX,
toY,
outline=canvas.getShapeColor(), width=self.PEN_WIDTH)
示例6: __init__
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_rectangle [as 别名]
def __init__(self, canvas: tk.Canvas, x, y):
self.width = 80
self.height = 10
self.ball = None # type: Ball
item = canvas.create_rectangle(
x - self.width / 2, y - self.height / 2, x + self.width / 2, y + self.height / 2, fill="blue"
)
super(Paddle, self).__init__(canvas, item)
示例7: draw
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_rectangle [as 别名]
def draw(self, canvas: tk.Canvas, points: [point.Point]) -> None:
'''Draws a dot onto a canvas, given its points'''
self._tl, self._br = points
self._tl_x, self._tl_y = self._tl.frac()
self._br_x, self._br_y = self._br.frac()
width = canvas.winfo_width()
height = canvas.winfo_height()
point_pixels = []
for point in points:
point_pixels.append(point.pixel(width, height))
canvas.create_rectangle(point_pixels[0][0],
point_pixels[0][1],
point_pixels[1][0],
point_pixels[1][1],
fill = 'black')
示例8: main
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_rectangle [as 别名]
def main():
DAYS = 365
WIDTH = 1000
base_url = "http://api.coindesk.com/v1/bpi/historical/close.json"
end = dtime.now().date()
start = end - timedelta(days=DAYS)
request_params = {
'start': start.strftime("%Y-%m-%d"),
'end': end.strftime("%Y-%m-%d"),
}
# что бы получить параметры в виде start=2014-10-10&end=...
response = requests.get(base_url, params=request_params)
if response.status_code != 200: # 200 is HTTP OK
print("Error, server returned: {}".format(response.status_code))
return
# мы получим строку от сервера, приведём в unicode строку
# и с помощью библиотеки json превратим в структуру
data = json.loads(response.content.decode('utf-8'))['bpi']
# data = {
# '2014-10-10': "353.53",
# '2014-10-08': "353.48",
# '2014-10-09': "356.03",
# }
# из чисел в строки
# map(int, '1', '2', '3') => int('1'), int('2'), int('3')
# в результате имеем числа (1, 2, 3)
max_value = ceil(max(data.values()))
root = Tk()
root.title = 'BitCoin graph'
root.geometry("{}x{}".format(WIDTH, max_value))
canvas = Canvas(root)
canvas.pack(fill=BOTH, expand=1)
step = WIDTH/len(data)
for key, value in data.items():
cur_date = dtime.strptime(key, "%Y-%m-%d").date()
days = (cur_date-start).days
canvas.create_rectangle(days*step, max_value,
(days+1)*step, max_value - round(value),
fill="black")
root.mainloop()
示例9: WindowInstance
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_rectangle [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")
示例10: Example
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_rectangle [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
示例11: initUI
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_rectangle [as 别名]
def initUI(self):
self.parent.title("Graphs")
self.pack(fill=BOTH, expand=1)
canvas = Canvas(self)
date = self.first_date
i = 1
total_sum = 0
while(date < self.last_date):
date += timedelta(days=1)
year = date.year
month = date.month
day = date.day
if self.trans_table.get_sum(year, month, day) != None:
total_sum += self.trans_table.get_sum(year, month, day)
x_coord1 = self.bar_spacing * i
x_coord2 = x_coord1 + self.bar_width
y_coord1 = self.vertical_bias
y_coord2 = total_sum
if y_coord2 == None:
y_coord2 = y_coord1
else:
y_coord2 = y_coord2 * self.sum_gain + y_coord1
# Draw the totalSum on every other day
if (day % 2) == 0:
i += 1
canvas.create_rectangle(x_coord1, y_coord1, x_coord2, y_coord2,
outline="#fb0", fill="#fb0")
canvas.pack(fill=BOTH, expand=1)
示例12: __init__
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_rectangle [as 别名]
def __init__(self: 'CheeseView',
size: float,
click_handler: (lambda Event: None),
canvas: Canvas,
thickness: float,
x_center: float, y_center: float) -> None:
"""
Initialize a new CheeseView.
size - horizontal extent of this cheese
click_handler - function to react to mouse clicks
canvas - space to draw a representation of this cheese
thickness - vertical extent of this cheese
x_center - center of this cheese horizontally
y_center - center of this cheese vertically
"""
# Call the superclass constructor appropriately.
super().__init__(size)
# Store canvas, thickness, x_center and y_center in instance variables.
self.canvas = canvas
self.thickness = thickness
self.x_center = x_center
self.y_center = y_center
# 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)
# Initial placement.
self.place(x_center, y_center)
# Initially unhighlighted.
self.highlight(False)
# 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.
self.canvas.tag_bind(self.index,
'<ButtonRelease>',
lambda _: click_handler(self))
示例13: __init__
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_rectangle [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))
示例14: Classes
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_rectangle [as 别名]
def Classes(sbjBook, string):
from tkinter import Tk
from tkinter import Canvas
import os
master = Tk()
w=1240
h=1754
m=120
c = Canvas(master, width=1240, height=1754)
c.pack()
c.create_rectangle(0, 0, w, h, fill="#fff", outline="#fff")
c.create_rectangle(m, 60, w-m, 180, fill="#9bbb59", outline="#cadba6")
c.create_text(m+60, 90, fill="#fff", font=("Ubuntu","12", "bold") , text="SUBJECT")
c.create_text(m+170, 90, fill="#fff", font=("Ubuntu","12", "bold") , text="CLASS")
c.create_text(m+420, 90, fill="#fff", font=("Ubuntu","12", "bold") , text="SCHEDULE")
c.create_text(m+720, 90, fill="#fff", font=("Ubuntu","12", "bold") , text="PROFESSOR")
c.create_text(m+920, 90, fill="#fff", font=("Ubuntu","12", "bold") , text="OFFERED AS")
for i in range(13):
c.create_rectangle(m, m+120*i, w-m, m+120*i+60, fill="#ebf1de", outline="#cadba6")
c.create_rectangle(m, m+120*i+60, w-m, m+120*i+120, fill="#fff", outline="#cadba6")
count = -1
page = 0
for i in sbjBook:
if(i == -1):
pass
else:
classroom = -1
sameSche = [[],[],[]]
scheRecord = [[],[],[]]
for j in range(len(sbjBook[i])):
classroom += 1
count += 1
period = sbjBook[i][j][1]
hpw = sbjBook[i][j][2]
professor = sbjBook[i][j][3]
group = sbjBook[i][j][4]
if(group==None):
group = 'Elective'
else:
course_id = int(group/5)
b26 = ''
d = int(1)
while(d<course_id):
d = int(d*26)
if(d>=26):d = int(d/26)
else: pass
while(d>=1):
b26 = b26+chr(int(course_id/d) + ord('A'))
course_id = course_id % d
d = d/26
group = str(group+1)+'-Year required subject\nfor course '+b26
sche = sbjBook[i][j][5:]
if(sche in scheRecord[period]):
class_id = scheRecord[period].index(sche)
class_idBK = scheRecord[period].index(sche)
sameSche[period][class_id][0] += 1
else:
scheRecord[period].append(sche)
sameSche[period].append([0])
class_id = scheRecord[period].index(sche)
class_idBK = scheRecord[period].index(sche)
schedule = ""
for k in sche:
if(schedule==""):pass
else: schedule = schedule + "\n"
weekday = int((k+1)/2) + (k+1)%2
if(weekday==1): weekday = 'Monday '
elif(weekday==2): weekday = 'Tuesday '
elif(weekday==3): weekday = 'Wednesday '
elif(weekday==4): weekday = 'Thursday '
else: weekday = 'Friday '
if(k%2==0 and period==0): hour = "from 8:00 am to 10:00 am"
elif(k%2==0 and period==1): hour = "from 2:00 pm to 4:00 pm"
elif(k%2==0 and period==2): hour = "from 7:00 pm to 9:00 pm"
elif(k%2==1 and period==0): hour = "from 10:00 am to 12:00 pm"
elif(k%2==1 and period==1): hour = "from 4:00 pm to 6:00 pm"
elif(k%2==1 and period==2): hour = "from 9:00 pm to 11:00 pm"
try: schedule = schedule + weekday + hour
except: print(k,period); raise
b26 = ''
div = int(1)
while(div<class_id):
div = int(div*26)
if(div>=26):div = int(div/26)
else: pass
while(div>=1):
#.........这里部分代码省略.........
示例15: CanvasRenderer
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_rectangle [as 别名]
class CanvasRenderer(AbstractRenderer):
"""
The CanvasRenderer can draw figures and grids on a canvas
"""
def __init__(self, window):
"""
Constructor
:param window: Reference to the main window instance
"""
super().__init__(window)
self.canvas = Canvas(self.window)
self.canvas.grid(row=0, column=0, padx=BOARD_CELL_SIZE, ipadx=10, ipady=10, sticky='nsew')
self.path_sprites = set()
def render_board(self, math_coords=False):
"""
Renders the data
"""
debug('CanvasRenderer.render_board() called')
if not self.board:
messagebox.showerror(
'No Board',
'No board has been selected, cannot render'
)
self.clear()
payload = self.board.grid
row_range = range(0, self.board_height)
# If we are drawing using mathematical coordinates (Y-axis reversed)
if math_coords:
row_range = range(self.board_height - 1, -1, -1)
# Iterate through all nodes, create sprite coords and determine fill color
for y in row_range:
for x in range(len(payload[y])):
draw_y = y
if math_coords:
draw_y = self.board_height - y
coords = (
x * BOARD_CELL_SIZE + 1,
draw_y * BOARD_CELL_SIZE + 1,
x * BOARD_CELL_SIZE + BOARD_CELL_SIZE + 1,
draw_y * BOARD_CELL_SIZE + BOARD_CELL_SIZE + 1,
)
node = self.board.get_node(x, y)
fill_color = '#FFFFFF'
if not node.walkable:
fill_color = '#000000'
elif node.is_start:
fill_color = '#4040FF'
elif node.is_goal:
fill_color = '#40FF40'
self.canvas.create_rectangle(
*coords,
fill=fill_color
)
def render_path(self, path, math_coords=False, **kwargs):
"""
Renders path nodes on top of the map, after clearing previously rendered path nodes
:param path: A list of Node objects
"""
open_set = kwargs['open_set_size']
closed_set = kwargs['closed_set_size']
# Remove all previously rendered path sprites from canvas
for sprite in self.path_sprites:
self.canvas.delete(sprite)
self.path_sprites.clear()
if 'nonogram' in kwargs and kwargs['nonogram'] is not None:
p = path[0].state
for y in range(kwargs['nonogram'].total_rows):
if len(p.nodes[y]) != 1:
continue
for x in range(len(p.nodes[y][0][1])):
coords = (
x * BOARD_CELL_SIZE + 1,
y * BOARD_CELL_SIZE + 1,
x * BOARD_CELL_SIZE + BOARD_CELL_SIZE + 1,
y * BOARD_CELL_SIZE + BOARD_CELL_SIZE + 1
)
fill_color = '#FFFFFF'
if p.nodes[y][0][1][x]:
fill_color = '#22EE22'
#.........这里部分代码省略.........