当前位置: 首页>>代码示例>>Python>>正文


Python Canvas.create_text方法代码示例

本文整理汇总了Python中tkinter.Canvas.create_text方法的典型用法代码示例。如果您正苦于以下问题:Python Canvas.create_text方法的具体用法?Python Canvas.create_text怎么用?Python Canvas.create_text使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在tkinter.Canvas的用法示例。


在下文中一共展示了Canvas.create_text方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: clear_can

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_text [as 别名]
def clear_can():
    """
    캔버스를 초기화 하는 버튼명령
    """
    global can, tx_counter, count
    can.destroy()
    can = Canvas(frame_left, width=400, height=400, bg="#FFFFFF")
    tx_counter = can.create_text(20, 10, text="0")
    can.pack()
    count = 0
开发者ID:soma0sd,项目名称:python-study,代码行数:12,代码来源:03_button.py

示例2: ListDialog

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_text [as 别名]
class ListDialog(object):
    def __init__ (self, master, items, message, accept_func):
        self.accept_func = accept_func

        self.top = Toplevel(master)
        self.top.transient(master)
        self.top.rowconfigure(0, weight=1)
        self.top.rowconfigure(1, weight=3)
        self.top.rowconfigure(2, weight=0)
        self.top.columnconfigure(0, weight=1)
        self.top.columnconfigure(1, weight=1)
        self.top.resizable(width=True, height=True)

        self.frame = Frame(self.top)
        self.frame.rowconfigure(0, weight=1)
        self.frame.rowconfigure(1, weight=0)
        self.frame.columnconfigure(0, weight=1)
        self.frame.columnconfigure(1, weight=0)
        self.frame.grid(row=0, column=0, sticky=(N, S, W, E), columnspan=2)
        self.canvas = Canvas(self.frame)
        self.canvas.create_text(0, 0, text=message, anchor=NW)
        self.canvas.grid(row=0, column=0, sticky=(N, W, S, E))

        self.vscroll = Scrollbar(self.frame, command=self.canvas.yview)
        self.vscroll.grid(row=0, column=1, sticky=(N, S))
        self.canvas['yscrollcommand'] = self.vscroll.set

        self.hscroll = Scrollbar(self.frame, command=self.canvas.xview, orient=HORIZONTAL)
        self.hscroll.grid(row=1, column=0, sticky=(W, E), columnspan=2)
        self.canvas['xscrollcommand'] = self.hscroll.set

        self.canvas['scrollregion'] = self.canvas.bbox('all')
        self.canvas.bind('<Button-4>', self.scroll)
        self.canvas.bind('<Button-5>', self.scroll)
        self.canvas.bind('<MouseWheel>', self.scroll)

        self.view = NameView(self.top, sorted(items))
        self.view.widget.grid(row=1, column=0, columnspan=2, sticky=(N, W, E, S))

        self.delbutton = Button(self.top, text='Ok', command=self.accept )
        self.cancelbutton = Button(self.top, text='Cancel', command=self.cancel)
        self.delbutton.grid(row=2, column=0)
        self.cancelbutton.grid(row=2, column=1)
        self.view.widget.focus_set()

    def accept(self):
        self.accept_func(self.view.selection())
        self.top.destroy()

    def cancel(self):
        self.result = None
        self.top.destroy()

    def scroll(self, event):
        if event.num == 4 or event.delta > 0:
            self.canvas.yview(SCROLL, -1, UNITS)
        elif event.num == 5 or event.delta < 0:
            self.canvas.yview(SCROLL, 1, UNITS)
开发者ID:gokai,项目名称:tim,代码行数:60,代码来源:dialog.py

示例3: show_mol

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_text [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()
开发者ID:sctincman,项目名称:oasa,代码行数:51,代码来源:coords_generator.py

示例4: draw_automata

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_text [as 别名]
def draw_automata(turing_machine=None):

    w = len(turing_machine.states)
    h = len(turing_machine.rules)

    root = Tk()
    frame = Frame(root, width=800, height=600)
    frame.grid(row=0, column=0)
    canvas = Canvas(frame, bg='#FFFFFF', width=800, height=600,
                    scrollregion=(0, -h * 15, w * 100, h * 15*3))
    hbar = Scrollbar(frame, orient=HORIZONTAL)
    hbar.pack(side=BOTTOM, fill=X)
    hbar.config(command=canvas.xview)
    vbar = Scrollbar(frame, orient=VERTICAL)
    vbar.pack(side=RIGHT, fill=Y)
    vbar.config(command=canvas.yview)
    canvas.config(width=800, height=600)
    canvas.config(xscrollcommand=hbar.set, yscrollcommand=vbar.set)
    canvas.pack(side=LEFT, expand=True, fill=BOTH)

    for position, state in enumerate(turing_machine.states):
        state_position[state] = position
        loop_occurrences[position] = 0
        canvas_id = canvas.create_text(10 + 80 * position, 400, anchor="nw")
        canvas.itemconfig(canvas_id, text="state-")
        canvas.insert(canvas_id, 12, "%d" % state)

    counter = 1
    for rule in turing_machine.rules:
        counter = draw_arrow(state_position[rule.current_state],
                             state_position[rule.next_state],
                             canvas, counter, rule)

    root.mainloop()
开发者ID:ytsvetkov,项目名称:TuringMachine,代码行数:36,代码来源:automata_graph.py

示例5: demo2

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_text [as 别名]
def demo2():
    try:
        if sys.version_info[0] == 3:
            from tkinter import Tk, Canvas
        else:
            from Tkinter import Tk, Canvas
    except ImportError:
        Tk = Canvas = None      

    if Tk: 
        from pykbool import connect
        import json, gzip
        
        with gzip.open(os.path.join('data','poly.json.gz'), 'r') as f:
            contour, holes = json.loads(f.readline().decode())
        
        try:
            connected = connect([contour]+holes)

            root1 = Tk()
            root1.title(string='not connected - contour (%d points) + holes (%d points)'%(len(contour), sum(map(len, holes))))
            canvas1 = Canvas(root1, width=810, height=510, background='white')
            canvas1.pack()
            canvas1.create_polygon(contour, outline='blue', fill='')
            for hole in holes:
                canvas1.create_polygon(hole, outline='red', fill='')

            root2 = Tk()
            root2.title(string='connected - keyhole polygon (%d points)' %(len(connected)))
            canvas2 = Canvas(root2, width=810, height=510, background='white',)
            canvas2.pack()

            canvas2.create_polygon(connected, outline='black', fill='#98BAD3', dash=(4,))

            canvas2.create_text(connected[0], text='P1', fill='red')
            canvas2.create_text(connected[int(len(connected)*0.5)], text='Pi', fill='red')
            canvas2.create_text(connected[int(len(connected)*2/3)], text='Pj', fill='red')

            root1.mainloop()
        except:
            traceback.print_exc()
开发者ID:decitre,项目名称:pykbool,代码行数:43,代码来源:setup.py

示例6: mainLoop

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_text [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()
开发者ID:MathiasGarnier,项目名称:Python-Test,代码行数:18,代码来源:Vector.py

示例7: Canvas

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_text [as 别名]
    global dn
    global times
    global correct
    global direcs
    global totalresp
    global top
    global curd
    correct = []
    times = []
    direcs = []
    totalresp = 0
    top = tkinter.Tk()
    
    gameboard = Canvas(top, bg = "black", width = 1000, height = 750)
    downI = PhotoImage(file = "Down.PNG")
    upI = PhotoImage(file = "Up.PNG")
    leftI = PhotoImage(file = "Left.PNG")
    rightI = PhotoImage(file = "Right.PNG")
    
    cur = 1
    curd = 1
    dn = 0
    
    arrow = gameboard.create_image(650, 200, anchor= "ne", image = downI)
    tdisp = gameboard.create_text(0, 0, anchor = "ne", text = '', fill = 'red') 
    
    gameboard.pack()
    gameboard.bind_all('<KeyRelease>', kp) 
    start = time.time()
    top.mainloop()
开发者ID:conNULL,项目名称:Arrow_Response_Test,代码行数:32,代码来源:statsgame.py

示例8: SudokuUI

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_text [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"
                )
开发者ID:stevegleds,项目名称:my-project-ideas,代码行数:96,代码来源:tkintertesting.py

示例9: Tk

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_text [as 别名]
@ License: MIT
"""
from tkinter import Tk, Canvas, Frame, Button
from numpy import random

master = Tk()

frame_left = Frame(master, width=400, height=400, bg="#FFFFFF")
frame_right = Frame(master, width=100, height=400, bg="#676767")
frame_left.pack(side='left')
frame_right.pack(side='top')


count = 0  # 캔버스에 그려진 오브젝트의 숫자를 세는 변수
can = Canvas(frame_left, width=400, height=400, bg="#FFFFFF")
tx_counter = can.create_text(20, 10, text="0")  # 오브젝트의 갯수 표시
can.pack()


def add_obj():
    """
    랜덤한 x, y지점에 크기가 [5, 5]인 원을 그리는 버튼명령
    """
    global count, can, tx_counter
    count += 1
    can.delete(tx_counter)
    tx_counter = can.create_text(20, 10, text=str(count))
    x, y = (random.randint(395), random.randint(395))
    can.create_oval(x, y, x+5, y+5, fill="#000")

开发者ID:soma0sd,项目名称:python-study,代码行数:31,代码来源:03_button.py

示例10: QuickHull

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_text [as 别名]
class QuickHull(Tk):
	def __init__(self,points):
		Tk.__init__(self)
		board = Frame(self)
		self.title("Diagram") 

		width = 800 #setting height and width
		height = 600

		windowx = self.winfo_screenwidth()
		windowy = self.winfo_screenheight()
		x = (windowx - width)/2		#getting center
		y = (windowy - height)/2

		self.geometry("%dx%d+%d+%d" % (width,height,x,y)) #creates window of size _width by _height, and positions it at the center of the screen

		board.pack(fill=BOTH, expand=1)
	
		self.canvas = Canvas(board,height=600,width=800,background="white")
		self.canvas.place(x=0,y=0)
		
		self.drawPoints(points) #Draw points and the first line from the highest an lowest points
		

					

		
		def point(event):  #Add points by clicking on the screen
			self.canvas.create_text(event.x, event.y,text = "+")
			points.append([event.x,event.y])

		def start():
			if(points != []):
				startB.destroy()
				quickHullStart(points)
				self.nextButton()
	
		self.canvas.bind("<Button-1>", point)
		
		startB = Button(self, text = "Start QuickHull", command = start)
		startB.pack()
	
		
	
		self.mainloop()
	
				
	def nextButton(self):					#Button that steps forward one step in the QuickHull
		def callBack():
			self.animate()

		continueB = Button(self, text="-->",command=callBack)
		continueB.place(x=350,y=550)


	def animate(self):						#animation loop
		if(triList == []):
			self.onExit()
			return
		self.canvas.create_polygon(triList.pop(0),fill="red",outline="black")
			





	def onExit(self):  #Window popup signaling that the Quick Hull is complete
		alert = Tk()
		finish = Window(alert)
		finish.config(title="Complete",w = 200, h=50)
		finish.positionWindow()

		done = Label(alert,text="QuickHull Complete")
		done.pack()

		ok = Button(alert,text="OK",command=alert.destroy)
		ok.pack()
		alert.mainloop()
		return
		


	def drawPoints(self,points):			#Draw points Imported from a file
		for p in points:
			self.canvas.create_text(p[0],p[1],text="+")
开发者ID:liangtianumich,项目名称:QuickHull,代码行数:87,代码来源:QuickHull.py

示例11: View

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_text [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()
开发者ID:magetron,项目名称:ENGF0002,代码行数:102,代码来源:te_view.py

示例12: Schedules

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_text [as 别名]
def Schedules(profBook, profBook0):

	from tkinter import Tk
	from tkinter import Canvas
	import os

	mod = 1
	try: profBook[-1]
	except: mod = 0
	for professor in (range(len(profBook)-mod)):
		master = Tk()

		w=1240
		h=1754
		x=86
		y=86

		c = Canvas(master, width=1240, height=1754)
		c.pack()
	
		# Initial solution
	
		c.create_text(w/2, y, font=("Ubuntu","16", "bold"), text="Professor "+str(professor)+" schedule in initial solution")

		c.create_rectangle(x, y+30, x+124, y+48, fill="#fff", tags=("00n","init")) # Blank rectangle

		c.create_rectangle(x, y+48, x+124, y+120, fill="#fff", tags=("01n","init"))     # 
		xp = (c.coords("01n")[0]+c.coords("01n")[2])/2                                   # 8:00 am 
		yp = (c.coords("01n")[1]+c.coords("01n")[3])/2                                   # rectangle
		c.create_text(xp, yp, font=("Arial","12"), text="8:00 am - 10:00 am")          # 

		c.create_rectangle(x, y+120, x+124, y+192, fill="#fff", tags=("02n","init"))    # 
		xp = (c.coords("02n")[0]+c.coords("02n")[2])/2                                   # 10:00 am 
		yp = (c.coords("02n")[1]+c.coords("02n")[3])/2                                   # rectangle
		c.create_text(xp, yp, font=("Arial","12"), text="10:00 am - 12:00 pm")         # 

		c.create_rectangle(x, y+192, x+124, y+228, fill="#fff", tags=("03n","init"))    # 
		xp = (c.coords("03n")[0]+c.coords("03n")[2])/2                                   # 12:00 pm 
		yp = (c.coords("03n")[1]+c.coords("03n")[3])/2                                   # rectangle
		c.create_text(xp, yp, font=("Arial","12"), text="12:00 pm - 2:00 pm")          #

		c.create_rectangle(x, y+228, x+124, y+300, fill="#fff", tags=("04n","init"))    # 
		xp = (c.coords("04n")[0]+c.coords("04n")[2])/2                                   # 2:00 pm 
		yp = (c.coords("04n")[1]+c.coords("04n")[3])/2                                   # rectangle
		c.create_text(xp, yp, font=("Arial","12"), text="2:00 pm - 4:00 pm")           #

		c.create_rectangle(x, y+300, x+124, y+372, fill="#fff", tags=("05n","init"))    # 
		xp = (c.coords("05n")[0]+c.coords("05n")[2])/2                                   # 4:00 pm 
		yp = (c.coords("05n")[1]+c.coords("05n")[3])/2                                   # rectangle
		c.create_text(xp, yp, font=("Arial","12"), text="4:00 pm - 6:00 pm")           #

		c.create_rectangle(x, y+372, x+124, y+408, fill="#fff", tags=("06n","init"))    # 
		xp = (c.coords("06n")[0]+c.coords("06n")[2])/2                                   # 6:00 pm 
		yp = (c.coords("06n")[1]+c.coords("06n")[3])/2                                   # rectangle
		c.create_text(xp, yp, font=("Arial","12"), text="6:00 pm - 7:00 pm")           #

		c.create_rectangle(x, y+408, x+124, y+480, fill="#fff", tags=("07n","init"))    # 
		xp = (c.coords("07n")[0]+c.coords("07n")[2])/2                                   # 7:00 pm 
		yp = (c.coords("07n")[1]+c.coords("07n")[3])/2                                   # rectangle
		c.create_text(xp, yp, font=("Arial","12"), text="7:00 pm - 9:00 pm")           #

		c.create_rectangle(x, y+480, x+124, y+552, fill="#fff", tags=("08n","init"))    # 
		xp = (c.coords("08n")[0]+c.coords("08n")[2])/2                                   # 9:00 pm 
		yp = (c.coords("08n")[1]+c.coords("08n")[3])/2                                   # rectangle
		c.create_text(xp, yp, font=("Arial","12"), text="9:00 pm - 11:00 pm")          #

		week = ['Monday','Tuesday','Wednesday', 'Thursday', 'Friday']
		for i in range(5):
			c.create_rectangle(x+124+i*186, y+30, x+310+i*186, y+48, fill="#fff")
			c.create_rectangle(x+124+i*186, y+48, x+310+i*186, y+120, fill="#fff", tags=("00,0"+str(2*i),"init"))
			c.create_rectangle(x+124+i*186, y+120, x+310+i*186, y+192, fill="#fff", tags=("00,0"+str(2*i+1),"init"))
			c.create_rectangle(x+124+i*186, y+192, x+310+i*186, y+228, fill="#fff")
			c.create_rectangle(x+124+i*186, y+228, x+310+i*186, y+300, fill="#fff", tags=("01,0"+str(2*i),"init"))
			c.create_rectangle(x+124+i*186, y+300, x+310+i*186, y+372, fill="#fff", tags=("01,0"+str(2*i+1),"init"))
			c.create_rectangle(x+124+i*186, y+372, x+310+i*186, y+408, fill="#fff")
			c.create_rectangle(x+124+i*186, y+408, x+310+i*186, y+480, fill="#fff", tags=("02,0"+str(2*i),"init"))
			c.create_rectangle(x+124+i*186, y+480, x+310+i*186, y+552, fill="#fff", tags=("02,0"+str(2*i+1),"init"))
			c.create_text(x+217+i*186, y+39, font=("Arial","12"), text=week[i])

		halfSlots = []
		for i in range(len(profBook0[professor])):
			for j in range(5,len(profBook0[professor][i])):
			
				sbj = profBook0[professor][i][0]
				slot = profBook0[professor][i][j]
			
				if(j+1==len(profBook0[professor][i]) and profBook0[professor][i][2]%2==1):
				
					coord = c.coords("0"+str(profBook0[professor][i][1])+",0"+str(slot))
					coord = [int(i) for i in coord]
					if("0"+str(profBook0[professor][i][1])+",0"+str(slot) in halfSlots):
						c.create_rectangle((coord[0]+coord[2])/2, coord[1], coord[2], coord[3], fill="#ccc")
						c.create_text((coord[0]+3*coord[2])/4,(coord[1]+coord[3])/2, font=("Ubuntu","15"), justify='center', text="Subject "+str(sbj))
					else:
						c.create_rectangle(coord[0], coord[1], (coord[0]+coord[2])/2, coord[3], fill="#ccc")
						halfSlots.append("0"+str(profBook0[professor][i][1])+",0"+str(slot))
						c.create_text((3*coord[0]+coord[2])/4,(coord[1]+coord[3])/2, font=("Ubuntu","15"), justify='center', text="Subject "+str(sbj))
				else:
			
					coord = c.coords("0"+str(profBook0[professor][i][1])+",0"+str(slot))
#.........这里部分代码省略.........
开发者ID:allrod5,项目名称:optimization-algorithms,代码行数:103,代码来源:report.py

示例13: prgCanvas

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_text [as 别名]
class prgCanvas(Frame):
    def __init__(self,window=None,height=500,width=500,bg="grey"):
        Frame.__init__(self,window,height=height,width=width,bg=bg)
        self.canvas = Canvas(self, bg=bg, height=height, width=width)
        self.flagDescription = False
        self.setdefault(mashtab=True,reper=True,normalization=True)
        self.canvas.pack(expand='y',fill="both")
        self.field = None #данные, блоки групп, графические примитивы, точки, #графические примитивы, надписи
        self.fileprogram = None #имя файла для загрузки

        self.filter = None #фильтр, по которому определяется выделенный фрагмент

    def setdefault(self,mashtab=False,reper=False,normalization=False):
        if mashtab:
            self.mashtab = 1.00 #масштаб
        if reper:
            self.reper = [10.00,10.00] #смещение
        if normalization:
            self.normalization = [0.00,0.00] #коэффициент для нормализации координат
        
    def configure(self,file=None,filter= None):
        if file!=None:
            self.fileprogram = file
        self.filter=filter

    def setMashtab(self):
        '''Эта функция устанавливает текущий масштаб, так чтобы вся плата была в зоне видимости'''
        def findcoord(field):
            mX,mY = field[0][0],field[0][1]
            # sX,sY = field[0][0],field[0][1]
            sX,sY = 0, 0
            for c in field:
                if c[0]<sX: sX = c[0]
                elif c[0]>mX: mX = c[0]
                if c[1]<sY: sY = c[1]
                elif c[1]>mY: mY = c[1]
            return [sX,sY,mX,mY]
        sX,sY,mX,mY=findcoord(self.field)
        lX = int(self.canvas["width"])
        lY = int(self.canvas["height"])
        lengthX = abs(mX-sX)
        lengthY = abs(mY-sY)
        if lengthX>0 and lengthY>0:
            cX = lX/lengthX
            cY = lY/lengthY
        else:
            cX,cY=1.0,1.0
        print("MSH",cX,cY)
        
        self.normalization = [abs(sX),abs(sY)]
        self.mashtab = int(min(cX,cY)*0.9)
    
    def transform(self,x,y,a,etalon):
        """
        точка отсчета - в центре эталона
        """
        new = list()
        for item in etalon:
            ca = cos(a)
            sa = sin(a)
            x2,y2 = item[0]-x, item[1]-y
            
            new.append([x2*ca + y2*sa+x, x2*sa - y2*ca+y])
        return new
        
    def genfield(self):
        x,y,d=0,1,2
        
        self.canvas.delete("all")

        for c in self.field:
            cx = (c[x]+self.normalization[x])*self.mashtab+self.reper[x]
            cy = (c[y]+self.normalization[y])*self.mashtab+self.reper[y]

            print("filter",self.filter)
            
            if self.flagDescription and self.filter==None:
                tag = "BLACK"
                _color1,_color2 = "black","black"
                font = "Verdana 8"
                self.canvas.create_text(cx,cy,anchor="nw",text=str(c[d][1]), fill=_color1,font=font,tag=("DESC",tag))
            elif (not self.flagDescription) and self.filter==None:
                tag = "BLACK"
                _color1,_color2 = "black","black"
            elif self.flagDescription and self.filter!=None and self.filter(c[d][2]):
                _color1,_color2 = ["red","red"]
                tag = "RED"
                font = "Verdana 10 bold"
                self.canvas.create_text(cx,cy,anchor="nw",text=str(c[d][1]), fill=_color1,font=font,tag=("DESC",tag))
            elif self.flagDescription:
                _color1,_color2 = "black","black"
                tag = "BLACK"
                # font = "Verdana 8"
                # self.canvas.create_text(cx,cy,anchor="nw",text=str(c[d][1]), fill=_color1,font=font,tag=("DESC",tag))
                pass
                
            # здесь может быть выбор фигуры
            # здесь может быть угол поворота
            print("c",c)
            if c[-2][0]=="25":
#.........这里部分代码省略.........
开发者ID:sergnov,项目名称:PrgViewer,代码行数:103,代码来源:prgviewer.py

示例14: demo1

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_text [as 别名]
def demo1():
    try:
        
        if sys.version_info[0] == 3:
            from tkinter import Tk, Canvas, PhotoImage, NW, SW
        else:
            from Tkinter import Tk, Canvas, PhotoImage, NW, SW
    except ImportError:
        Tk = Canvas = None      

    if Tk: 
        from pykbool import connect
        
        contour = [(491.1025968497233, 19.886736214605065), (491.1025968497233, 5.524093392945851), (455.34269902086, 5.524093392945851), (455.34269902086, 19.886736214605065), (353.68241805023416, 17.677098857426728), (353.68241805023416, 8.838549428713364), (323.20136228182207, 8.838549428713364), (323.20136228182207, 17.677098857426728), (210.81311196253725, 14.362642821659207), (210.81311196253725, 3.3144560357675132), (175.05321413367392, 3.3144560357675132), (175.05321413367392, 14.362642821659207), (73.22264793529162, 14.362642821659207), (73.22264793529162, 10.0), (34.05704555129843, 10.0), (32.18390804597701, 110.48186785891704), (10.0, 110.48186785891704), (10.0, 162.40834575260803), (48.36100468284376, 156.88425235966218), (75.09578544061303, 156.88425235966218), (128.56534695615156, 162.40834575260803), (178.62920391656024, 176.77098857426725), (226.81992337164752, 196.65772478887232), (249.9787143465304, 211.02036761053148), (291.18773946360153, 246.374565325385), (328.65048957002983, 283.9384003974168), (337.5053214133674, 298.30104321907595), (337.5053214133674, 341.3889716840536), (448.1907194550873, 350.22752111276696), (448.1907194550873, 333.6552409339294), (685.7386121753938, 350.22752111276696), (683.8654746700724, 356.856433184302), (771.3920817369094, 364.5901639344262), (774.9680715197957, 318.18777943368104), (767.816091954023, 318.18777943368104), (789.272030651341, 60.765027322404364), (796.4240102171137, 60.765027322404364), (800.0, 8.838549428713364), (757.088122605364, 8.838549428713364), (757.088122605364, 23.20119225037257), (644.6998722860792, 19.886736214605065), (644.6998722860792, 8.838549428713364), (610.8131119625373, 5.524093392945851), (608.9399744572158, 19.886736214605065)]
        holea = [(162.62239250744997, 127.0541480377546), (189.35717326521925, 135.89269746646795), (239.42103022562793, 159.09388971684052), (287.6117496807152, 187.81917536015894), (308.8974031502767, 205.49627421758566), (348.2332907620264, 246.374565325385), (366.1132396764581, 266.26130153999003), (389.272030651341, 301.6154992548435), (450.0638569604087, 307.13959264778936), (451.7667092379736, 57.45057128663686), (355.38527032779905, 55.24093392945852), (355.38527032779905, 66.28912071535022), (323.20136228182207, 66.28912071535022), (323.20136228182207, 55.24093392945852), (210.81311196253725, 55.24093392945852), (210.81311196253725, 60.765027322404364), (173.35036185610898, 60.765027322404364), (173.35036185610898, 55.24093392945852), (73.22264793529162, 51.926477893691), (71.51979565772669, 116.00596125186286), (107.27969348659005, 119.32041728763039)]
        holeb = [(749.9361430395913, 60.765027322404364), (498.254576415496, 57.45057128663686), (494.67858663260967, 294.9865871833085), (566.0280970625798, 301.6154992548435), (566.0280970625798, 292.77694982613014), (591.0600255427842, 292.77694982613014), (589.3571732652192, 303.8251366120218), (730.3533418475947, 315.9781420765027)]
          
        connected_polygon = connect([contour, holea, holeb])

        root = Tk()
        root.title(string='connect holes to contour / fill resulting polygon')
        canvas1 = Canvas(root, width=900, height=415, background='white')
        canvas1.pack()

        canvas1.create_polygon(contour, outline='blue', fill='')
        canvas1.create_text(contour[0], text='C(1)')
        canvas1.create_text(contour[20], text='C(i)')
        canvas1.create_text(contour[-1], text='C(n)')

        canvas1.create_polygon(holea, outline='red', fill='')
        canvas1.create_text(holea[0], text='H1(1)')
        canvas1.create_text(holea[9], text='H1(i)')
        canvas1.create_text(holea[-1], text='H1(n)')

        canvas1.create_polygon(holeb, outline='green', fill='')
        canvas1.create_text(holeb[0], text='H2(1)')
        canvas1.create_text(holeb[2], text='H2(i)')
        canvas1.create_text(holeb[-1], text='H2(n)')
        
        canvas1.create_text((10, 350), text='# More info in setup.py\n'
            'from pykbool import connect\n'
            'contour=[(... , ...) ... ]; hole1=[(... , ...) ... ]; hole2=...\n'
            'polygon=connect([contour, hole1, hole2, ...])', anchor=SW)
        
        canvas2 = Canvas(root, width=900, height=415, background='white')
        canvas2.pack()
        image=PhotoImage(file=os.path.join('data','demo.gif'))
        canvas2.create_image((0,0), image=image, anchor=NW)
        canvas2.image=image
        canvas2.create_polygon(connected_polygon, outline='black', fill='grey')
        canvas2.create_text(connected_polygon[0], text='P1')
        canvas2.create_text(connected_polygon[62], text='Pi')
        canvas2.create_text(connected_polygon[-1], text='Pn')

        root.mainloop()
开发者ID:decitre,项目名称:pykbool,代码行数:57,代码来源:setup.py

示例15: GraphView

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_text [as 别名]

#.........这里部分代码省略.........
			for d in self._data:
				d.append()
			if self._data[pos].size() > 1:
				self._write_prev_records()
		self._data[pos].put_value(value)

		graph_w = self._win_size[0] - self._graph_x;
		count = int(graph_w / GraphView.POINT_MARGIN + 1)

		for d in self._data:
			d.shrink(count)

	def _write_prev_records(self):
		write = ','.join((str(d.get_value(-2)) for d in self._data)) + '\n'
		self._file.write(write)
		self._file.flush()

	def _refresh(self):
		self._redraw_graph()
		self._tk.after(16, self._refresh)

	def _full_redraw(self):
		self._canvas.delete("all")
		bounding_box = self._redraw_data_labels()
		self._graph_rect = 0, 0, self._win_size[0], bounding_box[1]
		self._redraw_y_labels()
		for v in self._data_view:
			v.clear_lines();
		self._redraw_graph()

	def _redraw_data_labels(self):
		top = self._win_size[1]
		x = GraphView._DATA_LABEL_PADDING
		for l, c in zip(self._labels, self._colors):
			t = self._canvas.create_text(x,
					self._win_size[1] - GraphView._DATA_LABEL_PADDING,
					anchor = tkinter.SW, fill = c, font = config.FONT,
					text = '-' + l)
			bounding_box = self._canvas.bbox(t)
			top = min(top, bounding_box[1])
			x = bounding_box[2] + GraphView._DATA_LABEL_PADDING
		return 0, top, x, self._win_size[1]

	def _redraw_y_labels(self):
		height = self._graph_rect[3] - self._graph_rect[1] \
				- GraphView.WIN_PADDING_Y * 2
		count = max(int(height / 50), 2)

		labels = []
		max_label_size = 0
		longest_label = None
		longest_label_i = None
		for i in range(count):
			ratio = i / (count - 1)
			value = self._max - self._diff * ratio
			value_label = ("%.2f" % value) if value % 1 != 0 else str(value)
			labels.append(value_label)
			if len(value_label) > max_label_size:
				max_label_size = len(value_label)
				longest_label = value_label
				longest_label_i = i

		label_id = self._canvas.create_text(0, height * (longest_label_i \
						/ (count - 1)) + GraphView.WIN_PADDING_Y,
				anchor = tkinter.W, fill = config.COL_GREY_100,
				font = config.FONT, text = longest_label)
		bounding_box = self._canvas.bbox(label_id)
		width = bounding_box[2] - bounding_box[0]
		self._graph_x = width + GraphView.POINT_MARGIN

		for i in range(count):
			ratio = i / (count - 1)
			y = height * ratio + GraphView.WIN_PADDING_Y
			if i != longest_label_i:
				self._canvas.create_text(width, y, anchor = tkinter.E,
						fill = config.COL_GREY_100, font = config.FONT,
						text = labels[i])
			self._canvas.create_line(self._graph_x, y, self._graph_rect[2], y,
					fill = config.COL_GREY_700)

	def _redraw_graph(self):
		graph_h = self._graph_rect[3] - GraphView.WIN_PADDING_Y * 2
		for d, v in zip(self._data, self._data_view):
			v.populate(d.get_values(), self._max, self._diff, self._graph_x,
					graph_h)
			v.draw(self._canvas)

	def _get_auto_colors(self, size) -> list:
		product = GraphView._COLOR_REPO[:min(size, len(GraphView._COLOR_REPO))]
		while len(product) < size:
			product.append("#%06x" % random.randrange(0xFFFFFF))
		return product

	_LABEL_SIZE = 10
	_DATA_LABEL_PADDING = 8
	_MSG_SIZE = 6
	_MSG_TYPE_INT = 0
	_MSG_TYPE_FLOAT = 1
	_COLOR_REPO = ["#F44336", "#4CAF50", "#2196F3", "#FFEB3B", "#607D8B",
			"#9C27B0", "#009688", "#673AB7", "#795548"]
开发者ID:hkust-smartcar,项目名称:sc-studio,代码行数:104,代码来源:graph_view.py


注:本文中的tkinter.Canvas.create_text方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。