def initUI(self): self.parent.title("Mario's Picross Puzzle Editor") self.puzzles = None # Build the menu menubar = Menu(self.parent) self.parent.config(menu=menubar) fileMenu = Menu(menubar) self.fileMenu = fileMenu fileMenu.add_command(label="Open Mario's Picross ROM...", command=self.onOpen) fileMenu.add_command(label="Save ROM as...", command=self.onSave, state=DISABLED) fileMenu.add_separator() fileMenu.add_command(label="Exit", command=self.onExit) menubar.add_cascade(label="File", menu=fileMenu) # Navigation Label(self.parent).grid(row=0, column=0) Label(self.parent).grid(row=0, column=4) self.parent.grid_columnconfigure(0, weight=1) self.parent.grid_columnconfigure(4, weight=1) prevButton = Button(self.parent, text="<--", command=self.onPrev, state=DISABLED ) self.prevButton = prevButton prevButton.grid(row=0, column=1) puzzle_number = 1 self.puzzle_number = puzzle_number puzzleNumber = Label(self.parent, text="Puzzle #{}".format(puzzle_number)) self.puzzleNumber = puzzleNumber puzzleNumber.grid(row=0, column=2) nextButton = Button(self.parent, text="-->", command=self.onNext, state=DISABLED ) self.nextButton = nextButton nextButton.grid(row=0, column=3) # Canvas canvas = Canvas(self.parent) self.canvas = canvas for i in range(15): for j in range(15): fillcolor = "gray80" self.canvas.create_rectangle(10+20*j, 10+20*i, 10+20*(j+1), 10+20*(i+1), fill=fillcolor, tags="{},{}".format(i, j) ) self.canvas.bind("<ButtonPress-1>", self.onClick) canvas.grid(row=1, columnspan=5, sticky=W+E+N+S) self.parent.grid_rowconfigure(1, weight=1)
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
def setUpCanvas(): from tkinter import Tk, Canvas, YES, BOTH root = Tk() root.title("A Tk/Python Graphics Program") canvas = Canvas(root, width = 1270, height = 780, bg = 'black') canvas.pack(expand = YES, fill = BOTH) return canvas, root
def main(): root = Tk(className="My graphics!") root.geometry("400x400") canvas = Canvas() canvas.pack(fill=BOTH, expand=1) # img = draw_gradient(canvas) img = draw_danger_levels(canvas, 50, 50) # что бы ограничить число # if n > 255: # n = 255 # хочу: n = 256 => 0 # n = 257 => 1 # ... # n = 300 => 44 # 10 // 3 = 3(1) # 10 - (10 // 3) * 3 # 10 % 3 # a % b < b # 10 % 3 = 1 # 11 % 3 = 2 # 12 % 3 = 0 # 13 % 3 = 1 root.mainloop()
class Main(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.info = {} self.window = None self.size = (640, 480) self.fields = [] self.init_ui() def init_ui(self): self.parent.title("Node Writer") self.style = Style() self.style.theme_use("alt") self.pack(fill="both", expand=True) menubar = Menu(self.parent) self.parent.config(menu=menubar) menubar.add_command(label="New", command=self.onNew) menubar.add_command(label="Show Info", command=self.get_info) menubar.add_command(label="Exit", command=self.quit) self.canvas = Canvas(self, background="white", width=self.size[0], height=self.size[1]) self.canvas.pack(fill="both", expand=1) self.canvas.bind("<Motion>", self.move_boxes) def move_boxes(self, event): print(event.x, event.y) """ x, y = (event.x-1, event.y-1) x1, y1, x2, y2 = self.canvas.bbox("test") if x > x1 and y > y1 and x < x2 and y < y2: print("Hit") else: print("Missed") """ def onNew(self): new = Node(self, "Node_entry") label = new.insert_entry_field("Labels") label2 = new.insert_entry_field("Labels2") text = new.insert_text_field("Text") new.ok_cancel_buttons() def get_info(self): x, y = (self.size[0]/2, self.size[1]/2) for i in self.info: label_frame= LabelFrame(self, text="name") label_frame.pack(fill="y") for entry in self.info[i]["Entry"]: frame = Frame(label_frame) frame.pack(fill="x") label = Label(label_frame, text=self.info[i]["Entry"][entry], width=6) label.pack(side="left", anchor="n", padx=5, pady=5) for text in self.info[i]["Text"]: frame = Frame(label_frame) frame.pack(fill="x") label = Label(label_frame, text=self.info[i]["Text"][text], width=6) label.pack(side="left", anchor="n", padx=5, pady=5) window = self.canvas.create_window(x, y, window=label_frame, tag="test")
def __init__(self, parent): Canvas.__init__(self, width=WIDTH, height=HEIGHT, background="black", highlightthickness=0) self.parent = parent self.initGame() self.pack()
def main(): # Basic starter code. window = tkinter.Tk() canvas = Canvas(window, width = CANVAS_SIZE, height = CANVAS_SIZE) canvas.pack() draw_shaky_line(canvas, 50, 50, 650, 650)
class TkWindowMainLoop(Thread): '''class for thread that handles Tk window creation and main loop''' def __init__(self, client): Thread.__init__(self) self.window = None self.canvas = None self.client = client self.start() def callbackDeleteWindow(self): self.client.stop() def stop(self): self.window.quit() def run(self): self.window = Tk() self.canvas = Canvas(self.window, width=1024, height=768) self.canvas.pack() self.window.protocol("WM_DELETE_WINDOW", self.callbackDeleteWindow) self.window.mainloop() def getWindow(self): return self.window def getCanvas(self): return self.canvas
def __init__(self, *args, **kwargs): Canvas.__init__(self, *args, **kwargs) self.graphs = [] self.x = Axis() self.y = Axis() self.y.direction = -1 self.bind("<Configure>", lambda ev: self.after_idle(self.__onConfigure__))
def simulation_canvas(parent, **config): """Initializes the canvas and sets it up to receive user input.""" global the_canvas the_canvas = Canvas(parent, **config) the_canvas.focus_set() # this makes tkinter canvas accept keyboard commands the_canvas.bind("<Key>", lambda event: model.move_ship(event)) return the_canvas
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")
def __init__(self, master=None, cnf=None, **kw): if not cnf: cnf = {} Canvas.__init__(self, master, cnf, **kw) self._polygons = list() self._layer = None self._image = None
def __init__(self, master, controller, *, height, width, background): self.height = height self.width = width self.controller = controller self.viewports = [] Canvas.__init__(self, master, height=height, width=width, background=background) self.SetupMenu(master) self.SetNamedView(FLAGS.gui_initial_view or self.default_initial_view)
def __init__(self, **kwargs): """ Constructor root - reference to the widget containing this widget """ Canvas.__init__(self, **kwargs) self["bg"] = DEAD_COLOUR GolCell.__init__(self)
def __init__(self, parent): """Simple Canvas class.""" Canvas.__init__(self, parent) self.parent = parent self.config(background="white", width=960, height=640) self.num = 1 self.pack() self.element_list = [] self.bindings()
def build(self): width = self.hardware.get('x') * LCD.SCREEN_SCALE height = self.hardware.get('y') * LCD.SCREEN_SCALE skin_position = self.hardware.get('skin_position') if skin_position == 'Y': width, height = height, width canvas = Canvas(self.master, width=width, height=height) canvas.pack() self.widget = canvas
def main(): root = Tk() canvas = Canvas(root, bg='white', width=720, height=900) canvas.pack() map1 = Map() map1.drawMap(canvas) root.mainloop()
def __init__(self, master=None, cnf={}, **kw): Canvas.__init__(self, master, cnf, **kw) Observable.__init__(self) self.__boxId = None self.__start_x = None self.__start_y = None self.bind('<Button-1>', self.onButton1Press) self.bind('<B1-Motion>', self.onMouseMove) self.bind('<ButtonRelease-1>', self.onButton1Release)
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)
def main(): from tkinter import Canvas, mainloop, Tk gamma, size = [0.3, 0.2, -0.1, -0.4, 0.0], 11 width, height, scale, center = 800, 800, 20, 400+400j w = Canvas(Tk(), width=width, height=height) w.pack() for rhombus, color in tiling(gamma, size): coords = to_canvas(rhombus, scale, center) w.create_polygon(*coords, fill=color, outline="black") mainloop()
def initUI(self): self.parent.title("Raspberry Pi Sensorik") self.pack(fill=BOTH, expand=1) canvas = Canvas(self) canvas.create_oval(MARGIN, MARGIN, CIRCLE_RADIUS*2, CIRCLE_RADIUS*2, outline="#fb0", fill="#fb0", width=2) #canvas.create_oval(20, 10, 20+CIRCLE_SIZE, CIRCLE_SIZE, outline="#f50", fill="#f50") #canvas.create_oval(CIRCLE_SIZE * 3, 10, CIRCLE_SIZE, CIRCLE_SIZE, outline="#05f", fill="#05f") canvas.pack(fill=BOTH, expand=1)
class Window(Frame): def __init__(self,parent): Frame.__init__(self,parent) self.parent = parent self.canvas = Canvas(self) self.parent.title("Shapes") self.pack(fill=BOTH, expand=1) def drawShape(self,shape,x,y): shape.draw(canvas=self.canvas,x=x,y=y) self.canvas.pack(fill=BOTH, expand=1)
def __init__(self, master=None, data=None, cell_size=10, color='green'): self.cell = data if data else [[False]] self._grid_width = len(self.cell) self._grid_height = len(self.cell[0]) self._width = self._grid_width * cell_size self._height = self._grid_height * cell_size Canvas.__init__(self, master, width=self._width, height=self._height) self.cell_size = cell_size self.color = color self.bind('<Button-1>', self.on_click) self.bind('<B1-Motion>', partial(self.on_click, motion=True)) self.draw()
def __init__(self, tk, clock): self.width = 600 self.height = 400 self.clock = clock # create canvas w = Canvas(tk, width=self.width, height=self.height) w.pack() self.canvas = w # cache self.cache = {}
def initDrawing(titre,x,y,largeur,hauteur): global root,application,canvas,btnQuitter root = Tk() application = Frame(root) application.pack() application.master.title(titre) canvas = Canvas(application, width=largeur, height=hauteur) canvas.pack(side=TOP) btnQuitter = Button(application, text="Quitter", command=application.quit) btnQuitter.pack(side=RIGHT)
def main(): root = Tk() root.title = 'BitCoin graph' root.geometry("{}x{}".format(WIDTH, HEIGHT)) canvas = Canvas(root) canvas.pack(fill=BOTH, expand=1) try: draw_from_script('shapes.txt', canvas) except IOError: draw_custom(canvas) root.mainloop()
def __init__(self, image, COLORFLAG = False): self.img = PhotoImage(width = WIDTH, height = HEIGHT) for row in range(HEIGHT): for col in range(WIDTH): num = image[row*WIDTH + col] if COLORFLAG == True: kolor = '#%02x%02x%02x' % (num[0], num[1], num[2]) else: kolor = '#%02x%02x%02x' % (num, num, num) self.img.put(kolor, (col, row)) c = Canvas(root, width = WIDTH, height = HEIGHT); c.pack() c.create_image(0, 0, image = self.img, anchor = NW) printElapsedTime('displayed image')
def creeInterface(a_largeur=LARGEUR_FEN, a_hauteur=HAUTEUR_FEN): global Wroot, Wcanvas, Wlargeur, Whauteur, ValLargeur, ValHauteur, EntreeX, EntreeY, SortieX, SortieY, NewLargeur, NewHauteur global CoulEntreeLbl, CoulEntreeBtn, CoulSortieLbl, CoulSortieBtn, Main, Orient, Replay, DemarrerBtn # Fenêtre principale Wroot = Tk() # Titre de la fenêtre Wroot.title(TITRE + VERSION) # Initialisation de la largeur et hauteur du graphique (et de la sauvegarde utilisée pour resize) NewLargeur = Wlargeur = a_largeur NewHauteur = Whauteur = a_hauteur # Définition de la taille de la fenêtre principale Wroot.geometry( str(a_largeur) + "x" + str(a_hauteur + HAUTEUR_MENU) + "-10+10") # Fonction appelée pour le changement de taille de la fenêtre Wroot.bind('<Configure>', resizeWindow) # Fonction appelée pour le lacher du bouton souris (indique la fin du resize) Wroot.bind('<ButtonRelease>', leaveWindow) # Frame des données dataFrame = Frame(Wroot) # Partie 'Labyrinthe' labyFrame = LabelFrame(dataFrame, text='Labyrinthe') # Première ligne : largeur du labyrinthe Label(labyFrame, text='Largeur').grid(row=0, column=0) ValLargeur = StringVar(Wroot) ValLargeur.set(LARGEUR_DEF) Entry(labyFrame, textvariable=ValLargeur, width=2).grid(row=0, column=1) # Deuxième ligne : hauteur du labyrinthe Label(labyFrame, text='Hauteur').grid(row=1, column=0) ValHauteur = StringVar(Wroot) ValHauteur.set(HAUTEUR_DEF) Entry(labyFrame, textvariable=ValHauteur, width=2).grid(row=1, column=1) # Troisième ligne : bouton 'Créer' Button(labyFrame, text='Créer', command=creerLabyCmd).grid(row=2, column=0, columnspan=1) taille = Scale(labyFrame, from_=CELLULE_MIN, to=CELLULE_MAX, showvalue=False, orient='h', label='Taille hexa', command=largeurCmd) taille.set(CELLULE_INI) taille.grid(row=2, column=1) # Fin de la partie labyFrame labyFrame.grid(row=0, column=0, sticky=tkinter.N + tkinter.S) # Partie 'Entrée' entreeFrame = LabelFrame(dataFrame, text='Entrée') # Abscisse Label(entreeFrame, text="X").grid(row=0, column=0) EntreeX = Scale(entreeFrame, to=LARGEUR_DEF - 1, showvalue=False, orient='h', command=xEntreeCmd) EntreeX.grid(row=0, column=1) # Ordonnée Label(entreeFrame, text="Y").grid(row=1, column=0) EntreeY = Scale(entreeFrame, to=HAUTEUR_DEF - 1, showvalue=False, orient='h', command=yEntreeCmd) EntreeY.grid(row=1, column=1) # Label Couleur CoulEntreeLbl = Label(entreeFrame, text="Couleur", bg=CoulEntree) CoulEntreeLbl.grid(row=2, column=0) # Bouton Couleur CoulEntreeBtn = Button(entreeFrame, text=CoulEntree, bg=CoulEntree, command=coulEntreeCmd) CoulEntreeBtn.grid(row=2, column=1) # Fin de la partie entreeFrame entreeFrame.grid(row=0, column=1, sticky=tkinter.N + tkinter.S) # Partie 'Sortie' sortieFrame = LabelFrame(dataFrame, text='Sortie') # Abscisse Label(sortieFrame, text="X").grid(row=0, column=0) SortieX = Scale(sortieFrame, to=LARGEUR_DEF - 1, showvalue=False, orient='h', command=xSortieCmd) SortieX.grid(row=0, column=1) # Ordonnée Label(sortieFrame, text="Y").grid(row=1, column=0) SortieY = Scale(sortieFrame, to=HAUTEUR_DEF - 1, showvalue=False, orient='h', command=ySortieCmd) SortieY.grid(row=1, column=1) # Label Couleur CoulSortieLbl = Label(sortieFrame, text="Couleur", bg=CoulSortie) CoulSortieLbl.grid(row=2, column=0) # Bouton Couleur CoulSortieBtn = Button(sortieFrame, text=CoulSortie, bg=CoulSortie, command=coulSortieCmd) CoulSortieBtn.grid(row=2, column=1) # Fin de la partie sortieFrame sortieFrame.grid(row=0, column=2, sticky=tkinter.N + tkinter.S) # Partie 'Algo' algoFrame = LabelFrame(dataFrame, text='Algorithme') # Main Label(algoFrame, text='Main').grid(row=0, column=0) Main = StringVar(Wroot) Main.set(MAIN[0]) OptionMenu(algoFrame, Main, *MAIN, command=mainCmd).grid(row=0, column=1) # Orientation Label(algoFrame, text='Orientation').grid(row=1, column=0) Orient = StringVar(Wroot) Orient.set(ORIENTATION[0]) OptionMenu(algoFrame, Orient, *ORIENTATION, command=orientationCmd).grid(row=1, column=1) # Bouton 'Démarrer' DemarrerBtn = Button(algoFrame, text='Démarrer', command=demarrerCmd, state='disabled') DemarrerBtn.grid(row=2, column=0) # Scale 'Replay' Replay = Scale(algoFrame, showvalue=False, orient='h', label='Chemin', command=replayCmd) Replay.grid(row=2, column=1) # Fin de la partie algoFrame algoFrame.grid(row=0, column=3, sticky=tkinter.N + tkinter.S) # Fin de la partie dataFrame et affichage dataFrame.grid(row=0, column=0) # Fenêtre graphique (canvas) Wcanvas = Canvas(Wroot, background='white', width=a_largeur, height=a_hauteur) # Fin de la partie Wcanvas et affichage Wcanvas.grid(row=1, column=0) return
# connect previous mouse position to current one curve.append(canvas.create_line(oldx, oldy, newx, newy)) oldx, oldy = newx, newy # new position becomes previous def delete(event): 'delete last curve drawn' global curve for segment in curve: canvas.delete(segment) #GUI root = Tk() oldx, oldy = 0, 0 # mouse coordinates (global variables) # canvas canvas = Canvas(root, height=100, width=150) # bind left mouse button click event to begin() canvas.bind("<Button-1>", begin) # bind mouse motion while pressing left button event to draw() canvas.bind("<Button1-Motion>", draw) # bind Ctrl-Left button mouse click to delete() canvas.bind('<Control-Button-1>', delete) canvas.pack() root.mainloop()
class SudokuUI(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.__initUI() def __initUI(self): self.parent.title("AI: Sudoku Solver") self.pack(fill=BOTH) self.canvas = Canvas(self, width=WIDTH, height=HEIGHT + 10) self.problem = Problem(self.canvas, 0, DELAY) # Initialize each cell in the puzzle for i in range(1, 10): for j in range(1, 10): self.item = self.canvas.create_text( MARGIN + (j - 1) * SIDE + SIDE / 2, MARGIN + (i - 1) * SIDE + SIDE / 2, text='', tags="numbers", fill="black", font=("Helvetica", 12)) self.item = self.canvas.create_text(40, 490, text='Count :', fill="black", font=("Helvetica", 13)) self.item = self.canvas.create_text(95, 490, text='', fill="black", font=("Helvetica", 13)) self.item = self.canvas.create_text(170, 490, text='Average :', fill="black", font=("Helvetica", 13)) self.item = self.canvas.create_text(225, 490, text='', fill="black", font=("Helvetica", 13)) self.item = self.canvas.create_text(320, 490, text='Ranking :', fill="black", font=("Helvetica", 13)) self.item = self.canvas.create_text(370, 490, text='', fill="black", font=("Helvetica", 13)) self.item = self.canvas.create_text(420, 490, text='Total :', fill="black", font=("Helvetica", 13)) self.item = self.canvas.create_text(460, 490, text='', fill="black", font=("Helvetica", 13)) self.canvas.pack(fill=BOTH, side=TOP) self.start_button1 = Button(self, text="__Start__", command=self.__start_solver) self.start_button2 = Button(self, text="__Submit__", command=self.__submit) self.start_button2.pack(side=LEFT) self.start_button1.pack(side=RIGHT) self.start_button2.config(state="disabled") self.__draw_grid() # Draws 9x9 grid def __draw_grid(self): for i in range(10): width = 3 if i % 3 == 0 else 1 x0 = MARGIN + i * SIDE y0 = MARGIN x1 = MARGIN + i * SIDE y1 = HEIGHT - MARGIN self.canvas.create_line(x0, y0, x1, y1, fill="black", width=width) x0 = MARGIN y0 = MARGIN + i * SIDE x1 = WIDTH - MARGIN y1 = MARGIN + i * SIDE self.canvas.create_line(x0, y0, x1, y1, fill="black", width=width) def __start_solver(self): self.start_button1.config(state="disabled") for i in range(100): for m in range(1, 10): for n in range(1, 10): self.canvas.itemconfig(9 * (m - 1) + n, text='', tags="numbers", fill="black") self.SudokuSolver = SudokuSolver(self.problem) self.SudokuSolver.solver() if self.problem.finished == 0: self.problem.fail() break self.canvas.update() self.problem = Problem(self.canvas, self.problem.tk, 0) self.problem.update_a() self.start_button2.config(state="active") def __submit(self): request = self.problem.submit(univ_id, password) message = request.split(',') if int(message[0]) == 100: self.problem.fail_10min() elif int(message[0]) == 101: self.canvas.update() self.canvas.itemconfig(87, text=int(message[1]), tags="numbers", fill="blue") self.canvas.itemconfig(89, text=int(message[2]), tags="numbers", fill="blue") self.problem.already_done() elif int(message[0]) == 102: self.canvas.update() self.canvas.itemconfig(87, text=int(message[1]), tags="numbers", fill="blue") self.canvas.itemconfig(89, text=int(message[2]), tags="numbers", fill="blue") self.problem.is_done() elif int(message[0]) == 501: print("501") self.problem.wrong_id_pw()
def build(self): """widget construction Parameters ---------- None Results ------- None """ rl1 = Label(self.fr0, text='red ') rl1.grid(column=0, row=0) self.rcan = Canvas(self.fr0, width=self.canvas_w, height=self.canvas_h) self.rcan.grid(column=1, row=0, sticky='n') rsc = Scale(self.fr0, from_=0, to=255, variable=self.rvar, orient='horizontal', length=self.scale_l, command=self.rhandle, tickinterval=20, showvalue=0) rsc.grid(column=1, row=1, sticky='nw') rsb = Spinbox(self.fr0, from_=0, to=255, textvariable=self.rvar, command=self.rhandle, width=5) rsb.grid(column=2, row=1, sticky='nw') gl1 = Label(self.fr0, text='green') gl1.grid(column=0, row=2) self.gcan = Canvas(self.fr0, width=self.canvas_w, height=self.canvas_h) self.gcan.grid(column=1, row=2, sticky='n') gsc = Scale(self.fr0, from_=0, to=255, variable=self.gvar, orient='horizontal', length=self.scale_l, command=self.ghandle, tickinterval=20, showvalue=0) gsc.grid(column=1, row=3, sticky='nw') gsb = Spinbox(self.fr0, from_=0, to=255, textvariable=self.gvar, command=self.ghandle, width=5) gsb.grid(column=2, row=3, sticky='nw') bl1 = Label(self.fr0, text='blue ') bl1.grid(column=0, row=4) self.bcan = Canvas(self.fr0, width=self.canvas_w, height=self.canvas_h) self.bcan.grid(column=1, row=4, sticky='n') bsc = Scale(self.fr0, from_=0, to=255, variable=self.bvar, orient='horizontal', length=self.scale_l, command=self.bhandle, tickinterval=20, showvalue=0) bsc.grid(column=1, row=5, sticky='nw') bsb = Spinbox(self.fr0, from_=0, to=255, textvariable=self.bvar, command=self.bhandle, width=5) bsb.grid(column=2, row=5, sticky='nw') self.lab = lab = Label(self.fr0, height=4, width=10) lab.grid(column=1, row=6) lab.grid_propagate(0) lab['background'] = self.rgbhash(self.rvar.get(), self.gvar.get(), self.bvar.get())
def pilot_canvas(width=800, height=600, linewidth=3, linecolor="BLACK"): """Opens a canvas widget using tkinter that allows a user to save their work. :param width: Canvas width, defaults to 800. :type width: int, optional :param height: Canvas height, defaults to 600. :type height: int, optional :param linewidth: Canvas marker linewidth, defaults to 3. :type linewidth: int, optional :param linecolor: Canvas marker linecolor, defaults to black. :type linecolor: str, optional :return: Dictionary of filename where canvas was saved. :rtype: dict """ def save(): """Saves a canvas file after appending with string of N random characters for uniquness. :param N: Number of random characters to append, defaults to 5. :type N: int """ filename = "temp_files/cv_temp.png" canvas_image.save(filename) print("File was saved as: ", filename) def save_posn(event): """Saves positional coordinates of object event. :param event: Recorded mouse-click events for drawing. :type event: class tkinter.Event :return: none :rtype: none """ global lastx, lasty lastx, lasty = event.x, event.y def quit(): root.destroy() def add_line(event): """Adds a line connection previous location of event to current event location. Event here is where the mouse was and is located. Also draws the same line on a PIL image which represents the image drawn on the tkinter canvas by the user. This is the image that will actually be saved and used by the OCR. :param event: Recorded mouse-click events for drawing. :type event: class tkinter.Event :return: none :rtype: none """ # This canvas call is what the user sees on the screen. canvas.create_line((lastx, lasty, event.x, event.y), smooth=True, width=linewidth, fill=linecolor) # The draw call is in the background (invisible) # capturing what will actually get converted to an image. draw.line([lastx, lasty, event.x, event.y], fill=linecolor, width=linewidth, joint='curve') save_posn(event) offset = (linewidth) / 2 filename = {} root = Tk() # Instantiate the tkinter canvas to draw on. canvas = Canvas(root, bg="white", width=width, height=height) canvas.pack() # PIL create an empty image and draw object to draw on memory only. It is not visible. canvas_image = Image.new("RGB", (width, height), (255, 255, 255)) draw = ImageDraw.Draw(canvas_image) canvas.pack(expand=True, fill="both") canvas.bind("<Button-1>", save_posn) canvas.bind("<B1-Motion>", add_line) button_save = Button(text="Save Image", command=save) button_quit = Button(text="Quit", command=quit) button_save.pack() button_quit.pack() root.mainloop()
b_3 = Radiobutton(frame0, text="New Database", variable=database, value=3, anchor='w') b_0.pack() b_1.pack() b_2.pack() b_3.pack() button5 = Button(frame0, text="Validate", command=lambda x=database: validate_database(x)) button5.pack(side=RIGHT, padx=30, pady=30) # canvas 1 in frame 1 canvas1 = Canvas(frame1, width=100, height=100, background='white') canvas1.bind("<Button-1>", mouseDown) canvas1.bind("<B1-Motion>", mouseMove) canvas1.pack(side=LEFT, padx=30, pady=30) # buttons in frame 1 button7 = Button(frame1, text="Save", command=save) button7.pack(side=RIGHT, padx=30, pady=30) button3 = Button(frame1, text="Add", command=add) button3.pack(side=RIGHT, padx=30, pady=30) button2 = Button(frame1, text="Correct", command=correct) button2.pack(side=RIGHT, padx=30, pady=30) button1 = Button(frame1, text="Predict", command=predict)
from tkinter import Tk, Canvas, mainloop root = Tk() c = Canvas(root, width=500, height=500) c.pack() # Put drawing here! c.create_rectangle(50, 50, 250, 250, fill='red') c.create_oval(350, 50, 250, 250, 500, fill='green') c.create_rectangle(50, 50, 300, 400, fill='blue') for y in range(50, 500, 50): c.create_line(0, y, 500, y) c.create_text(18, y + 10, text=str(y)) for x in range(50, 500, 50): c.create_line(x, 0, x, 500) c.create_text(x + 18, 10, text=str(x)) def react_to_click(event): root.quit() c.bind('<Button-1>', react_to_click) mainloop()
from tkinter import Canvas, Tk import time import shapes gui = Tk() gui.title('Animation') canvas = Canvas(gui, width=500, height=500, background='white') canvas.pack() ########################## YOUR CODE BELOW THIS LINE ############################## # Challenge: # Do the same thing as in 05_while_animate, but with # all 4 shapes: # 1. Make the car smoothly drive across the screen # 2. Make it drive backwards (on your own) # 3. Make it drive vertically (on your own) # 4. Make it drive diagonally (on your own) # 5. If it gets to the end, of the screen, # make it reverse directions (on your own) # 6. Make it accelerate (on your own) #make car: top_id = shapes.make_rectangle(canvas, (100, 20), 100, 40) bottom_id = shapes.make_rectangle(canvas, (50, 50), 200, 45) wheel1_id = shapes.make_circle(canvas, (100, 100), 20, color='black') wheel2_id = shapes.make_circle(canvas, (200, 100), 20, color='black') # move car: shapes.move(canvas, wheel1_id, x=60, y=0) shapes.move(canvas, wheel2_id, x=60, y=0) shapes.move(canvas, bottom_id, x=60, y=0)
from tkinter import YES from tkinter import BOTH from SierpinskiTriangle import SierpinskiTriangle # ---- main program if __name__ == "__main__": sp_tri = SierpinskiTriangle(500, 500) cw, ch = sp_tri.grid_dimensions() root = Tk() root.title('Sierpinski Triangle') canvas_1 = Canvas(root, width=cw, height=ch, background='white') canvas_1.pack(expand=YES, fill=BOTH) #img = PhotoImage(width=cw, height=ch) #canvas_1.create_image((0, 0), image=img, state="normal") plot_count = 25000 for i in range(1, plot_count): ptx, pty = sp_tri.next() canvas_1.create_oval(ptx, pty, ptx, pty, width=0, fill='red') # plots a "point" #img.put("#ffffff", (ptx, pty)) # "live" update, no explicit update() call required canvas_1.update( ) # refresh the drawing on the canvas after all points plotted root.mainloop()
posArray = np.ndarray([numXspaces,numYspaces],dtype=CellPos) for i in range(0, numXspaces): #canWidth//gridSizeX): xNext = xLast+gridSizeX for j in range(0,numYspaces): #canHeight//gridSizeY): yNext = yLast+gridSizeY recPos = CellPos(xLast,yLast,xNext,yNext) #list_of_pos.append(recPos) posArray[i][j] = recPos yLast = yNext xLast = xNext yLast = xStart #create canvas and put it on the window canvas = Canvas(root,width=canWidth,height=canHeight) canvas.pack() x = 0 #pheduo x y = 0 #pheduo y #this code fills each surrounding rectangle with their adjacent rectangle addresses #it also draws each position on the canvas for row in posArray: for rec in row: #list_of_pos: rec.drawSelf(canvas) #draws every rectangle #print("########&&&&&&&&&&&&&&&&&&&&&&&&&") #print("cell x = ", x, "y = ",y,"has neighbors") for i in range(-1,2): for j in range(-1,2): #print("x, y,, x+i,y+j were called",x,y,i,j,"(x+i) and (y+j)",(x+i),(x+j))
KEY_LEFT: lambda x, y: (x - 1, y), KEY_RIGHT: lambda x, y: (x + 1, y), KEY_UP: lambda x, y: (x, y - 1), KEY_DOWN: lambda x, y: (x, y + 1) } opcmapper.parse_layout(layout) window = Tk() window.geometry('{}x{}'.format(X * BLOCK_SIZE, Y * BLOCK_SIZE)) window.resizable(False, False) frame = Frame(window) frame.master.title('Snake') frame.pack(fill=BOTH, expand=1) canvas = Canvas(frame) canvas.pack(fill=BOTH, expand=1) def frame_off(): global pixels pixels = [(0, 0, 0)] * numLEDs client.put_pixels(pixels) def add_to_current_pixel_frame(x, y, color): #print('x:', x) #print('y:', y) pixels[opcmapper.find_led_number_for_x_and_y_value(x, y)] = color
ps = 1 else: ps = 0 move() def slow(): global ps if ps == 1: ps = 0 move() ps = 1 fen1 = Tk() can1 = Canvas(fen1, height=largeur, width=longueur, bg='grey80') x = [0] * N y = [0] * N R = [[i, j] for i in range(1, longueur // (2 * r)) for j in range(1, largeur // (2 * r))] [x[0], y[0]] = choice(R) for i in range(1, N): R.remove([x[i - 1], y[i - 1]]) [x[i], y[i]] = choice(R) for i in range(N): x[i], y[i] = 2 * r * x[i], 2 * r * y[i] cercle = [] for i in range(N): cercle.append([ can1.create_oval(x[i] - r, y[i] - r,
def simulation_canvas (parent,**config): global the_canvas the_canvas = Canvas(parent,**config) the_canvas.bind("<ButtonRelease>", lambda event : model.mouse_click(event.x,event.y)) return the_canvas
class SudokuUI(Frame): def __init__(self, parent, game): self.game = game self.parent = parent self.Width = Width self.Height = Height Frame.__init__(self, parent) self.row, self.col = 0, 0 self.__initUI__() def __initUI__(self): self.parent.title("Sudoku") self.pack(fill=BOTH) self.canvas = Canvas(self, width=self.Width, height=self.Height) self.canvas.pack(fill=BOTH, side=TOP) self.frame = Frame(self) #self.frame.grid(row = 2, column = 0) button1 = Button(self.frame, text="Solve", bg="green", font=('Ariel', 16)) button2 = Button(self.frame, text="Reset", bg="green", font=('Ariel', 16), command=self.reset) button1.grid(row=0, column=2, padx=(0, 2.5), pady=(0, 5)) button2.grid(row=0, column=3, padx=(2.5, 0), pady=(0, 5)) self.frame.pack() self.draw_grid() self.insert_values() self.canvas.bind("<Button-1>", self.cell_clicked) self.canvas.bind("<Key>", self.key_pressed) #Grid drawing def draw_grid(self): 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 reset(self): self.game.__init__() self.insert_values() def insert_values(self): self.canvas.delete("numbers") for i in range(9): for j in range(9): x = Margin + Side * i + Side / 2 y = Margin + Side * j + Side / 2 val = self.game.board[i][j] if val != 0: color = "black" self.canvas.create_text(y, x, text=val, font=('Ariel', 12, 'bold'), fill=color, tags="numbers") def cell_clicked(self, event): x, y = event.x, event.y if Margin < x < Width - Margin and Margin < y < Height - Margin: self.canvas.focus_set() row, col = (y - Margin) // Side, (x - Margin) // Side if (row, col) == (self.row, self.col): self.row, self.col = -1, -1 elif self.game.board[row][col] == 0: self.row, self.col = row, col self.highlight_cell() def highlight_cell(self): self.canvas.delete("Highlight") if self.row >= 0 and self.col >= 0: y0 = Margin + self.row * Side x0 = Margin + self.col * Side y1 = Margin + (self.row + 1) * Side x1 = Margin + (self.col + 1) * Side self.canvas.create_rectangle(x0, y0, x1, y1, tags="Highlight", outline="red") def key_pressed(self, event): if self.row >= 0 and self.col >= 0 and event.char in "123456789": val = int(event.char) self.game.board[self.row][self.col] = val self.row = -1 self.col = -1 if self.game.isValidMove(self.game.board, self.row, self.col, val): #print("Success") self.insert_cell(event, val) else: print("Fail") def insert_cell(self, event, value): x, y = event.x, event.y row, col = (y - Margin) // Side, (x - Margin) // Side row = Margin + Side * col + Side // 2 col = Margin + Side * row + Side // 2 self.canvas.create_text(col, row, text=value, font=('Ariel', 12, 'bold'), fill="black", tags="numbers")
class RgbSelect: """Class to construct rgb gradients Parameters ---------- fr0 : str parent widget Returns ------- None """ def __init__(self, fr0): self.fr0 = fr0 self.rvar = IntVar() self.gvar = IntVar() self.bvar = IntVar() self.scale_l = 300 self.canvas_w = self.scale_l - 30 self.canvas_h = 26 self.build() self.rvar.set(255) self.gvar.set(0) self.bvar.set(0) def rhandle(self, _evt): """command callback for red Parameters ---------- None Results ------- None """ red = self.rvar.get() green = self.gvar.get() blue = self.bvar.get() draw_gradient(self.gcan, (red, 0, blue), (red, 255, blue), width=self.canvas_w) draw_gradient(self.bcan, (red, green, 0), (red, green, 255), width=self.canvas_w) self.lab['background'] = self.rgbhash(red, green, blue) def ghandle(self, _evt): """command callback for green Parameters ---------- None Results ------- None """ red = self.rvar.get() green = self.gvar.get() blue = self.bvar.get() draw_gradient(self.rcan, (0, green, blue), (255, green, blue), width=self.canvas_w) draw_gradient(self.bcan, (red, green, 0), (red, green, 255), width=self.canvas_w) self.lab['background'] = self.rgbhash(red, green, blue) def bhandle(self, _evt): """command callback for blue Parameters ---------- None Results ------- None """ red = self.rvar.get() green = self.gvar.get() blue = self.bvar.get() draw_gradient(self.rcan, (0, green, blue), (255, green, blue), width=self.canvas_w) draw_gradient(self.gcan, (red, 0, blue), (red, 255, blue), width=self.canvas_w) self.lab['background'] = self.rgbhash(red, green, blue) def build(self): """widget construction Parameters ---------- None Results ------- None """ rl1 = Label(self.fr0, text='red ') rl1.grid(column=0, row=0) self.rcan = Canvas(self.fr0, width=self.canvas_w, height=self.canvas_h) self.rcan.grid(column=1, row=0, sticky='n') rsc = Scale(self.fr0, from_=0, to=255, variable=self.rvar, orient='horizontal', length=self.scale_l, command=self.rhandle, tickinterval=20, showvalue=0) rsc.grid(column=1, row=1, sticky='nw') rsb = Spinbox(self.fr0, from_=0, to=255, textvariable=self.rvar, command=self.rhandle, width=5) rsb.grid(column=2, row=1, sticky='nw') gl1 = Label(self.fr0, text='green') gl1.grid(column=0, row=2) self.gcan = Canvas(self.fr0, width=self.canvas_w, height=self.canvas_h) self.gcan.grid(column=1, row=2, sticky='n') gsc = Scale(self.fr0, from_=0, to=255, variable=self.gvar, orient='horizontal', length=self.scale_l, command=self.ghandle, tickinterval=20, showvalue=0) gsc.grid(column=1, row=3, sticky='nw') gsb = Spinbox(self.fr0, from_=0, to=255, textvariable=self.gvar, command=self.ghandle, width=5) gsb.grid(column=2, row=3, sticky='nw') bl1 = Label(self.fr0, text='blue ') bl1.grid(column=0, row=4) self.bcan = Canvas(self.fr0, width=self.canvas_w, height=self.canvas_h) self.bcan.grid(column=1, row=4, sticky='n') bsc = Scale(self.fr0, from_=0, to=255, variable=self.bvar, orient='horizontal', length=self.scale_l, command=self.bhandle, tickinterval=20, showvalue=0) bsc.grid(column=1, row=5, sticky='nw') bsb = Spinbox(self.fr0, from_=0, to=255, textvariable=self.bvar, command=self.bhandle, width=5) bsb.grid(column=2, row=5, sticky='nw') self.lab = lab = Label(self.fr0, height=4, width=10) lab.grid(column=1, row=6) lab.grid_propagate(0) lab['background'] = self.rgbhash(self.rvar.get(), self.gvar.get(), self.bvar.get()) def rgbhash(self, red, green, blue): """Convert rgb to hexadecimal Parameters ---------- red : int red component green : int green component blue : int blue component Results ------- string hexadecimal colour """ rgb = (red, green, blue) return '#%02x%02x%02x' % rgb
from tkinter import Tk, Canvas, mainloop SPEED = 10 root = Tk() c = Canvas(root, width=500, height=500) c.pack() # Put drawing here! c.create_rectangle(0, 0, 500, 300, fill='blue') c.create_rectangle(0, 300, 500, 500, fill='yellow') c.create_rectangle(347, 380, 353, 450, fill='white') c.create_polygon(350, 360, 400, 400, 300, 400, fill='green') c.create_oval(80, 320, 140, 380, fill='white') c.create_oval(85, 320, 135, 380, fill='blue') c.create_oval(90, 320, 130, 380, fill='red') c.create_oval(95, 320, 125, 380, fill='white') c.create_oval(100, 320, 120, 380, fill='blue') c.create_oval(105, 320, 115, 380, fill='red') c.create_oval(109, 320, 111, 380, fill='white') c.create_oval(440, 0, 550, 110, fill='yellow') c.create_rectangle(0, 0, 505, 50, fill='light grey') birds = [ c.create_polygon(300, 175, 335, 200, 300, 185, 265, 200, fill='white'), c.create_polygon(165, 125, 200, 150, 165, 135, 130, 150, fill='white'), ] def animate(): # Make bird wings flap.
def __initUI(self): self.parent.title("AI: Sudoku Solver") self.pack(fill=BOTH) self.canvas = Canvas(self, width=WIDTH, height=HEIGHT + 10) self.problem = Problem(self.canvas, 0, DELAY) # Initialize each cell in the puzzle for i in range(1, 10): for j in range(1, 10): self.item = self.canvas.create_text( MARGIN + (j - 1) * SIDE + SIDE / 2, MARGIN + (i - 1) * SIDE + SIDE / 2, text='', tags="numbers", fill="black", font=("Helvetica", 12)) self.item = self.canvas.create_text(40, 490, text='Count :', fill="black", font=("Helvetica", 13)) self.item = self.canvas.create_text(95, 490, text='', fill="black", font=("Helvetica", 13)) self.item = self.canvas.create_text(170, 490, text='Average :', fill="black", font=("Helvetica", 13)) self.item = self.canvas.create_text(225, 490, text='', fill="black", font=("Helvetica", 13)) self.item = self.canvas.create_text(320, 490, text='Ranking :', fill="black", font=("Helvetica", 13)) self.item = self.canvas.create_text(370, 490, text='', fill="black", font=("Helvetica", 13)) self.item = self.canvas.create_text(420, 490, text='Total :', fill="black", font=("Helvetica", 13)) self.item = self.canvas.create_text(460, 490, text='', fill="black", font=("Helvetica", 13)) self.canvas.pack(fill=BOTH, side=TOP) self.start_button1 = Button(self, text="__Start__", command=self.__start_solver) self.start_button2 = Button(self, text="__Submit__", command=self.__submit) self.start_button2.pack(side=LEFT) self.start_button1.pack(side=RIGHT) self.start_button2.config(state="disabled") self.__draw_grid()
cell = CellMatrix[row][col] cell.dark = True cell.variant = -1 cell.update_cell() update_score(canvas, reset=True) make_move() if game_over_label != None: game_over_label.destroy() root.update() game_over_label = None if __name__ == '__main__': load_assets() canvas = Canvas(root, borderwidth=0, width=1000, height=1000) canvas.place(x=0, y=0, relwidth=1, relheight=1) create_cells() update_background(canvas) place_cells(canvas) create_info(canvas) generate_hint_items() place_hint_items() generate_hint_items() try:
class PetriNetView(Frame): """ This class implements a Petri net widget. This class use a canvas to draw a Petri net. """ def __init__(self, parent): """ This method creates a new, emtpy PetriNetView. """ Frame.__init__(self, parent) self.__parent = parent self.__initUI() self.__net = None self.__node_size = 15 def __initUI(self): """ Set up user interface. """ self.pack(fill=BOTH, expand=1) self.__canvas = Canvas(self) # canvas for the Petri net self.__canvas.pack(fill=BOTH, expand=1) # Scroll with mouse drag gestures self.__canvas.bind("<ButtonPress-1>", self.__scroll_start) self.__canvas.bind("<B1-Motion>", self.__scroll_move) def __scroll_start(self, event): """ Scroll Petri net with mouse gestures: Start of scroll event. """ self.__canvas.scan_mark(event.x, event.y) def __scroll_move(self, event): """ Scroll Petri net with mouse gestures: Drag event. """ self.__canvas.scan_dragto(event.x, event.y, gain=1) def showPetriNet(self, petrinet): """ This method show the given LPO in this LpoView. """ self.__net = petrinet # set Petri net reference self.__drawNet() # create Net graph def __drawNet(self): """ This method draws the Petri net. """ # draw places for id, place in self.__net.places.items(): self.__drawPlace(place) # draw transitions for id, transition in self.__net.transitions.items(): self.__drawTransition(transition) # draw Petri net edges (arc layer is behind the other layers) for edge in self.__net.edges: self.__drawEdge(edge) def __drawPlace(self, place): """ Draw the given place. """ self.__canvas.create_oval(place.position[0] - self.__node_size, place.position[1] - self.__node_size, place.position[0] + self.__node_size, place.position[1] + self.__node_size, outline="#000", fill="#FFFFFF", width=2) self.__canvas.create_text(place.position[0], place.position[1] + self.__node_size + 10, text=place.label) def __drawTransition(self, transition): """ Draw the given place. """ self.__canvas.create_rectangle( transition.position[0] - self.__node_size, transition.position[1] - self.__node_size, transition.position[0] + self.__node_size, transition.position[1] + self.__node_size, outline="#000", fill="#FFFFFF", width=2) self.__canvas.create_text(transition.position[0], transition.position[1] + self.__node_size + 10, text=transition.label) def __drawEdge(self, edge): """ Draw the given edge. """ start_node = edge.find_source() # get start event end_node = edge.find_target() # get end event intersections = self.__calculateIntersections( start_node, end_node) # calculate intersection points # start point of arc start = start_node.position[0] + intersections[0][ 0], start_node.position[1] + intersections[0][1] # end point of arc end = end_node.position[0] + intersections[1][0], end_node.position[ 1] + intersections[1][1] # create line with arrow head as end self.__canvas.create_line(start[0], start[1], end[0], end[1], arrow=LAST, arrowshape=(8.6, 10, 5), width=2) def __calculateIntersections(self, start, end): """ Calculate intersection point of start and end events with the arc. This method calculates two vectors which describe the intersection point of the arc from the given start event to the given end event. """ # vector from the center of the start event to the center of the end event vector = float(end.position[0] - start.position[0]), float(end.position[1] - start.position[1]) if type(start) is petrinet.Transition: #calculate a factor to scale the x-component to 10px (half of side length) fact = 1 if vector[0] != 0: fact = self.__node_size / math.fabs(vector[0]) # scale the vector start_vector = vector[0] * fact, vector[1] * fact # if y-component of vector is larger than 10px or x-component is 0, scale with y-component if math.fabs(start_vector[1]) > self.__node_size or vector[0] == 0: fact = self.__node_size / math.fabs(vector[1]) start_vector = vector[0] * fact, vector[1] * fact else: fact = self.__node_size / math.sqrt(vector[0]**2 + vector[1]**2) start_vector = vector[0] * fact, vector[1] * fact #calculate intersection for arc end if type(end) is petrinet.Transition: if vector[0] != 0: fact = self.__node_size / math.fabs(vector[0]) end_vector = -vector[0] * fact, -vector[1] * fact if math.fabs(end_vector[1]) > self.__node_size or vector[0] == 0: fact = self.__node_size / math.fabs(vector[1]) end_vector = -vector[0] * fact, -vector[1] * fact else: fact = self.__node_size / math.sqrt(vector[0]**2 + vector[1]**2) end_vector = -vector[0] * fact, -vector[1] * fact return start_vector, end_vector
class SudokuUI(Frame): """ The Tkinter UI, responsible for drawing the board and accepting user input. """ def __init__(self, board): """Initialize Tk frame""" self.sudoku = board self.parent = Tk() Frame.__init__(self, self.parent) self.row, self.col = -1, -1 self.__initialize() def __initialize(self): """Set up all widgets on board""" self.parent.title("Sudoku Solver") self.pack(fill=BOTH) save_button = Button(self, text="Save", command=self.__save) save_button.pack(fill=BOTH, side=BOTTOM) self.canvas = Canvas(self, width=WIDTH, height=HEIGHT) self.canvas.pack(fill=BOTH, side=TOP) clear_button = Button(self, text="Clear", command=self.__clear) clear_button.pack(fill=BOTH, side=BOTTOM) solve_button = Button(self, text="Solve", command=self.__solve) solve_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 3x3 squares """ 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): """Fill in the existing puzzle details""" self.canvas.delete("result") # remove time stamp from view self.canvas.delete("numbers") for i in range(9): for j in range(9): cell = self.sudoku.board[i][j] number = cell.number if number != 0: x = MARGIN + j * SIDE + SIDE / 2 y = MARGIN + i * SIDE + SIDE / 2 self.canvas.create_text(x, y, text=number, tags="numbers", fill="black") def __draw_cursor(self): """Draw a red border around a selected cell""" 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 __draw_result(self, success, time): # create a oval (which will be a circle) x0 = y0 = MARGIN + SIDE * 2 x1 = y1 = MARGIN + SIDE * 7 self.canvas.create_oval(x0, y0, x1, y1, tags="result", fill="dark gray", outline="black") # create text x = y = MARGIN + 4 * SIDE + SIDE / 2 text = "{0:.4f}s".format(time) if success else "Invalid Board" self.canvas.create_text(x, y, text=text, tags="result", fill="white", font=("Arial", 28)) def __draw_message(self, msg): # create a oval (which will be a circle) x0 = y0 = MARGIN + SIDE * 2 x1 = y1 = MARGIN + SIDE * 7 self.canvas.create_oval(x0, y0, x1, y1, tags="result", fill="white", outline="blue") # create text x = y = MARGIN + 4 * SIDE + SIDE / 2 self.canvas.create_text(x, y, text=msg, tags="result", fill="black", font=("Arial", 12)) def __cell_clicked(self, event): self.canvas.delete("result") # remove time stamp from view 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 # if cell was selected already - deselect it if (row, col) == (self.row, self.col): self.row, self.col = -1, -1 else: self.row, self.col = row, col else: self.row, self.col = -1, -1 self.__draw_cursor() def __key_pressed(self, event): """Catch all key press events and handle them""" if self.row >= 0 and self.col >= 0: if event.keysym in ["Up", "w"]: self.row = ((self.row + 8) % 9) elif event.keysym in ["Down", "Return", "s"]: self.row = ((self.row + 10) % 9) elif event.keysym in ["Right", "d"]: self.col = ((self.col + 10) % 9) elif event.keysym in ["Left", "a"]: self.col = ((self.col + 8) % 9) elif event.keysym in ["Delete", "BackSpace"]: self.sudoku.board[self.row][self.col].reset() elif event.char != "" and event.char in "1234567890": self.sudoku.board[self.row][self.col].number = int(event.char) self.__go_next() else: print("Unsupported key: \"{}\"".format(event.keysym)) self.__draw_puzzle() self.__draw_cursor() def __go_next(self): """Advance to the next cell""" row = self.row col = self.col if col < 8: self.col += 1 elif row < 8: self.row += 1 self.col = 0 else: self.row = 0 self.col = 0 def __clear(self): self.sudoku.clear() self.__draw_puzzle() def __solve(self): success, time = self.sudoku.solve() self.__draw_puzzle() self.__draw_result(success, time) def __save(self): f_path = io.write(self.sudoku) self.__draw_message("Saved to\n{}".format(f_path))
class GraphviewFrame(Frame): """ Frame inheritance class for plotting satellite view. """ def __init__(self, app, *args, **kwargs): """ Constructor. :param object app: reference to main tkinter application """ self.__app = app # Reference to main application class self.__master = self.__app.get_master() # Reference to root class (Tk) Frame.__init__(self, self.__master, *args, **kwargs) def_w, def_h = WIDGETU2 self.width = kwargs.get("width", def_w) self.height = kwargs.get("height", def_h) self._body() self.bind("<Configure>", self._on_resize) def _body(self): """ Set up frame and widgets. """ self.grid_columnconfigure(0, weight=1) self.grid_rowconfigure(0, weight=1) self.can_graphview = Canvas( self, width=self.width, height=self.height, bg=BGCOL ) self.can_graphview.pack(fill=BOTH, expand=YES) def init_graph(self): """ Initialise graph view """ w, h = self.width, self.height show_legend = self.__app.frm_settings.get_settings()["graphlegend"] resize_font = font.Font(size=min(int(h / 25), 10)) ticks = int(MAX_SNR / 10) self.can_graphview.delete("all") self.can_graphview.create_line(AXIS_XL, 5, AXIS_XL, h - AXIS_Y, fill=FGCOL) self.can_graphview.create_line( w - AXIS_XR + 2, 5, w - AXIS_XR + 2, h - AXIS_Y, fill=FGCOL ) for i in range(ticks, 0, -1): y = (h - AXIS_Y) * i / ticks self.can_graphview.create_line(AXIS_XL, y, w - AXIS_XR + 2, y, fill=FGCOL) self.can_graphview.create_text( 10, y, text=str(MAX_SNR - (i * 10)), angle=90, fill=FGCOL, font=resize_font, ) if show_legend: self._draw_legend() def _draw_legend(self): """ Draw GNSS color code legend """ w = self.width / 9 h = self.height / 15 resize_font = font.Font(size=min(int(self.height / 25), 10)) for i, (_, (gnssName, gnssCol)) in enumerate(GNSS_LIST.items()): x = LEG_XOFF + w * i self.can_graphview.create_rectangle( x, LEG_YOFF, x + w - LEG_GAP, LEG_YOFF + h, outline=gnssCol, fill=BGCOL, width=OL_WID, ) self.can_graphview.create_text( (x + x + w - LEG_GAP) / 2, LEG_YOFF + h / 2, text=gnssName, fill=FGCOL, font=resize_font, ) def update_graph(self, data, siv=16): """ Plot satellites' signal-to-noise ratio (cno). Automatically adjust y axis according to number of satellites in view. :param list data: array of satellite tuples (gnssId, svid, elev, azim, cno): :param int siv: number of satellites in view """ if siv == 0: return w, h = self.width, self.height self.init_graph() offset = AXIS_XL + 2 colwidth = (w - AXIS_XL - AXIS_XR + 1) / siv resize_font = font.Font(size=min(int(colwidth / 2), 10)) for d in sorted(data): # sort by ascending gnssid, svid gnssId, prn, _, _, snr = d if snr in ("", "0", 0): snr = 1 # show 'place marker' in graph else: snr = int(snr) snr_y = int(snr) * (h - AXIS_Y - 1) / MAX_SNR (_, ol_col) = GNSS_LIST[gnssId] prn = f"{int(prn):02}" self.can_graphview.create_rectangle( offset, h - AXIS_Y - 1, offset + colwidth - OL_WID, h - AXIS_Y - 1 - snr_y, outline=ol_col, fill=snr2col(snr), width=OL_WID, ) self.can_graphview.create_text( offset + colwidth / 2, h - 10, text=prn, fill=FGCOL, font=resize_font, angle=35, ) offset += colwidth self.can_graphview.update() def _on_resize(self, event): # pylint: disable=unused-argument """ Resize frame """ self.width, self.height = self.get_size() def get_size(self): """ Get current canvas size. """ self.update_idletasks() # Make sure we know about any resizing width = self.can_graphview.winfo_width() height = self.can_graphview.winfo_height() return (width, height)
class JogoOrdenador(AbstractRegrasJogo): def __init__(self, qtde_elems, a_seed=None): self.grade = [[0 for indiceLinha in range(qtdQuadradosLargura)] for indiceColuna in range(qtdQuadradosAltura)] self.window = Tk() self.canvas = Canvas(self.window, width=largura, height=altura, bg='black') self.canvas.pack() self.peca = listaPecas[0] '''self.window.bind("<Right>", print('right')) self.window.bind("<Left>", print('left')) self.window.bind("<Down>", print('down'))''' # Método responsável por adicionar peças ao jogo conforme forem caindo as anteriores def addPecas(self, peca): for lin in range(peca.tamanho): for col in range(peca.tamanho): if peca.grade[lin][col] != 0: self.grade[lin + peca.coluna][col + peca.linha] = peca.grade[lin][col] def registrarAgenteJogador(self, elem_agente=AgentesOrdenador.JOGADOR_PADRAO): """ Só há um agente, o jogador, então não preciso de lógica. """ return 1 def isFim(self): """ Se a lista estiver ordenada, fim de jogo. XXXX """ return False def gerarCampoVisao(self, id_agente): """ Como esse jogo é muito simples e totalmente observável, vou apenas utilizar um dicionário diretamente, com uma tupla imutável, como objeto de visão. """ for indiceLinha in range(self.peca.tamanho): for indiceColuna in range(self.peca.tamanho): if self.peca.grade[indiceLinha][indiceColuna] != 0: self.canvas.create_polygon( [(self.peca.linha + indiceColuna) * quadradoLado + 2, (self.peca.coluna + indiceLinha) * quadradoLado + 2, (self.peca.linha + indiceColuna) * quadradoLado + quadradoLado - 2, (self.peca.coluna + indiceLinha) * quadradoLado + 2, (self.peca.linha + indiceColuna) * quadradoLado + quadradoLado - 2, (self.peca.coluna + indiceLinha) * quadradoLado + quadradoLado - 2, (self.peca.linha + indiceColuna) * quadradoLado + 2, (self.peca.coluna + indiceLinha) * quadradoLado + quadradoLado - 2], fill='green') for lin in range(qtdQuadradosAltura): for col in range(qtdQuadradosLargura): if self.grade[lin][col] != 0: self.canvas.create_polygon([ col * quadradoLado + 2, lin * quadradoLado + 2, col * quadradoLado + quadradoLado - 2, lin * quadradoLado + 2, col * quadradoLado + quadradoLado - 2, lin * quadradoLado + quadradoLado - 2, col * quadradoLado + 2, lin * quadradoLado + quadradoLado - 2 ], fill="red") return {"grade": tuple(self.grade)} def registrarProximaAcao(self, id_agente, acao): """ Como só há um agente atuando no mundo, o próprio jogador, não é necessário nenhum mecanismo para guardar ações associadas por agentes distintos. """ self.acao_jogador = acao def atualizarEstado(self, diferencial_tempo): """ Não preciso me preocupar com a passagem do tempo, pois só uma jogada é feita por vez, e o jogo não muda seu estado sem jogadas. Verifico a ação última registrada e atualizado o estado do jogo computando-a. """ from acoes_agentes import AcoesJogador if self.acao_jogador.tipo == AcoesJogador.MOVER: direcao = self.acao_jogador.parametros if (direcao == "dir"): self.peca.direita(self) if (direcao == "esq"): self.peca.esquerda(self) if (direcao == "baixo"): global indice desceu = self.peca.desce(self) if desceu == 0: if (indice == 9): print("Você Venceu!") quit() indice += 1 self.addPecas(self.peca) self.peca = listaPecas[indice] for lin in range(self.peca.tamanho): for col in range(self.peca.tamanho): if self.peca.grade[lin][col] == 1 and self.grade[ self.peca.coluna + lin][self.peca.linha + col] != 0: print("Você perdeu!") quit() self.canvas.delete('all') else: raise TypeError
from itertools import cycle from random import randrange from tkinter import Tk, Canvas, messagebox, font canvas_width = 800 canvas_height = 400 win = Tk() #create canvas c = Canvas(win, width=canvas_width, height=canvas_height, background='deep sky blue') #create ground c.create_rectangle(-5, canvas_height - 100, canvas_width + 5, canvas_height + 5, fill='sea green', width=0) #create sun c.create_oval(-80, -80, 120, 120, fill='orange', width=0) c.pack() #create eggs color_cycle = cycle([ 'light blue', 'light pink', 'light yellow', 'light green', 'red', 'blue', 'green', 'black' ]) egg_width = 45 egg_height = 55
# CHoice option frame & grid methods for layout management choiceOptionFrame = groupBoxes("Choice Options", "right", mainFrameTop) btnColumn = Button(choiceOptionFrame, text="I am in column 3") btnColumn.grid(column=3) btnColumnSpan = Button(choiceOptionFrame, text="I have a columnspan of 3") btnColumnSpan.grid(columnspan=3) mainFrameBottom = Frame(mainWindow) mainFrameBottom.pack(side="bottom", fill="both", expand="yes") # Picture Viewer pictureFrame = groupBoxes("Picture Viewer", "left", mainFrameBottom) canvas = Canvas(pictureFrame, width=300, height=300) canvas.pack() img = PhotoImage(file=r"F:\Bilder\Anime\saber_mini.png") canvas.create_image(20, 20, anchor='nw', image=img) # Canvas Drawer canvasFrame = groupBoxes("Canvas Drawer", "right", mainFrameBottom) canvas = Canvas(canvasFrame, width=200, height=200) canvas.pack() def forward(): t.forward(50) def back(): t.back(50)
from tkinter import Tk, Canvas # Подключаем модуль import random # Модуль генерирования случайных чисел WIDTH =300 HEIGHT=300 BACKCOLOR = "#003300" FONTSIZE1 = "Arial 15" FONTSIZE2 = "Arial 20" root = Tk() root.title("My Game") c = Canvas(root, width=WIDTH, height=HEIGHT, bg=BACKCOLOR) c.grid() c.focus_set() game_over_text = c.create_text(WIDTH/2, HEIGHT/2, text="GAME OVER!", font=FONTSIZE1, fill='red', state='hidden') restart_text = c.create_text(WIDTH/2, HEIGHT-HEIGHT/3, font=FONTSIZE2, fill='white', text="Click here to restart", state='hidden')
return def sad(): if c.happy_level == 0: c.itemconfigure(mouth_happy, state=HIDDEN) c.itemconfigure(mouth_normal, state=HIDDEN) c.itemconfigure(mouth_sad, state=NORMAL) else: c.happy_level -= 1 win.after(500, sad) win = Tk() c = Canvas(win, width=400, height=400) c.configure(bg='red', highlightthickness=0) c.body_color = 'SkyBlue1' body = c.create_oval(35, 20, 365, 350, outline=c.body_color, fill=c.body_color) foot_left = c.create_oval(65, 320, 145, 360, outline=c.body_color, fill=c.body_color) foot_right = c.create_oval(250, 320, 330, 360,
class CanvasObject(Screen, metaclass=ABCMeta): def __init__(self, game): super().__init__(game, "gameEngine") os.environ['SDL_WINDOWID'] = str(self.f.winfo_id()) if platform.system() == "Windows": os.environ['SDL_VIDEODRIVER'] = 'windib' self.usePygame = True self.display = pygame.display.set_mode( (self.game.window.width, self.game.window.height)) self.display.fill((255, 255, 255)) pygame.display.init() pygame.font.init() else: self.usePygame = False self.canvas = Canvas(self.game.window.root, bg="white", width=self.game.window.width, height=self.game.window.height) self.canvas.pack(in_=self.f) self.customDrawLayer = None self.backgroundColor = (121, 202, 249) self.tkImageList = [ ] # images must maintain a reference in order to appear on the canvas def render(self): """ Clears screen draws all gameObjects at the appropriate layer, and then calls the draw method at the customDrawLayer, or last if not specified updates the canvas depending on whether using pygame :return: None """ self.clear() self.game.frameRateEngine.startTimer("draw canvas") objectList = GameObject.gameObjectList[:] customDrawn = False layerToDraw = 0 while len(objectList) != 0: for object in objectList: if object.layer == layerToDraw: object.draw(self) objectList.remove(object) layerToDraw += 1 if layerToDraw == self.customDrawLayer: self.draw() customDrawn = True if not customDrawn: self.draw() self.game.frameRateEngine.endTimer("draw canvas") self.updateCanvas() def clear(self): """ clears the screen and fills it with the background color :return: None """ self.game.frameRateEngine.startTimer("clear canvas") if self.usePygame: self.display.fill(self.backgroundColor) else: self.canvas.delete("all") self.canvas.create_rectangle(0, 0, self.game.window.width, self.game.window.height, fill="#%02x%02x%02x" % self.backgroundColor) self.tkImageList.clear() self.game.frameRateEngine.endTimer("clear canvas") def updateCanvas(self): """ updates the canvas with the proper method based on whether pygame is being used or tkinter :return: None """ self.game.frameRateEngine.startTimer("update canvas") if self.usePygame: pygame.display.update() self.game.window.root.update( ) # must update while in canvas in pygame but not in tkinter else: self.canvas.update() self.game.frameRateEngine.endTimer("update canvas") @abstractmethod def draw(self): """ abstract method to be overwritten by the draw method in drawingEngine :return: None """ pass def showRectangle(self, position1, position2, color, secondaryColor=(0, 0, 0), width=0, shiftPosition=False): """ Wrapper method for tkinter and pygame showRectangle methods :param position1: The first bounding point for the rectangle :param position1: the second point :param color: the color of the rectangle in rgb :param width: the width of the outline of the rectangle :param shiftPosition: whether to call the abstract method shift position on the passed coordinates. Default: False :param secondaryColor: the color of the outline in rgb. Default: black :return: None """ if shiftPosition: x1 = int((self.getScreenX(position1[0]))) y1 = int((self.getScreenY(position1[1]))) x2 = int((self.getScreenX(position2[0]))) y2 = int((self.getScreenY(position2[1]))) else: x1 = int(position1[0]) y1 = int(position1[1]) x2 = int(position2[0]) y2 = int(position2[1]) if self.usePygame: pygame.draw.rect(self.display, color, ((int(x1), int(y1)), (int(x2 - x1), int(y2 - y1)))) if width != 0: pygame.draw.rect(self.display, secondaryColor, ((int(x1), int(y1)), (int(x2 - x1), int(y2 - y1))), int(width)) else: tk_rgb = "#%02x%02x%02x" % color secondary_tk_rgb = "#%02x%02x%02x" % secondaryColor self.canvas.create_rectangle(x1, y1, x2, y2, fill=tk_rgb, width=width, outline=secondary_tk_rgb) def showLine(self, position1, position2, color, width, shiftPosition=False, rounded=False): """ Wrapper method for tkinter and pygame showLine methods :param position1: the first point of the line :param position1: the second point :param color: the color of the line in rgb :param width: the width of the line :param shiftPosition: whether to call the abstract method shift position on the passed coordinates. Default: False :param rounded: whether to round the ends of the lines. Default:False :return: None """ show = False if shiftPosition: x1 = int((self.getScreenX(position1[0]))) y1 = int((self.getScreenY(position1[1]))) x2 = int((self.getScreenX(position2[0]))) y2 = int((self.getScreenY(position2[1]))) else: x1 = int(position1[0]) y1 = int(position1[1]) x2 = int(position2[0]) y2 = int(position2[1]) if x1 < self.game.window.width and x1 > 0: if y1 < self.game.window.height and y1 > 0: show = True if x2 < self.game.window.width and x2 > 0: if y2 < self.game.window.height and y2 > 0: show = True if show: if self.usePygame: pygame.draw.line(self.display, color, (x1, y1), (x2, y2), int(width)) if rounded: pygame.draw.circle(self.diplay, color, (x1, y1), int(width / 2)) pygame.draw.circle(self.diplay, color, (x2, y2), int(width / 2)) else: tk_rgb = "#%02x%02x%02x" % color self.canvas.create_line(x1, y1, x2, y2, fill=tk_rgb, width=int(width)) if rounded: self.canvas.create_oval(x1 - width / 2, y1 - width / 2, x1 + width / 2, y1 + width / 2, fill=tk_rgb, outline="") self.canvas.create_oval(x2 - width / 2, y2 - width / 2, x2 + width / 2, y2 + width / 2, fill=tk_rgb, outline="") def showText(self, text, position, color, fontName="Times", fontSize=12, bold=False, italic=False, anchorCenter=False, shadowWidth=0, secondaryColor=(0, 0, 0), outlineWidth=0, shiftPosition=False): """ Wrapper method for tkinter and pygame showText methods :param position: the position of the upper right hand corner of the text if anchorCenter is false, if true, the center of text :param text: the text to display :param color: the color of the text in rgb :param secondaryColor: the color of the outline or shadow of the text in rgb. Default: black :param shiftPosition: whether to call the abstract method shift position on the passed coordinates. Default: False :param anchorCenter: whether to display text at center of passed coordinates or from the upper right corner. Default: False :param fontSize: default: 12 :param bold: default: False :param italic: default: False :param outlineWidth: default:0 :param shadowWidth: default: 0 :param fontName: default: "Times" :return: None """ if shiftPosition: if self.usePygame: if outlineWidth != 0: font = pygame.font.SysFont(fontName, fontSize, bold, italic) screenText = font.render(text, 1, secondaryColor) if anchorCenter: textW = screenText.get_width() textH = screenText.get_height() else: textW = 0 textH = 0 for angle in range(0, 361, int(8 / math.sqrt(outlineWidth)) + 1): x = outlineWidth * math.sin(angle) y = outlineWidth * math.cos(angle) self.display.blit( screenText, (int(self.getScreenX(position[0] - textW / 2 + x)), int(self.getScreenY(position[1] - textH / 2 + y)))) elif shadowWidth != 0: font = pygame.font.SysFont(fontName, fontSize, bold, italic) screenText = font.render(text, 1, secondaryColor) if anchorCenter: textW = screenText.get_width() textH = screenText.get_height() else: textW = 0 textH = 0 for shift in range(shadowWidth): self.display.blit( screenText, (int( self.getScreenX(position[0] - textW / 2 + shift)), int(self.getScreenY(position[1] - textH / 2)))) font = pygame.font.SysFont(fontName, fontSize, bold, italic) screenText = font.render(text, 1, color) if anchorCenter: textW = screenText.get_width() textH = screenText.get_height() else: textW = 0 textH = 0 self.display.blit( screenText, (int(self.getScreenX(position[0] - textW / 2)), int(self.getScreenY(position[1] - textH / 2)))) else: tk_rgb = "#%02x%02x%02x" % color fontString = fontName + " " + str(fontSize) if bold: fontString += " bold" if italic: fontString += " italic" if anchorCenter: if outlineWidth != 0: secondary_tk_rgb = "#%02x%02x%02x" % secondaryColor for angle in range( 0, 361, int(8 / math.sqrt(outlineWidth)) + 1): x = outlineWidth * math.sin(angle) y = outlineWidth * math.cos(angle) self.canvas.create_text( int(self.getScreenX(position[0] + x)), int(self.getScreenY(position[1] + y)), fill=secondary_tk_rgb, font=fontString, text=text) elif shadowWidth != 0: secondary_tk_rgb = "#%02x%02x%02x" % secondaryColor for shift in range(shadowWidth): self.canvas.create_text( int(self.getScreenX(position[0] + shift)), int(self.getScreenY(position[1])), fill=secondary_tk_rgb, font=fontString, text=text) self.canvas.create_text(int(self.getScreenX(position[0])), int(self.getScreenY(position[1])), fill=tk_rgb, font=fontString, text=text) else: if outlineWidth != 0: secondary_tk_rgb = "#%02x%02x%02x" % secondaryColor for angle in range( 0, 361, int(8 / math.sqrt(outlineWidth)) + 1): x = outlineWidth * math.sin(angle) y = outlineWidth * math.cos(angle) self.canvas.create_text( int(self.getScreenX(position[0] + x)), int(self.getScreenY(position[1] + y)), fill=secondary_tk_rgb, font=fontString, text=text, anchor=NW) elif shadowWidth != 0: secondary_tk_rgb = "#%02x%02x%02x" % secondaryColor for shift in range(shadowWidth): self.canvas.create_text( int(self.getScreenX(position[0] + shift)), int(self.getScreenY(position[1])), fill=secondary_tk_rgb, font=fontString, text=text, anchor=NW) self.canvas.create_text(int(self.getScreenX(position[0])), int(self.getScreenY(position[1])), fill=tk_rgb, font=fontString, text=text, anchor=NW) else: if self.usePygame: if outlineWidth != 0: font = pygame.font.SysFont(fontName, fontSize, bold, italic) screenText = font.render(text, 1, secondaryColor) if anchorCenter: textW = screenText.get_width() textH = screenText.get_height() else: textW = 0 textH = 0 for angle in range(0, 361, int(8 / math.sqrt(outlineWidth)) + 1): x = outlineWidth * math.sin(angle) y = outlineWidth * math.cos(angle) self.display.blit(screenText, (int(position[0] - textW / 2) + x, int(position[1] - textH / 2) + y)) elif shadowWidth != 0: font = pygame.font.SysFont(fontName, fontSize, bold, italic) screenText = font.render(text, 1, secondaryColor) if anchorCenter: textW = screenText.get_width() textH = screenText.get_height() else: textW = 0 textH = 0 for shift in range(shadowWidth): self.display.blit( screenText, (int(position[0] - textW / 2) + shift, int(position[1] - textH / 2))) font = pygame.font.SysFont(fontName, fontSize, bold, italic) screenText = font.render(text, 1, color) if anchorCenter: textW = screenText.get_width() textH = screenText.get_height() else: textW = 0 textH = 0 self.display.blit(screenText, (int(position[0] - textW / 2), int(position[1] - textH / 2))) else: tk_rgb = "#%02x%02x%02x" % color fontString = fontName + " " + str(fontSize) if bold: fontString += " bold" if italic: fontString += " italic" if anchorCenter: if outlineWidth != 0: secondary_tk_rgb = "#%02x%02x%02x" % secondaryColor for angle in range( 0, 361, int(8 / math.sqrt(outlineWidth)) + 1): x = outlineWidth * math.sin(angle) y = outlineWidth * math.cos(angle) self.canvas.create_text(position[0] + x, position[1] + y, fill=secondary_tk_rgb, font=fontString, text=text) elif shadowWidth != 0: secondary_tk_rgb = "#%02x%02x%02x" % secondaryColor for shift in range(shadowWidth): self.canvas.create_text(position[0] + shift, position[1], fill=secondary_tk_rgb, font=fontString, text=text) self.canvas.create_text(position[0], position[1], fill=tk_rgb, font=fontString, text=text) else: if outlineWidth != 0: secondary_tk_rgb = "#%02x%02x%02x" % secondaryColor for angle in range( 0, 361, int(8 / math.sqrt(outlineWidth)) + 1): x = outlineWidth * math.sin(angle) y = outlineWidth * math.cos(angle) self.canvas.create_text(position[0] + x, position[1] + y, fill=secondary_tk_rgb, font=fontString, text=text, anchor=NW) elif shadowWidth != 0: secondary_tk_rgb = "#%02x%02x%02x" % secondaryColor for shift in range(shadowWidth): self.canvas.create_text(position[0] + shift, position[1], fill=secondary_tk_rgb, font=fontString, text=text, anchor=NW) self.canvas.create_text(position[0], position[1], fill=tk_rgb, font=fontString, text=text, anchor=NW) def showImage(self, image, position, anchorCenter=False, shiftPosition=False): """ Wrapper method for tkinter and pygame showImage methods :param image: the Pillow image to be displayed :param position: the position of the upper right hand corner of the text if anchorCenter is false, if true, the center of text :param anchorCenter: whether to display text at center of passed coordinates or from the upper right corner. Default: False :param shiftPosition: whether to call the abstract method shift position on the passed coordinates. Default: False :return: None """ if self.usePygame: imageW = image.get_width() imageH = image.get_height() else: imageW, imageH = image.size if shiftPosition: x = int(self.getScreenX(position[0])) y = int(self.getScreenY(position[1])) else: x = int(position[0]) y = int(position[1]) show = True if x > self.game.window.width: show = False if x + imageW < 0: show = False if y > self.game.window.height: show = False if y + imageH < 0: show = False if self.usePygame: if not anchorCenter: imageW = 0 imageH = 0 else: if anchorCenter: imageW = 0 imageH = 0 if show: if self.usePygame: self.display.blit(image, (x - imageW / 2, y - imageH / 2)) else: image = ImageTk.PhotoImage(image) self.tkImageList.append(image) self.canvas.create_image((x + imageW / 2, y + imageH / 2), image=image) def showPolygon(self, pointList, color, position=(0, 0), shiftPosition=False, secondaryColor=(0, 0, 0), width=0): """ Wrapper method for tkinter and pygame showPolygon methods doesnt not display polygons that are bigger than the screen :param pointList: list of points to be displayed :param position: the vector to shift all points in pointList by, this value is affected by shiftPosition. Default: (0,0) :param color: the color of the polygon in rgb :param width: the width of the outline. Default: 0 :param secondaryColor: the color of the outline of the polygon in rgb. Default: black :param shiftPosition: whether to call the abstract method shift position on the passed coordinates. Default: False :return: None """ points = [] for index in range(len(pointList)): if shiftPosition: points.append( (int(self.getScreenX(pointList[index][0] + position[0])), int(self.getScreenY(pointList[index][1] + position[1])))) else: points.append((int(pointList[index][0] + position[0]), int(pointList[index][1] + position[1]))) show = False for point in points: if not show: if point[0] < self.game.window.width and point[0] > 0: if point[1] < self.game.window.height and point[1] > 0: show = True if show: if self.usePygame: pygame.draw.polygon(self.display, color, points) if width: pygame.draw.polygon(self.display, secondaryColor, points, width) else: tk_rgb = "#%02x%02x%02x" % color secondary_tk_rgb = "#%02x%02x%02x" % secondaryColor self.canvas.create_polygon(points, outline=secondary_tk_rgb, fill=tk_rgb, width=width) def showCircle(self, position, radius, color, width=0, secondaryColor=(0, 0, 0), shiftPosition=False): """ Wrapper method for tkinter and pygame showCircle methods :param the center position of the circle :param color: the color of the circle in rgb :param width: the width of the outline. Default: 0 :param secondaryColor: the color of the outline of the circle in rgb. Default: black :param shiftPosition: whether to call the abstract method shift position on the passed coordinates. Default: False :return: None """ if shiftPosition: width = int(self.getScreenX(width) - self.getScreenX(0)) radius = int(self.getScreenX(radius) - self.getScreenX(0)) + 1 x = int(self.getScreenX(position[0])) y = int(self.getScreenY(position[1])) else: width = int(width) radius = int(radius + 1) x = int(position[0]) y = int(position[1]) show = True if x - radius / 2 > self.game.window.width: show = False if x + radius / 2 < 0: show = False if y - radius / 2 > self.game.window.height: show = False if y + radius / 2 < 0: show = False if show: if self.usePygame: pygame.draw.circle(self.display, color, (x, y), radius) if int(width) != 0: pygame.draw.circle(self.display, secondaryColor, (x, y), radius, width) else: tk_rgb = "#%02x%02x%02x" % color if width: secondary_tk_rgb = "#%02x%02x%02x" % secondaryColor else: secondary_tk_rgb = "" self.canvas.create_oval(x - radius, y - radius, x + radius, y + radius, fill=tk_rgb, width=width, outline=secondary_tk_rgb) def setBackgroundColor(self, color): """ sets the color of the background :param color: the desired background color :return: None """ self.backgroundColor = color def setDrawLayer(self, layer): """ sets the layer at which the draw method is called :param layer: the desired layer :return: None """ self.customDrawLayer = layer def getBackgroundColor(self): """ gets the color of the background :return: the background color """ return self.backgroundColor def getDrawLayer(self): """ gets the layer at which the draw method is called :return: the draw layer """ return self.customDrawLayer def update(self, width, height): """ sets the width and height of the canvas :param width: the desired width :param height: the desired height :return: None """ self.f.config(width=width, height=height) if self.usePygame: self.diplay = pygame.display.set_mode((width, height)) else: self.canvas.config(width=width, height=height) def scaleImage(self, image, scale): """ scales an image by the given amout :param image: a Pillow image :param scale: the amount to scale the image :return: the scaled Pillow image """ newWidth = image.size[0] * scale wPercent = (newWidth / float(image.size[0])) hSize = int((float(image.size[1]) * float(wPercent))) scaledImage = image.resize((int(newWidth), int(hSize)), PIL.Image.ANTIALIAS) return scaledImage def rotate(self, image, angle): """ rotates an image by the given angle in degrees :param image: a Pillow image :param angle: the angle in degrees :return: the rotated Pillow image """ if self.usePygame: return pygame.transform.rotate(image, angle) else: return self.rotatePIL(image, angle) def rotatePIL(self, image, angle): """ wrapper method for the imageString.rotate() method which properly handles transparent pixels and large images :param image: a Pillow image :param angle: the angle in degrees :return: the rotated Pillow image """ startSize = image.size imageString = image.convert('RGBA') rotatedImage = imageString.rotate(angle, expand=0).resize(startSize) finalImage = Image.new("RGBA", startSize, (255, 255, 255, 0)) finalImage.paste(rotatedImage, (0, 0), rotatedImage) return finalImage def convertToDisplayFormat(self, image): """ converts image to the proper format depending on whether you are using pygame :param image: a Pillow image :return: A pygame image if using pygame, a Pillow otherwise """ if self.usePygame: imageBytes = image.convert('RGBA').tobytes("raw", 'RGBA') convertedImage = pygame.image.fromstring(imageBytes, image.size, 'RGBA') else: convertedImage = image return convertedImage def manipulateImage(self, image, scale, angle): """ wrapper method to scale, rotate, and convert an image :param image: a Pillow image :param scale: the amount to scale the image :param angle: the angle in degrees :return: A pygame image if using pygame, a Pillow otherwise """ scaledImage = self.scaleImage(image, scale) rotatedImage = self.rotatePIL(scaledImage, angle) finalImage = self.convertToDisplayFormat(rotatedImage) return finalImage @abstractmethod def getScreenX(self, x): """ abstract method to be overwritten by drawingEngine. Called by all draw methods when shiftPosition=True :param x: an x coordinate :return: x """ return x @abstractmethod def getScreenY(self, y): """ abstract method to be overwritten by drawingEngine. Called by all draw methods when shiftPosition=True :param y: an y coordinate :return: y """ return y
from tkinter import Tk as makescreen, Canvas, font from sql import * # MACROS ON = 'ON' OFF = 'OFF' RUN = 'RUN' screen = makescreen() canvas = Canvas(screen, width=500, height=500) screen.update() canvas.pack() rect = canvas.create_rectangle(100, 100, 400, 400, fill='yellow') status_font = font.Font(family="맑은 고딕", size=30) status_text = canvas.create_text(250, 200, text='status', font=status_font) time_font = font.Font(family="맑은 고딕", size=40) time_text = canvas.create_text(250, 300, text='time', font=time_font) seatnumber = '0' building = "'Soongsil Univ'" def update_canvas(): global rect, status_text, time_text sql = SQL() data = sql.select_where( 'ssu_table', 'seat_number=' + seatnumber + " AND name=" + building) status = data[1]
def setUpCanvas(root): root.title("SUDOKU: A tk/Phyton Graphics Program by Arianna Sze") canvas=Canvas(root,width=1290,height=710,bg='black') canvas.pack(expand=YES,fill=BOTH) return canvas
print("please enter a smaller number for x, y, and z") return finished_num except OverflowError: print("please enter a smaller numbers for your output :) ") check_that_size = MathematicalClass() main_application.title('Code Generation tool') pygame.mixer.init() pygame.mixer.music.load("FunHouse.mp3") pygame.mixer.music.play(loops=-1) code_generated = '' HEIGHT = 1024 WIDTH = 1500 canvas = Canvas(main_application, height=HEIGHT, width=WIDTH) canvas.pack() main_application.iconbitmap('icon.ico') background_image = PhotoImage(file='cyberlovers.png') background_label = Label(canvas, image=background_image) background_label.place(relwidth=1.2, relheight=1.2) info = "Enter whether you are on" + "\n" + "light side or dark side" + "\n" "even for yes and odd for no" + "\n" + "do you wish to echo back the completion?" def ask_quit(): if messagebox.askokcancel("Quit", "Would you like to generate code some other time?"): main_application.destroy() emp_ty = "" min_val = .001
def jouluvana(aken, vana_pilt): """Create santa, a message and make both move with another function.""" vana = Canvas(aken, width=90, height=70, bg="blue", highlightthickness=0) vana.create_image(45, 35, image=vana_pilt) vana.pack() tekst = Label(aken, text="Kõik kingid kuni 50% allahinnatud!", bg="blue", font=("Helvetica", 16), fg="white") tekst.pack() vana_liikuma(vana, 650, 200, tekst)
def main(): '''runs the program''' square_width = 64 num_cols = 7 num_rows = 6 canvas_width = (num_cols+1)*square_width canvas_height = (num_rows+1)*square_width window = Tk() window.configure(background='black') window.title("DynaBLASTER") window.resizable(0,0) #removes maximize option #window.iconbitmap('icon.ico') #window.tk.call('tk', 'scaling', 20.0) canvas = Canvas(window, width=canvas_width, highlightthickness=0, height=canvas_height, background='#717171') canvas.grid(row=1,column=0, columnspan=5) graphics = Graphics(canvas, num_rows, num_cols, square_width, window) board = Board(canvas, square_width, num_rows, num_cols, canvas_width, canvas_height) col=0 row=0 player1 = Player(canvas, board, square_width, graphics, col, row) col = graphics.cols - 3 row = graphics.rows - 3 player2 = Player(canvas, board, square_width, graphics, col, row) # Import settings from bindings file bindings_file = open('bindings.json') p1_bindings, p2_bindings, gen_bindings = json.load(bindings_file) window.bind(key_release_of(p1_bindings["Up"]), lambda event:player1.key_release('Up')) window.bind(key_release_of(p1_bindings["Down"]), lambda event:player1.key_release('Down')) window.bind(key_release_of(p1_bindings["Left"]), lambda event:player1.key_release('Left')) window.bind(key_release_of(p1_bindings["Right"]), lambda event:player1.key_release('Right')) window.bind(p1_bindings["Up"], lambda event:player1.key_press('Up')) window.bind(p1_bindings["Down"],lambda event:player1.key_press('Down')) window.bind(p1_bindings["Left"], lambda event:player1.key_press('Left')) window.bind(p1_bindings["Right"], lambda event:player1.key_press('Right')) window.bind(p1_bindings["Bomb"], player1.place_bomb) window.bind(key_release_of(p2_bindings["Up"]), lambda event:player2.key_release('Up')) window.bind(key_release_of(p2_bindings["Down"]), lambda event:player2.key_release('Down')) window.bind(key_release_of(p2_bindings["Left"]), lambda event:player2.key_release('Left')) window.bind(key_release_of(p2_bindings["Right"]), lambda event:player2.key_release('Right')) window.bind(p2_bindings["Up"], lambda event:player2.key_press('Up')) window.bind(p2_bindings["Down"], lambda event:player2.key_press('Down')) window.bind(p2_bindings["Left"], lambda event:player2.key_press('Left')) window.bind(p2_bindings["Right"], lambda event:player2.key_press('Right')) window.bind(p2_bindings["Bomb"], player2.place_bomb) window.bind(gen_bindings["Pause"], lambda event:pause_game(player1, player2, graphics)) window.mainloop()
class CameraView(View): def __init__(self, params): super(CameraView, self).__init__(params) self._multiplier = int(params["multiplier"]) if "multiplier" in params else 1 self._multiplier = max(self._multiplier, 1) self._tk = Tk() self._canvas = Canvas(self._tk, width=80 * self._multiplier, height=60 * self._multiplier) self._tk.title("Camera view") self._tk.resizable(width=False, height=False) self._canvas.pack(side=tkinter.LEFT, fill=tkinter.BOTH, expand=True) self._tk.protocol("WM_DELETE_WINDOW", self.on_press_close) self._base_dir = "camera_" + str(int(time.time() * 1000)) os.makedirs(self._base_dir) def run(self): super(CameraView, self).run() self._tk.mainloop() def on_new_input(self): try: hex_str = self.get_input() img = self._get_image(hex_str) except Exception as e: logging.debug(str(e)) return if img is None: return bmp = ImageTk.BitmapImage(image=img, foreground="white", background="black") self._canvas.create_image(0, 0, image=bmp, anchor=tkinter.NW) self._tk_image = bmp img.save(self._base_dir + "/" + str(int(time.time() * 1000)) + ".png") def on_dismiss(self): self._tk.after_idle(self.on_press_close) def on_press_close(self): self._tk.destroy() self.join_io_thread() def _get_image(self, hex_str) -> Image: try: hex_data = binascii.unhexlify(hex_str) # Invert data from MCU hex_data = bytes([~h & 0xFF for h in hex_data]) except TypeError as e: logging.debug(str(e)) return img = Image.frombytes(mode="1", size=(80, 60), data=hex_data) img = img.resize((80 * self._multiplier, 60 * self._multiplier)) return img