def pilve_pildid(): """Load two pictures of clouds and return them.""" pilve_pilt = PhotoImage(file="vihmaPilv.png") pilve_pilt = pilve_pilt.subsample(4, 4) teine_pilv = PhotoImage(file="tavalinePilv.png") teine_pilv = teine_pilv.subsample(7, 7) return pilve_pilt, teine_pilv
def __init__(self, labyrinthe): # ------------ Coordonnées sur écran ------------ self.coord_x = labyrinthe.robot_start_x * labyrinthe.largeur_carre self.coord_y = labyrinthe.robot_start_y * labyrinthe.hauteur_carre # ------------ Coordonnées logique ------------ self.logic_coord_x = labyrinthe.robot_start_y self.logic_coord_y = labyrinthe.robot_start_x # ------------ Chargement des images ------------ self.image_up = PhotoImage(file="up.gif") self.image_down = PhotoImage(file="down.gif") self.image_right = PhotoImage(file="right.gif") self.image_left = PhotoImage(file="left.gif") # ------------ Mise à l'échelle ------------ self.displayimage_up = self.image_up.subsample(2, 2) self.displayimage_down = self.image_down.subsample(2, 2) self.displayimage_right = self.image_right.subsample(2, 2) self.displayimage_left = self.image_left.subsample(2, 2) # ------------ Création de l'image ------------ self.display = labyrinthe.laby.create_image(self.coord_x, self.coord_y, anchor='nw', image=self.displayimage_up) self.ref_labyrinthe = labyrinthe # ------------ Variables pour l'animation de déplacement ------------ self.anim_count = 0 self.anim = False # ------------ Variables pour l'algorithme ------------ self.direction_actuel = 'Up' # ATTENTION INUTILISE self.direction_ancienne = 'Up'
def format_image(self, file, ratio): assert (ratio >= 1), "Ratio must be bigger than 1!" my_path = "images/" + str(file) + ".gif" image = PhotoImage(file = my_path) sfx = image.width() / self.size sfy = image.height() / self.size sf = int(min(sfx, sfy) * ratio) new_image = image.subsample(sf, sf) return new_image
def draw_danger_levels(canvas, x, y): img = PhotoImage(width=WIDTH, height=HEIGHT) canvas.create_image((WIDTH/2, HEIGHT//2), image=img, state="normal") for j in range(0, HEIGHT): for i in range(0, WIDTH): # RGB = red, green, blue # диапазон цвета: 0..255, 0x00..0xFF distance = sqrt((i-x)**2 + (j-y)**2) / 5 # две роли оператора % # 1 - форматирование строки # 2 - остаток от деления img.put("#%02x%02x%02x" % (255/(int(distance) % 256 + 1), 0, 0), (i, j)) return img
def buttonFun(): boxDisplay['text'] = comboChoices[i+1] boxPics = [] boxIDs = root.boxes[i] for j in range(boxLen): pkmnNum = boxIDs[j] pic = PhotoImage(file='res/{:0>3}.gif'.format(pkmnNum)) boxPics.append(pic) boxDisplay.boxPics = boxPics #avoiding garbage collection for pic in boxDisplay.winfo_children(): pic.destroy() for j in range(4): for k in range(5): pic = ttk.Label(boxDisplay, image=boxPics[5*j+k]) pic.grid(row=j, column=k)
class Jul: def __init__(self, root, x1, y1, x2, y2): t = time.time() self.img = PhotoImage(width=wid, height=hei) canv = Canvas(root, width = wid, height = hei) canv.pack() canv.create_image(0, 0, image = self.img, anchor=NW) dx = abs(x2-x1)/wid dy = abs(y2-y1)/hei #c = complex(-0.8, 0.156) #c = complex(-0.74543,+0.11301) #c = complex(-0.1,0.651) #c = complex(-0.70176,-0.3842) c = complex(-0.835,-0.2321) #c = complex(-0.74434, -0.10772) #c = complex(-0.62772, 0.42193) y = y1 for j in range(hei): line = '{' x = x1 for i in range(wid): x = x + dx a = complex(x, y) for k in range(maxiter): a = a*a + c if(abs(a) > blowup): break if(k == maxiter-1): #line += '#%02x%02x%02x ' % (255,255,255) line += '#%02x%02x%02x ' % (0,0,0) else: line += '#%02x%02x%02x ' % color(k) line += '}' self.img.put(line, (0, j)) canv.update() y = y - dy print(time.time() - t)
def setupSelectMachineButtons(self): numDevices = len(self.supportedDevices) numColumns = 3 numRows = math.ceil((numDevices+1)/3) self.photo = PhotoImage(file="eguana.gif") self.photo = self.photo.subsample(2); self.photo_label = Label(self.selectMachineFrame,image=self.photo,borderwidth=0,highlightthickness=0) self.photo_label.configure(bg='#FADC46') self.photo_label.grid(row=int(numRows/2),column=1, sticky=N+S+E+W,padx=2,pady =2) self.photo_label.image = self.photo index = 0 for i in range(numRows): for j in range(numColumns): if not(j == 1 and i == int(numRows/2)) and (index < numDevices): device = self.supportedDevices[index] b = Button(self.selectMachineFrame,text=device.name,relief=RAISED, command=lambda device=device :self.machineButtonPressed(device)) b.grid(row=i,column=j, sticky=N+S+E+W,padx=2,pady =2) index += 1 for i in range(numRows): self.selectMachineFrame.rowconfigure(i,weight=1) for i in range(numColumns): self.selectMachineFrame.columnconfigure(i,weight=1)
def __init__(self,parent): """ initialise tkinter with default parameters """ Tkinter.Tk.__init__(self,parent) self.parent = parent self.appWidth = 1900 # initial values self.appHeight = 1000 self.cell_width = 4 self.cell_height = 3 self.fname = '' self.screenWidth = self.winfo_screenwidth() self.screenHeight = self.winfo_screenheight() self.configure(bg='black') self.geometry('%dx%d+%d+%d' % (self.appWidth, self.appHeight, self.screenWidth - self.appWidth - 0, self.screenHeight - self.appHeight - 0)) WIDTH = self.appWidth HEIGHT = self.appHeight self.canvas = Canvas(self, width=WIDTH, height=HEIGHT, bg="#000000") self.canvas.pack() self.img = PhotoImage(width=WIDTH, height=HEIGHT) self.canvas.create_image(( WIDTH/2, HEIGHT/2), image=self.img, state="normal") #self.TEST_sin() # testing - draws a sin wave self.appWidth = 1900 # canvas.width self.appHeight = 1000 self.canvas.pack()
def __init__(self, thread): # set up screen, width = 512, height = 256 self.mythread = thread self.screen = Tk() self.screen.title("Jarvis Simulator") self.screen.geometry("512x256+1600+500") self.screen.wm_maxsize(width=512, height=256) self.screen.wm_minsize(width=512, height=256) self.screen.wm_resizable(width=False, height=False) self.image = PhotoImage(width = 512, height = 256) self.label = Label(self.screen, image=self.image) self.label.grid() # set up keyboard for c in self.Keycodes.keys(): exec("self.screen.bind(\"<%s>\", self.%s)" % (c, c)) self.screen.bind("<Any-KeyPress>", self.KeyPressed) self.screen.bind("<Any-KeyRelease>", self.KeyReleased) system("xset r off") self.screen.protocol("WM_DELETE_WINDOW", self.delete_callback)
class Mandel: def __init__(self, root, x1, y1, x2, y2): t = time.time() self.img = PhotoImage(width=wid, height=hei) canv = Canvas(root, width = wid, height = hei) canv.pack() canv.create_image(0, 0, image = self.img, anchor=NW) dx = abs(x2-x1)/wid dy = abs(y2-y1)/hei y = y1 for j in range(hei): line = '{' x = x1 for i in range(wid): x = x + dx c = complex(x, y) a = 0 for k in range(maxiter): a = a**2 + c if(abs(a) > blowup): break if(k == maxiter-1): line += '#%02x%02x%02x ' % (255,255,255) else: line += '#%02x%02x%02x ' % color(k) line += '}' self.img.put(line, (0, j)) canv.update() y = y - dy print(time.time() - t)
def set_next_image_to_frame(self, event=None): previous_text = self.entry_set.get() if self.__current_tk_image: self.__img_db[self.__current_dirname]['dir'] = previous_text # Delete tk images self.canvas.delete(tk.ALL) self.__current_tk_image = [] try: self.__current_dirname = self.__dirnames.pop() except IndexError: return self.__end_configuration() img_list = self.__img_db[self.__current_dirname]["thumbs"] self.entry_set.delete(0, len(previous_text)) self.entry_set.insert(0, self.__current_dirname) border = 10 cpt = 0 for image in img_list: imgobj = PhotoImage(file=image) _x = imgobj.width()/2 + imgobj.width()*(cpt % 2) + border _y = imgobj.height()/2 + imgobj.height()*int(cpt/2) + border cpt += 1 self.canvas.create_image(_x, _y, image=imgobj) self.__current_tk_image.append(imgobj) self.entry_set.focus_set()
def display_mandelbrot(): width = 700 height = 700 window = Tk() canvas = Canvas(window, width=width, height=height, bg="#ffffff") canvas.pack() img = PhotoImage(width=width, height=height) canvas.create_image((width//2, height//2), image=img, state="normal") real_range = (-2.25, .75) imag_range = (-1.5, 1.5) precision = 0.003 max_iterations = 20 real_to_x_mapper = make_linear_mapper(real_range, (0, width), int_out=True) imag_to_y_mapper = make_linear_mapper(imag_range, (0, height), int_out=True) color_mapper = make_color_mapper(max_iterations) m_set = calc_mandelbrot_for_range(real_range[0], real_range[1], imag_range[0], imag_range[1], precision, max_iterations) for item in m_set: point, result = item (x, y) = point x_pixel = real_to_x_mapper(x) y_pixel = imag_to_y_mapper(y) (in_mandelbrot_set, z_cur, steps_taken) = result color = "#000000" if not in_mandelbrot_set: color = color_mapper(steps_taken) print("plotting: {}, {} -> {}".format(x_pixel, y_pixel, color)) img.put(color, (x_pixel, y_pixel)) mainloop()
def __init__(self, parent): # Set up the initial variables/frame stuff self.parent = parent self.parent.geometry("378x288") self.frame = Frame(parent) self.memory_listener = MemoryListener(self.mem_action) self.print_listener = PrintListener(self.print_action) self.width = 378 self.height = 288 self.img = PhotoImage(width=self.width, height=self.height) self.canvas = None self.number_of_chars = 0 self.x = 0 self.y = 0 self.initUI()
def setupTopBar(self): self.openButton3D = Button(self.frame,text="Select Directory for 3D EMA",relief=RAISED,command=self.askDirectory) self.openButton3D.grid(row=0,column=0, sticky=N+S+E+W,padx=2,pady =2) self.openButton2D = Button(self.frame,text="Select Directory for 2D EMA",relief=RAISED,command=self.askDirectory); self.openButton2D.grid(row=2,column=2, sticky=N+S+E+W,padx=2,pady =2) self.p1Button = Button(self.frame,text="Placeholder",relief=RAISED) self.p1Button.grid(row=0,column=1, sticky=N+S+E+W,padx=2,pady =2) self.p2Button = Button(self.frame,text="Placeholder",relief=RAISED) self.p2Button.grid(row=0,column=2, sticky=N+S+E+W,padx=2,pady =2) self.p3Button = Button(self.frame,text="Placeholder",relief=RAISED) self.p3Button.grid(row=1,column=0, sticky=N+S+E+W,padx=2,pady =2) self.p4Button = Button(self.frame,text="Placeholder",relief=RAISED) self.p4Button.grid(row=1,column=2, sticky=N+S+E+W,padx=2,pady =2) self.p5Button = Button(self.frame,text="Placeholder",relief=RAISED) self.p5Button.grid(row=2,column=0, sticky=N+S+E+W,padx=2,pady =2) self.p6Button = Button(self.frame,text="Placeholder",relief=RAISED) self.p6Button.grid(row=2,column=1, sticky=N+S+E+W,padx=2,pady =2) self.openButton3D.bind('<Motion>',self.cursorPosition) self.openButton2D.bind('<Motion>',self.cursorPosition) self.photo = PhotoImage(file="eguana.gif") self.photo = self.photo.subsample(2); self.photo_label = Label(self.frame,image=self.photo,borderwidth=0,highlightthickness=0) self.photo_label.configure(bg='#FADC46') self.photo_label.grid(row=1,column=1, sticky=N+S+E+W,padx=2,pady =2) self.photo_label.image = self.photo self.frame.columnconfigure(0, weight=1) self.frame.columnconfigure(1, weight=1) self.frame.columnconfigure(2, weight=1) self.frame.rowconfigure(0, weight=1) self.frame.rowconfigure(1, weight=1) self.frame.rowconfigure(2, weight=1)
def reklaam_start(taust): """Close the previous window and create a new one for the commercial. The previous window will be closed after the button is pressed. Pictures are made for functions and functions are called out for the commercial. """ taust.destroy() aken = Tk() aken.title("Reklaam") aken.geometry("720x480") aken["bg"] = "Blue" vana_pilt = PhotoImage(file="jouluvana_saanis.png") vana_pilt = vana_pilt.subsample(4, 4) lume_pilt = PhotoImage(file="snowflake.png") lume_pilt = lume_pilt.subsample(25, 25) kingi_pilt = PhotoImage(file="gift.png") kingi_pilt = kingi_pilt.subsample(15, 15) aken.grid() pilve_list = pilve_pildid() loo_pilv(aken, pilve_list, 7) jouluvana(aken, vana_pilt) loo_lumi(aken, lume_pilt, kingi_pilt) aken.mainloop()
con.close() def callPreviousScreen(): dest.destroy() # same loc mein file ho toh ('nayi_screen_ka_naam.py') else ( python 'nayi_screen_ka_naam'.py) os.system('python prj.py') #DELETE Stu. dest = Tk() dest.title("Delete Stu.") dest.geometry("1280x970+0+0") C = Canvas(dest, bg="blue", height=120, width=120) filename = PhotoImage(file="stu1.gif") background_label = Label(dest, image=filename) background_label.place(x=0, y=0, relwidth=1, relheight=1) C.pack() lb_heading = Label(dest, text=" Delete Student Details ", width=27, font=('Beauty Mountains Personal Use', 56), bg='light green') lb_heading.place(x=90, y=20) lblDeleteRno = Label(dest, text="Enter rno: ", font=('Beauty Mountains Personal Use', 28)) entDeleteRno = Entry(dest, bd=5, font=('arial', 18, 'bold'))
def main(): def restart(end_canva): end_canva.destroy() main() let_num = IntVar() errors = IntVar() errors.set(1) if errors.get() > 11: errors.set(0) canva = Canvas(root, width=500, height=500, bg="#edf5e1") file = open("words.txt", "r") words = file.readlines() file.close() firs_img = PhotoImage(file="1.png") first_img_label = Label(root, image=firs_img, bg="#edf5e1") first_img_label.image = firs_img canva.create_window(250, 100, window=first_img_label) while True: right_word = random.choice(words).replace("\n", "").lower() if len(right_word) > 4: break word = [] right_list = [] ind = 0 for char in right_word: word.append("_") right_list.append(char) ind += 1 word_label = Label(root, text=" ".join(word), font=("Mistral", 14), width=500, bg="#edf5e1") canva.create_window((250, 250), window=word_label) def game_ended(text): canva.destroy() end_canva = Canvas(root, width=500, height=500, bg="#edf5e1") play_again = PhotoImage(file="play_again.png") if text == f"YOU LOST!\nTHE RIGHT WORD WAS {right_word.upper()}": hanged = PhotoImage(file="11.png") hanged_label = Label(root, image=hanged) hanged_label.image = hanged end_canva.create_window(250, 100, window=hanged_label) quit_game = PhotoImage(file="quit_game.png") button = Button( root, image=play_again, command=lambda: restart(end_canva), border=0, activebackground="#edf5e1", bg="#edf5e1", ) button.image = play_again close_button = Button( root, image=quit_game, command=root.destroy, activebackground="#edf5e1", bg="#edf5e1", border=0, ) close_button.image = quit_game end_canva.create_window(180, 300, window=button) end_canva.create_window(330, 300, window=close_button) end_label = Label( root, bg="#edf5e1", text=text, font=("Mistral", 14), ) end_canva.create_window(250, 200, window=end_label) end_canva.grid() def check(letter, button): is_in = False button.destroy() for index in range(len(right_list)): if letter == right_list[index]: word[index] = letter.upper() is_in = True let_num.set(let_num.get() + 1) word_label = Label(root, text=" ".join(word), font=("Mistral", 14), bg="#edf5e1", width=500) canva.create_window((250, 250), window=word_label) if not is_in: errors_value = StringVar() errors_value.set(errors.get() + 1) path = errors_value + ".png" errors.set(errors.get() + 1) img = PhotoImage(file=path) img_label = Label(root, image=img, bg="#edf5e1") img_label.image = img canva.create_window(250, 100, window=img_label) if errors.get() == 11: game_ended(f"YOU LOST!\nTHE RIGHT WORD WAS {right_word.upper()}") if let_num.get() == len(right_list): game_ended("YOU WON!") a = PhotoImage(file="a.png") b = PhotoImage(file="b.png") c = PhotoImage(file="c.png") d = PhotoImage(file="d.png") e = PhotoImage(file="e.png") f = PhotoImage(file="f.png") g = PhotoImage(file="g.png") h = PhotoImage(file="h.png") i = PhotoImage(file="i.png") j = PhotoImage(file="j.png") k = PhotoImage(file="k.png") l = PhotoImage(file="l.png") m = PhotoImage(file="m.png") n = PhotoImage(file="n.png") o = PhotoImage(file="o.png") p = PhotoImage(file="p.png") q = PhotoImage(file="q.png") r = PhotoImage(file="r.png") s = PhotoImage(file="s.png") t = PhotoImage(file="t.png") u = PhotoImage(file="u.png") v = PhotoImage(file="v.png") w = PhotoImage(file="w.png") x = PhotoImage(file="x.png") y = PhotoImage(file="y.png") z = PhotoImage(file="z.png") a_button = Button(root, command=lambda: check("a", a_button), image=a, border=0, bg="#edf5e1") a_button.image = a b_button = Button( root, command=lambda: check("b", b_button), image=b, border=0, bg="#edf5e1", activebackground="#edf5e1", ) b_button.image = b c_button = Button( root, command=lambda: check("c", c_button), image=c, border=0, bg="#edf5e1", activebackground="#edf5e1", ) c_button.image = c d_button = Button( root, command=lambda: check("d", d_button), image=d, border=0, bg="#edf5e1", activebackground="#edf5e1", ) d_button.image = d e_button = Button( root, command=lambda: check("e", e_button), image=e, border=0, bg="#edf5e1", activebackground="#edf5e1", ) e_button.image = e f_button = Button( root, command=lambda: check("f", f_button), image=f, border=0, bg="#edf5e1", activebackground="#edf5e1", ) f_button.image = f g_button = Button( root, command=lambda: check("g", g_button), image=g, border=0, bg="#edf5e1", activebackground="#edf5e1", ) g_button.image = g h_button = Button( root, command=lambda: check("h", h_button), image=h, border=0, bg="#edf5e1", activebackground="#edf5e1", ) h_button.image = h i_button = Button( root, command=lambda: check("i", i_button), image=i, border=0, bg="#edf5e1", activebackground="#edf5e1", ) i_button.image = i j_button = Button( root, command=lambda: check("j", j_button), image=j, border=0, bg="#edf5e1", activebackground="#edf5e1", ) j_button.image = j k_button = Button( root, command=lambda: check("k", k_button), image=k, border=0, bg="#edf5e1", activebackground="#edf5e1", ) k_button.image = k l_button = Button( root, command=lambda: check("l", l_button), image=l, border=0, bg="#edf5e1", activebackground="#edf5e1", ) l_button.image = l m_button = Button( root, command=lambda: check("m", m_button), image=m, border=0, bg="#edf5e1", activebackground="#edf5e1", ) m_button.image = m n_button = Button( root, command=lambda: check("n", n_button), image=n, border=0, bg="#edf5e1", activebackground="#edf5e1", ) n_button.image = n o_button = Button( root, command=lambda: check("o", o_button), image=o, border=0, bg="#edf5e1", activebackground="#edf5e1", ) o_button.image = o p_button = Button( root, command=lambda: check("p", p_button), image=p, border=0, bg="#edf5e1", activebackground="#edf5e1", ) p_button.image = p q_button = Button( root, command=lambda: check("q", q_button), image=q, border=0, bg="#edf5e1", activebackground="#edf5e1", ) q_button.image = q r_button = Button( root, command=lambda: check("r", r_button), image=r, border=0, bg="#edf5e1", activebackground="#edf5e1", ) r_button.image = r s_button = Button( root, command=lambda: check("s", s_button), image=s, border=0, bg="#edf5e1", activebackground="#edf5e1", ) s_button.image = s t_button = Button( root, command=lambda: check("t", t_button), image=t, border=0, bg="#edf5e1", activebackground="#edf5e1", ) t_button.image = t u_button = Button( root, command=lambda: check("u", u_button), image=u, border=0, bg="#edf5e1", activebackground="#edf5e1", ) u_button.image = u v_button = Button( root, command=lambda: check("v", v_button), image=v, border=0, bg="#edf5e1", activebackground="#edf5e1", ) v_button.image = v w_button = Button( root, command=lambda: check("w", w_button), image=w, border=0, bg="#edf5e1", activebackground="#edf5e1", ) w_button.image = w x_button = Button( root, command=lambda: check("x", x_button), image=x, border=0, bg="#edf5e1", activebackground="#edf5e1", ) x_button.image = x y_button = Button( root, command=lambda: check("y", y_button), image=y, border=0, bg="#edf5e1", activebackground="#edf5e1", ) y_button.image = y z_button = Button( root, command=lambda: check("z", z_button), image=z, border=0, bg="#edf5e1", activebackground="#edf5e1", ) z_button.image = z canva.create_window(115, 300, window=a_button) canva.create_window(145, 300, window=b_button) canva.create_window(175, 300, window=c_button) canva.create_window(205, 300, window=d_button) canva.create_window(235, 300, window=e_button) canva.create_window(265, 300, window=f_button) canva.create_window(295, 300, window=g_button) canva.create_window(325, 300, window=h_button) canva.create_window(355, 300, window=i_button) canva.create_window(385, 300, window=j_button) canva.create_window(115, 330, window=k_button) canva.create_window(145, 330, window=l_button) canva.create_window(175, 330, window=m_button) canva.create_window(205, 330, window=n_button) canva.create_window(235, 330, window=o_button) canva.create_window(265, 330, window=p_button) canva.create_window(295, 330, window=q_button) canva.create_window(325, 330, window=r_button) canva.create_window(355, 330, window=s_button) canva.create_window(385, 330, window=t_button) canva.create_window(185, 360, window=u_button) canva.create_window(215, 360, window=v_button) canva.create_window(245, 360, window=w_button) canva.create_window(275, 360, window=x_button) canva.create_window(305, 360, window=y_button) canva.create_window(335, 360, window=z_button) def bindings(letter, button): if button.winfo_exists(): check(letter, button) root.bind("<a>", lambda event: bindings("a", a_button)) root.bind("<b>", lambda event: bindings("b", b_button)) root.bind("<c>", lambda event: bindings("c", c_button)) root.bind("<d>", lambda event: bindings("d", d_button)) root.bind("<e>", lambda event: bindings("e", e_button)) root.bind("<f>", lambda event: bindings("f", f_button)) root.bind("<g>", lambda event: bindings("g", g_button)) root.bind("<h>", lambda event: bindings("h", h_button)) root.bind("<i>", lambda event: bindings("i", i_button)) root.bind("<j>", lambda event: bindings("j", j_button)) root.bind("<k>", lambda event: bindings("k", k_button)) root.bind("<l>", lambda event: bindings("l", l_button)) root.bind("<m>", lambda event: bindings("m", m_button)) root.bind("<n>", lambda event: bindings("n", n_button)) root.bind("<o>", lambda event: bindings("o", o_button)) root.bind("<p>", lambda event: bindings("p", p_button)) root.bind("<q>", lambda event: bindings("q", q_button)) root.bind("<r>", lambda event: bindings("r", r_button)) root.bind("<s>", lambda event: bindings("s", s_button)) root.bind("<t>", lambda event: bindings("t", t_button)) root.bind("<u>", lambda event: bindings("u", u_button)) root.bind("<v>", lambda event: bindings("v", v_button)) root.bind("<w>", lambda event: bindings("w", w_button)) root.bind("<x>", lambda event: bindings("x", x_button)) root.bind("<y>", lambda event: bindings("y", y_button)) root.bind("<z>", lambda event: bindings("z", z_button)) canva.grid()
""" from tkinter import Button, Tk, Label, StringVar, Entry, IntVar, PhotoImage import fPendu #Création fenêtre principale tkinter mw = Tk() mw.title("JEU DU PENDU") mw.geometry('500x500') mw.configure(bg='#1f3c88') #--------Initialisation du programme-------- #Stockage des images dans une liste image = [ PhotoImage(file=f"./versionUI/bonhomme{9-i}.gif") for i in range(1, 9) ] #Personal Best Score pb = 0 #On choisi un mot au hasard word = fPendu.pickWord() #Liste de toutes les lettres utilisés pas l'utilisateur lstLetterUsed = [word[0]] #Point de vie hp = IntVar() hp.set(8) #Mot à afficher dispWord = StringVar() dispWord.set(fPendu.displayWord(word, lstLetterUsed))
def loadPack(): '''This function creates and packs our load menu''' global loadCanvas, loadListName, firstLoad global buttonList, loadBg, loadListScore if not firstLoad: loadBg = PhotoImage(file="assets/load.png") loadCanvas = Canvas(loadFrame, width=w, height=h, bg="black") loadCanvas.pack() loadCanvas.create_image(0, 0, image=loadBg, anchor="nw") back = Button(loadFrame, text="Back", font=("Arial", 25), bg="white", command=loadUnpack) loadCanvas.create_window(80, 50, window=back) back = Button( loadFrame, text="Reset saved games", font=("Arial", 25), bg="white", command=resetLoad, ) loadCanvas.create_window(w / 2, 670, window=back) data = fileReadLoad() tmpCoord = 200 # Creates the different save game texts and their # respective load buttons for i in range(len(data)): buttonList.append( Button(loadFrame, text="Load this", font=("Arial", 15), bg="white", height=1, command=lambda i=i: load(i))) loadCanvas.create_window(920, tmpCoord, window=buttonList[i]) loadCanvas.create_text(280, tmpCoord, text=str(i + 1) + ".", fill="white", font=("Arial", 45), anchor="w") loadListName.append( loadCanvas.create_text((w / 2) - 300, tmpCoord, text=data[i][0], fill="white", font=("Arial", 45), anchor="w")) loadCanvas.create_text(650, tmpCoord, text=":", fill="white", font=("Arial", 45)) loadListScore.append( loadCanvas.create_text((w / 2) + 70, tmpCoord, text=data[i][1], fill="white", font=("Arial", 45), anchor="w")) tmpCoord += 55 firstLoad = True else: results = fileReadLoad() # Except for the first load, the values keep getting updated for i in range(len(results)): loadCanvas.itemconfig(loadListName[i], text=results[i][0]) loadCanvas.itemconfig(loadListScore[i], text=results[i][1]) mainMenuFrame.pack_forget() loadFrame.pack()
class Monitor(): def __init__(self, parent): # Set up the initial variables/frame stuff self.parent = parent self.parent.geometry("378x288") self.frame = Frame(parent) self.memory_listener = MemoryListener(self.mem_action) self.print_listener = PrintListener(self.print_action) self.width = 378 self.height = 288 self.img = PhotoImage(width=self.width, height=self.height) self.canvas = None self.number_of_chars = 0 self.x = 0 self.y = 0 self.initUI() def draw_text(self, x, y, char): #Height of each letter is around 10 pixels, so start there. Then their width is 7 pixels-ish, so increase by that much. So yeah. self.canvas.create_text(x + 10 + (7 * self.number_of_chars), y + 10, text=char, fill="white") self.number_of_chars += 1 def handle_close(self): self.memory_listener.unregister() self.parent.destroy() def print_action(self, data): self.draw_text(self.x, self.y, data) self.x = (self.x + 1)%126 self.y = (self.y + 1)//126 def mem_action(self, data): address = data[0] # Video mem starts at 0x8000, and since the monitor is 120x90, and (120*90) = 0x2A30, so 0x8000 + 0x2A30 = 0xAA30 if(address >= 0x8000 and address <= 0xAA30): pixel = address - 0x8000 color = data[1] # I don't think I'm getting the RGB values correctly... # rrrrrrgggggbbbbb r = (color >> 10) & 0b111111 g = (color >> 5) & 0b11111 b = color & 0b11111 print("[VIDEO]: Pixel,", hex(pixel), "set to,", hex(data[1]), "(#%02x%02x%02x)" % (r,g,b)) #Calculate the x and y. Offset the y by 3, because the border takes up 3 pixels. x = (pixel%126)*3 y = ((pixel//126)*3)+3 print("********************Y = ", y) #Update the image with a static pink #self.img.put("#FF00FF", (x,y)) #Update the image with the given RGB, upscale dat stuff. #Row 1 self.img.put("#%02x%02x%02x" % (r*4,g*8,b*8), (x, y)) self.img.put("#%02x%02x%02x" % (r*4,g*8,b*8), (x + 1, y)) self.img.put("#%02x%02x%02x" % (r*4,g*8,b*8), (x + 2, y)) #Row 2 self.img.put("#%02x%02x%02x" % (r*4,g*8,b*8), (x, y + 1)) self.img.put("#%02x%02x%02x" % (r*4,g*8,b*8), (x + 1, y + 1)) self.img.put("#%02x%02x%02x" % (r*4,g*8,b*8), (x + 2, y + 1)) #Row 3 self.img.put("#%02x%02x%02x" % (r*4,g*8,b*8), (x, y + 2)) self.img.put("#%02x%02x%02x" % (r*4,g*8,b*8), (x + 1, y + 2)) self.img.put("#%02x%02x%02x" % (r*4,g*8,b*8), (x + 2, y + 2)) def initUI(self): # Deal with the UI self.parent.title("Monitor") self.frame.pack(fill=BOTH, expand=1) # Now less placeholder-y self.canvas = Canvas(self.frame, width=self.width, height=self.height, bg="#000") self.canvas.pack(fill=BOTH, expand=1) # Need to create an image so we can place individual pixels self.canvas.create_image((self.width/2, self.height/2), image=self.img, state="normal") # Handle the closing event (unregister the event listener) self.parent.protocol("WM_DELETE_WINDOW", self.handle_close)
def get_image(self, image_width, image_height, num_iters, generator, starting_point=Coordinate(0, 0), bg_color="#000000", fg_color="#00FF00", colors=True, first_transformations=100): img = PhotoImage(width=image_width, height=image_height) # Set background color img.put(bg_color, to=(0, 0, image_width, image_height)) # Calculation of points all_points = [starting_point] all_transformations = [0] gen_str = "" current_point = starting_point for i in range(num_iters): gen_val = next(generator) index = int(gen_val, base=self.size) t = self.transformations[index] current_point = t.transform(current_point) all_points.append(current_point) all_transformations.append(index) gen_str += gen_val # Stretch to fit image min_x = min(all_points, key=lambda pt: pt.x).x max_x = max(all_points, key=lambda pt: pt.x).x min_y = min(all_points, key=lambda pt: pt.y).y max_y = max(all_points, key=lambda pt: pt.y).y fractal_width = max_x - min_x fractal_height = max_y - min_y fractal_size = max(fractal_width, fractal_height) drawn_points = [] draw_colors = [] for pt, index in zip(all_points, all_transformations): new_x = ((pt.x - min_x) / fractal_size) * image_width new_y = ((pt.y - min_y) / fractal_size) * image_height new_y = image_height - new_y drawn_points.append(Coordinate(new_x, new_y)) draw_colors.append(hsv_to_rgb(index * 360 / self.size, 1, 1)) # Draw points if colors: for pt, dot_color in zip(drawn_points, draw_colors): img.put(dot_color, (round(pt.x), round(pt.y))) else: for pt in drawn_points: img.put(fg_color, (round(pt.x), round(pt.y))) return img, gen_str[:first_transformations]
def load_images(self): """loads images from the disk""" for i in range(N_IMAGES): self.images.append(PhotoImage(file=f"res/{i}.png"))
# -*- coding: utf-8 -*- from tkinter import PhotoImage from turtle import * from random import randint squarelength = 100 # Nombre de pixels des petits carrés des grilles screen = Screen() witchimage = PhotoImage(file="witch.gif").subsample(10, 10) screen.addshape("witch", Shape("image", witchimage)) hutimage = PhotoImage(file="hut.gif").subsample(8, 8) screen.addshape("hut", Shape("image", hutimage)) witch = Turtle(shape="witch") # La tortue de la sorcière, dessine sa traînée witch.speed(0) witch.pu() hut = Turtle(shape="hut") # La tortue de la cabane (immobile) hut.speed(5) hut.pu() gridt = Turtle(visible=False) # La tortue qui dessine la grille gridt.speed(0) gridt.pu() hideturtle() penup() goto(0, -250) # La tortue qui écrit les messages grids = [(3, 3, 0, 2, 2, 2), (4, 3, 0, 0, 1, 2), (3, 4, 2, 2, 0, 1), (5, 3, 4, 2, 2, 0), (3, 5, 2, 2, 0, 4), (4, 4, 1, 2, 3, 3), (6, 3, 1, 1, 5, 2), (5, 4, 2, 0, 3, 0), (4, 5, 2, 0, 3, 4), (6, 4, 4, 1, 1, 3), (5, 5, 1, 1, 3, 3), (6, 5, 5, 1, 5, 4)
''' Create theme extract for custom widgets, need state selection to compare different themes. Both widgets almost same, but pil (lower one) has slightly jagged edges around arrow. ''' from tkinter import Tk, PhotoImage, StringVar from tkinter.ttk import Style, Label, Radiobutton, Frame, Combobox root = Tk() fr = Frame(root) fr.grid(column=0, row=0, sticky='nsew') img1 = PhotoImage("combo-n", file='../images/combo-n.png') img2 = PhotoImage("combo-p", file='../figures/09combo.png') img9 = PhotoImage("comboarrow-n", file='../images/comboarrow-n.png') img11 = PhotoImage("comboarrow-p", file='../figures/09comboarrow5.png') style = Style() # both theme_create and theme_settings worked style.theme_create( "yummy", parent="clam", settings={ #style.theme_settings('default', { "Combobox.field": { "element create": ("image", 'combo-p', ('alternate', 'combo-n'), { 'sticky': 'ew', 'border': [4] })
def __init__(self, parent, art: str = r"menus\start_art\highscoresb.gif", relx: float = 0, rely: float = 0): super().__init__(parent=parent, art=art, relx=relx, rely=rely) self.scores = PhotoImage(file=r"menus\start_art\scores.gif")
def paste(): content_text.event_generate("<<Paste>>") return "break" def undo(): content_text.event_generate("<<Undo>>") return "break" def redo(event=None): content_text.event_generate("<<Redo>>") return "break" new_file_icon = PhotoImage(file="icons/new_file.gif") open_file_icon = PhotoImage(file="icons/open_file.gif") save_file_icon = PhotoImage(file="icons/save.gif") cut_icon = PhotoImage(file="icons/cut.gif") copy_icon = PhotoImage(file="icons/copy.gif") paste_icon = PhotoImage(file="icons/paste.gif") undo_icon = PhotoImage(file="icons/undo.gif") redo_icon = PhotoImage(file="icons/redo.gif") menu_bar = Menu(root) file_menu = Menu(menu_bar, tearoff=0) file_menu.add_command(label="New", accelerator="Ctrl+N", compound="left", image=new_file_icon, underline=0)
def __init__(self, shape=19, master=None, scale=1.8, meter=400, pad=20): Canvas.__init__(self, master, bg='#369', bd=0, width=1.5 * meter * scale, height=meter * scale) GoBoard.__init__(self, shape=shape) self.scale, self.shape, self.meter, self.pad = scale, shape, meter, pad self.place(x=0, y=0) self.create_rectangle(0, 0, meter * scale, meter * scale, fill='#c51') # 刻画棋盘线及九个点 # 先画外框粗线 self.create_rectangle(pad * scale, pad * scale, (meter - pad) * scale, (meter - pad) * scale, width=3) unit = (meter - 2 * pad) * scale / (shape - 1) self.unit = unit # 棋盘上的九个定位点,以中点为模型,移动位置,以作出其余八个点 radius = 2 * scale core = meter / 2 * scale for m, n in product((-1, 0, 1), (-1, 0, 1)): original = self.create_oval(core - radius, core - radius, core + radius, core + radius, fill='#000') self.move(original, m * unit * BoardCanvas.KernelMap[shape], n * unit * BoardCanvas.KernelMap[shape]) for i in range(1, shape - 1): self.create_line(pad * scale, pad * scale + i * unit, (meter - pad) * scale, pad * scale + i * unit, width=2) self.create_line(pad * scale + i * unit, pad * scale, pad * scale + i * unit, (meter - pad) * scale, width=2) photoBD = PhotoImage(file=path.join(resource_dir, "BD-%d.png" % shape)) photoWD = PhotoImage(file=path.join(resource_dir, "WD-%d.png" % shape)) photoBU = PhotoImage(file=path.join(resource_dir, "BU-%d.png" % shape)) photoWU = PhotoImage(file=path.join(resource_dir, "WU-%d.png" % shape)) self.photoWBU = (photoBU, photoWU) self.photoWBD = (photoBD, photoWD) self.photoW = PhotoImage(file=path.join(resource_dir, "W.png")) self.photoB = PhotoImage(file=path.join(resource_dir, "B.png")) self.pW = self.create_image(1.25 * meter * scale + 11, 0.16 * meter * scale, image=self.photoW) self.pB = self.create_image(1.25 * meter * scale - 11, 0.16 * meter * scale, image=self.photoB) self.addtag_withtag('image', self.pW) self.addtag_withtag('image', self.pB) self.player_stone_image = self.create_image(0, 0, state=HIDDEN, image=photoBU), \ self.create_image(0, 0, state=HIDDEN, image=photoWU) self.__stones = np.empty((shape, shape), dtype=np.object) self.__image_signs = {} self.__stop_hover = False self.stop = False self.start_hover() self.__hover_pos = None self.bind('<Button-1>', self.on_click)
def __init__(self, top=None): '''This class configures and populates the toplevel window. top is the toplevel containing window.''' _bgcolor = '#d9d9d9' # X11 color: 'gray85' _fgcolor = '#000000' # X11 color: 'black' _compcolor = '#d9d9d9' # X11 color: 'gray85' _ana1color = '#d9d9d9' # X11 color: 'gray85' _ana2color = '#ececec' # Closest X11 color: 'gray92' font11 = "-family {Segoe UI} -size 12 -weight bold -slant " \ "roman -underline 0 -overstrike 0" font12 = "-family {Segoe UI} -size 10 -weight normal -slant " \ "italic -underline 0 -overstrike 0" font9 = "-family {Segoe UI} -size 9 -weight normal -slant " \ "roman -underline 0 -overstrike 0" font13 = "-family {Microsoft YaHei} -size 15 -weight bold " \ "-slant roman -underline 0 -overstrike 0" font17 = "-family {Segoe UI Historic} -size 12 -weight normal " \ "-slant italic -underline 1 -overstrike 0" font28 = "-family Arial -size 16 -weight normal -slant roman " \ "-underline 0 -overstrike 0" font30 = "-family Gadugi -size 15 -weight bold -slant roman " \ "-underline 1 -overstrike 0" font40 = "-family {OCR A Extended} -size 36 -weight bold " \ "-slant roman -underline 1 -overstrike 0" font9 = "-family {Segoe UI} -size 9 -weight normal -slant " \ "roman -underline 0 -overstrike 0" width = top.winfo_screenwidth() height = top.winfo_screenheight() top.geometry("%dx%d+0+0" % (width, height)) top.wm_state('normal') self.panel = None top.title("PGC Facial Recognition System") root.iconphoto(True, PhotoImage(file="./icons/Taskbar_Icon40x40.png")) #root = tk.Tk() #img = PhotoImage(file='icon.ico') #root.tk.call('wm','iconphoto',root._w,img) #top.wm_iconbitmap("icons/icon.png") top.configure(background="#d8d8d8") top.configure(highlightbackground="#d9d9d9") top.configure(highlightcolor="black") self.menubar = tk.Menu(top, font=font9, bg=_bgcolor, fg=_fgcolor) top.configure(menu=self.menubar) self.sub_menu = tk.Menu(top, tearoff=0) self.menubar.add_cascade(menu=self.sub_menu, activebackground="#ececec", activeforeground="#000000", background="#d9d9d9", font="TkMenuFont", foreground="#000000", label="File") self.sub_menu.add_command(command=self.loginPopup, activebackground="#ececec", activeforeground="#000000", background="#d8d8d8", font="TkMenuFont", foreground="#000000", label="Login") self.sub_menu.add_separator(background="#d9d9d9") self.sub_menu.add_command(command=quit, activebackground="#ececec", activeforeground="#000000", background="#d9d9d9", font="TkMenuFont", foreground="#000000", label="Exit") #--------[ home screen ----------------------------------------- # self.root=top # self.panel = None # self.frame = None # self.vs = VideoStream(usePiCamera=True).start() # time.sleep(2.0) # # construct the argument parser and parse the arguments # ap = argparse.ArgumentParser() # ap.add_argument("-c", "--cascade", required=True, # help = "path to where the face cascade resides") # ap.add_argument("-e", "--encodings", required=True, # help="path to serialized db of facial encodings") # args = vars(ap.parse_args()) # # # load the known faces and embeddings along with OpenCV's Haar # # cascade for face detection # print("[INFO] loading encodings + face detector...") # self.data = pickle.loads(open(args["encodings"], "rb").read()) # self.detector = cv2.CascadeClassifier(args["cascade"]) #self.loop() #self.cameraFrame.configure(width=350, height= 350) #---------------------------frame and label for employee access-------------------------------- self.accessFrame = tk.LabelFrame(top) self.accessFrame.place(relx=0.099, rely=0.543, width=350, height=200) #(relx=0.579, rely=0.664, relheight=0.255, relwidth=0.249) self.accessFrame.configure(relief='ridge') self.accessFrame.configure(font=font13) self.accessFrame.configure(foreground="black") self.accessFrame.configure(labelanchor="n") self.accessFrame.configure(relief="ridge") self.accessFrame.configure(text='''Access''') self.accessFrame.configure(background="#d9d9d9") #self.accessFrame.configure(width=350) #----------------------label for employee access on main window------------------------------- self.accessLabel = tk.Label(self.accessFrame) self.accessLabel.place(relx=0.1859, rely=0.41, height=40, width=220, bordermode='ignore') self.accessLabel.configure(activebackground="#f9f9f9") self.accessLabel.configure(activeforeground="black") self.accessLabel.configure(anchor='w') self.accessLabel.configure(background="#4dd823") self.accessLabel.configure(cursor="fleur") self.accessLabel.configure(disabledforeground="#a3a3a3") self.accessLabel.configure(font=font40) self.accessLabel.configure(foreground="#000000") self.accessLabel.configure(highlightbackground="#3cd842") self.accessLabel.configure(highlightcolor="black") self.accessLabel.configure(text='''Granted''') self.accessLabel.configure(width=220) #-----/////////////////////////////////////////////////////////////////////////////////////////// self.timeFrame = tk.Frame(top) self.timeFrame.place(relx=0.529, rely=0.5515, width=400, height=190) #relheight=0.255, relwidth=0.249) self.timeFrame.configure(relief='ridge') self.timeFrame.configure(borderwidth="2") self.timeFrame.configure(relief="ridge") self.timeFrame.configure(background="#d9d9d9") self.timeFrame.configure(highlightcolor="#1a2463") #self.timeFrame.configure(width=350) self.dateLabel = tk.Label(self.timeFrame) self.dateLabel.place(relx=0.082, rely=0.129, height=40, width=130) self.dateLabel.configure(activebackground="#f9f9f9") self.dateLabel.configure(activeforeground="black") self.dateLabel.configure(anchor='w') self.dateLabel.configure(background="#d9d9d9") self.dateLabel.configure(disabledforeground="#a3a3a3") self.dateLabel.configure(font=font30) self.dateLabel.configure(foreground="#000000") self.dateLabel.configure(highlightbackground="#d9d9d9") self.dateLabel.configure(highlightcolor="black") self.dateLabel.configure(text='''Date:''') self.timeLabel = tk.Label(self.timeFrame) self.timeLabel.place(relx=0.082, rely=0.581, height=40, width=130) self.timeLabel.configure(activebackground="#f9f9f9") self.timeLabel.configure(activeforeground="black") self.timeLabel.configure(anchor='w') self.timeLabel.configure(background="#d9d9d9") self.timeLabel.configure(disabledforeground="#a3a3a3") self.timeLabel.configure(font=font30) self.timeLabel.configure(foreground="#000000") self.timeLabel.configure(highlightbackground="#d9d9d9") self.timeLabel.configure(highlightcolor="black") self.timeLabel.configure(text='''Time:''') self.dateDisp = tk.Label(self.timeFrame) self.dateDisp.place(relx=0.259, rely=0.159, height=40, width=270) self.dateDisp.configure(activebackground="#f9f9f9") self.dateDisp.configure(activeforeground="#000000") self.dateDisp.configure(anchor='nw') self.dateDisp.configure(background="#d9d9d9") self.dateDisp.configure(compound='center') self.dateDisp.configure(disabledforeground="#a3a3a3") self.dateDisp.configure(font=font28) self.dateDisp.configure(foreground="#220c93") self.dateDisp.configure(highlightbackground="#d9d9d9") self.dateDisp.configure(highlightcolor="#2d03ff") self.dateDisp.configure(text='''August 16,2019''') self.dateDisp.configure(width=300) self.timeDisp = tk.Label(self.timeFrame) self.timeDisp.place(relx=0.259, rely=0.611, height=40, width=200) self.timeDisp.configure(activebackground="#f9f9f9") self.timeDisp.configure(activeforeground="#000000") self.timeDisp.configure(anchor='nw') self.timeDisp.configure(background="#d9d9d9") self.timeDisp.configure(compound='center') self.timeDisp.configure(disabledforeground="#a3a3a3") self.timeDisp.configure(font=font28) self.timeDisp.configure(foreground="#220c93") self.timeDisp.configure(highlightbackground="#d9d9d9") self.timeDisp.configure(highlightcolor="#2d03ff") self.timeDisp.configure(text='''07:24:12''') self.timeDisp.configure(width=200) self.eDataFrame = tk.LabelFrame(top) self.eDataFrame.place(relx=0.45, rely=0.076, width=600, height=360) #relheight=0.474 , relwidth=0.44) self.eDataFrame.configure(relief='groove') self.eDataFrame.configure(font=font17) self.eDataFrame.configure(foreground="black") self.eDataFrame.configure(labelanchor="n") self.eDataFrame.configure(text='''Employee Data''') self.eDataFrame.configure(background="#d9d9d9") self.eDataFrame.configure(highlightbackground="#f0f0f0") self.eDataFrame.configure(highlightcolor="black") self.eDataFrame.configure(takefocus="1") #self.eDataFrame.configure(width=500) self.nameLabelHead = tk.Label(self.eDataFrame) self.nameLabelHead.place(relx=0.075, rely=0.215, height=40, width=75, bordermode='ignore') self.nameLabelHead.configure(activebackground="#f9f9f9") self.nameLabelHead.configure(activeforeground="black") self.nameLabelHead.configure(anchor='w') self.nameLabelHead.configure(background="#d9d9d9") self.nameLabelHead.configure(disabledforeground="#a3a3a3") self.nameLabelHead.configure(font=font30) self.nameLabelHead.configure(foreground="#000000") self.nameLabelHead.configure(highlightbackground="#d9d9d9") self.nameLabelHead.configure(highlightcolor="black") self.nameLabelHead.configure(text='''Name:''') self.dptLabelHead = tk.Label(self.eDataFrame) self.dptLabelHead.place(relx=0.075, rely=0.462, height=40, width=150, bordermode='ignore') self.dptLabelHead.configure(activebackground="#f9f9f9") self.dptLabelHead.configure(activeforeground="black") self.dptLabelHead.configure(anchor='w') self.dptLabelHead.configure(background="#d9d9d9") self.dptLabelHead.configure(disabledforeground="#a3a3a3") self.dptLabelHead.configure(font=font30) self.dptLabelHead.configure(foreground="#000000") self.dptLabelHead.configure(highlightbackground="#d9d9d9") self.dptLabelHead.configure(highlightcolor="black") self.dptLabelHead.configure(text='''Department:''') self.statusLabelHead = tk.Label(self.eDataFrame) self.statusLabelHead.place(relx=0.075, rely=0.708, height=40, width=90, bordermode='ignore') self.statusLabelHead.configure(activebackground="#f9f9f9") self.statusLabelHead.configure(activeforeground="black") self.statusLabelHead.configure(anchor='w') self.statusLabelHead.configure(background="#d9d9d9") self.statusLabelHead.configure(disabledforeground="#a3a3a3") self.statusLabelHead.configure(font=font30) self.statusLabelHead.configure(foreground="#000000") self.statusLabelHead.configure(highlightbackground="#d9d9d9") self.statusLabelHead.configure(highlightcolor="black") self.statusLabelHead.configure(text='''Status:''') self.statusDisplay = tk.Label(self.eDataFrame) self.statusDisplay.place(relx=0.23, rely=0.721, height=40, width=200, bordermode='ignore') self.statusDisplay.configure(activebackground="#f9f9f9") self.statusDisplay.configure(activeforeground="black") self.statusDisplay.configure(anchor='nw') self.statusDisplay.configure(background="#d9d9d9") self.statusDisplay.configure(compound='center') self.statusDisplay.configure(disabledforeground="#a3a3a3") self.statusDisplay.configure(font=font28) self.statusDisplay.configure(foreground="#220c93") self.statusDisplay.configure(highlightbackground="#d9d9d9") self.statusDisplay.configure(highlightcolor="black") self.statusDisplay.configure(text='''Trainee''') self.statusDisplay.configure(width=200) self.dptDisplay = tk.Label(self.eDataFrame) self.dptDisplay.place(relx=0.349, rely=0.474, height=30, width=300, bordermode='ignore') self.dptDisplay.configure(activebackground="#f9f9f9") self.dptDisplay.configure(activeforeground="black") self.dptDisplay.configure(anchor='nw') self.dptDisplay.configure(background="#d9d9d9") self.dptDisplay.configure(compound='center') self.dptDisplay.configure(disabledforeground="#a3a3a3") self.dptDisplay.configure(font=font28) self.dptDisplay.configure(foreground="#220c93") self.dptDisplay.configure(highlightbackground="#d9d9d9") self.dptDisplay.configure(highlightcolor="black") self.dptDisplay.configure(text='''Electrical and Instrumentation''') self.dptDisplay.configure(width=300) self.employeeName = tk.StringVar() #self.employeeName = tk.StringVar() self.nameDisp = tk.Label(self.eDataFrame, textvariable=self.employeeName) self.nameDisp.place(relx=0.221, rely=0.227, height=40, width=280, bordermode='ignore') self.nameDisp.configure(activebackground="#f9f9f9") self.nameDisp.configure(activeforeground="#000000") self.nameDisp.configure(anchor='nw') self.nameDisp.configure(background="#d9d9d9") self.nameDisp.configure(compound='center') self.nameDisp.configure(disabledforeground="#a3a3a3") self.nameDisp.configure(font=font28) self.nameDisp.configure(foreground="#220c93") self.nameDisp.configure(highlightbackground="#d9d9d9") self.nameDisp.configure(highlightcolor="#2d03ff") #self.nameDisp.configure(textvariable= self.employeeName)#text='''David Ramjit''') self.root = top self.panel = None self.frame = None self.vs = VideoStream(usePiCamera=True).start() time.sleep(2.0) # construct the argument parser and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-c", "--cascade", required=True, help="path to where the face cascade resides") ap.add_argument("-e", "--encodings", required=True, help="path to serialized db of facial encodings") args = vars(ap.parse_args()) # load the known faces and embeddings along with OpenCV's Haar # cascade for face detection print("[INFO] loading encodings + face detector...") self.data = pickle.loads(open(args["encodings"], "rb").read()) self.detector = cv2.CascadeClassifier(args["cascade"]) self.loop() self.dateTime()
def initUI(self, master): self.master.title("Corinne") self.master.grid_columnconfigure(0, weight=1) self.master.grid_rowconfigure(2, weight=1) self.master.option_add('*foreground', 'black') self.master.option_add('*background', 'white') # Style for ttk widgets style = ttk.Style() style.configure("TNotebook", background=self.COLOR_frames, borderwidth=1, highlightthickness=1) style.configure("TNotebook.Tab", background=self.COLOR_frames, foreground="black", lightcolor=self.COLOR_frames, borderwidth=0) style.map("TNotebook.Tab", background=[("selected", self.COLOR_buttons)], foreground=[("selected", 'black')]) style.configure("TFrame", background=self.COLOR_frames, foreground="black") # get screen resolution self._screen_width, self._screen_height = master.winfo_screenwidth(), master.winfo_screenheight() start_x = int((self._screen_width / 4)) start_y = int((self._screen_height / 4)) # fit the guy at screen resolution master.geometry('%dx%d+%d+%d' % (self._screen_width / 2, self._screen_height / 2, start_x, start_y)) # create all of the containers top_frame = Frame(master) top_frame.grid(row=1, column=0, sticky=(tk.N, tk.S, tk.E, tk.W)) top_frame.configure(bg=self.COLOR_frames) top_frame.grid_columnconfigure(0, weight=1) property_frame = Frame(master) property_frame.grid(row=2, column=0, sticky=(tk.N, tk.S, tk.E, tk.W)) property_frame.configure(bg=self.COLOR_frames) property_frame.grid_columnconfigure(0, weight=1) property_frame.grid_rowconfigure(0, weight=1) buttons_frame = Frame(master, padx=10, pady=10) buttons_frame.grid(row=0, column=0, sticky=(tk.N, tk.S, tk.E, tk.W)) buttons_frame.configure(bg=self.COLOR_frames) buttons_frame.grid_columnconfigure(0, weight=1) buttons_frame.grid_columnconfigure(1, weight=1) buttons_frame.grid_columnconfigure(2, weight=1) buttons_frame.grid_columnconfigure(3, weight=1) buttons_frame.grid_columnconfigure(4, weight=1) open_icon = PhotoImage(file="icons/open.png") open_button = Button(buttons_frame, text=" Open", image=open_icon, compound=tk.LEFT, padx=1, highlightthickness=0, command=self.open_file) open_button.configure(borderwidth=0, background=self.COLOR_buttons) open_button.image = open_icon open_button.grid(row=0, column=0, padx=5, sticky=(tk.N, tk.S, tk.E, tk.W)) render_icon = PhotoImage(file="icons/render.png") render_button = Button(buttons_frame, text=" Render", image=render_icon, compound=tk.LEFT, padx=1, highlightthickness=0, command=self.open_render_view) render_button.configure(borderwidth=0, background=self.COLOR_buttons) render_button.image = render_icon render_button.grid(row=0, column=1, padx=5, sticky=(tk.N, tk.S, tk.E, tk.W)) prod_icon = PhotoImage(file="icons/product.png") prod_button = Button(buttons_frame, text=" Product", image=prod_icon, compound=tk.LEFT, highlightthickness=0, command=self.open_product_view) prod_button.configure(borderwidth=0, background=self.COLOR_buttons) prod_button.image = prod_icon prod_button.grid(row=0, column=2, padx=5, sticky=(tk.N, tk.S, tk.E, tk.W)) sync_icon = PhotoImage(file="icons/sync.png") sync_button = Button(buttons_frame, text=" Sync", image=sync_icon, compound=tk.LEFT, highlightthickness=0, command=self.open_sync_view) sync_button.configure(borderwidth=0, background=self.COLOR_buttons) sync_button.image = sync_icon sync_button.grid(row=0, column=3, padx=5, sticky=(tk.N, tk.S, tk.E, tk.W)) proj_icon = PhotoImage(file="icons/projection.png") proj_button = Button(buttons_frame, text=" Projection", image=proj_icon, compound=tk.LEFT, highlightthickness=0, command=self.open_proj_view) proj_button.configure(borderwidth=0, background=self.COLOR_buttons) proj_button.image = proj_icon proj_button.grid(row=0, column=4, padx=5, sticky=(tk.N, tk.S, tk.E, tk.W)) # create the log box self._log = Listbox(top_frame, highlightthickness=0, height=5, background=self.COLOR_log, foreground=self.COLOR_foreground) #_scrollb = Scrollbar(top_frame, orient=tk.VERTICAL) #self._log.configure(yscrollcommand=_scrollb.set) #_scrollb.config(command=self._log.yview) self._log.grid(column=0, row=0, padx=10, sticky=(tk.N, tk.S, tk.E, tk.W)) # _scrollb.grid(column=1, row=0, sticky=tk.S + tk.N) # create the tab manager for property self.tabs = ttk.Notebook(property_frame)
speed = 10 pausecount = 0 score = 0 shotNo = 1 cheat = 0 immunitycount = 0 doubleshotcount = 0 multishot = 0 field = [] shots = [] windowDimensions(width, height) canvasG = Canvas(window, bg="black", width=width, height=height) buttonInst = PhotoImage(file="ButttonInstructions.png") buttonPlayGame = PhotoImage(file="ButtonPlayGame.png") buttonLeaderboard = PhotoImage(file="ButttonLeaderBoard.png") buttonPlayAgain = PhotoImage(file="ButttonPlayAgain.png") bosskeyimg = PhotoImage(file="BossKeyImage.png") quitgameimg = PhotoImage(file="ButtonQuitGame.png") canvasG.create_oval(600, 500, 1500, 1400, outline="white", fill="black") canvasG.create_oval(50, 500, 450, 900, outline="white", fill="black") canvasG.create_oval(250, 30, 650, 430, outline="white", fill="black") title = canvasG.create_text(600, 200, fill="White", font="Arial 42 bold", text="Astroid") buttonInst = PhotoImage(file="ButttonInstructions.png") buttonPlayGame = PhotoImage(file="ButtonPlayGame.png") buttonLeaderboard = PhotoImage(file="ButttonLeaderBoard.png")
from unitynet import NetCon, get_state from PIL import Image import io from tkinter import Canvas, PhotoImage, Tk, NW import base64 import time root = Tk() canvas = Canvas(root, width=300, height=300) img = PhotoImage(file="lastframe.png") imageoncanvas = canvas.create_image(20, 20, anchor=NW, image=img) root.update() netcon = NetCon() while True: try: if netcon.open(0.1) == True: break except: time.sleep(0.1) actions = { 'w': ("Up"), 's': ("Down"), 'p': ("PauseGame"), 'c': ("ResumeGame"),
Create theme extract for custom widgets, include state selection to view the result of changing the state using different images and/or different settings. ''' from tkinter import Tk, PhotoImage from tkinter.ttk import Style, Label, Radiobutton, Frame from RunState import run_state root = Tk() fr = Frame(root) fr.grid(column=0, row=0, sticky='nsew') img1 = PhotoImage("radio", file='../images/piratz/radio.png') img2 = PhotoImage("radio-s", file='../images/piratz/radio-s.png') style = Style() # both theme_create and theme_settings worked style.theme_create( "yummy", parent="clam", settings={ #style.theme_settings('default', { # start of theme extract 'Radiobutton.indicator': { "element create": ('image', "radio", ('selected', "radio-s"), { 'width': 20, 'sticky': "w" })
from tkinter import Tk, Label, PhotoImage, BOTTOM, LEFT, RIGHT, RIDGE raiz = Tk() texto = Label(raiz, font=('Helvetica', 16, 'bold italic'), foreground='white', background='black', padx=25, pady=10, text='A Paz começa com um sorriso.') texto.pack(side=BOTTOM) peace = PhotoImage(file='peace.gif') peaceLabel = Label(raiz, borderwidth=3, relief=RIDGE, image = peace) peaceLabel.pack(side=LEFT) smilei = PhotoImage(file='smile.gif') smileiLabel = Label(raiz, image=smilei) smileiLabel.pack(side=RIGHT) raiz.mainloop
edit_menu.add_command(label="Preferences...", underline=1, command=preferences) menubar.add_cascade(label="Edit", menu=edit_menu) menuaide = Menu(menubar,tearoff=0) menuaide.add_command(label=glb.language[9], underline=1, command=about, accelerator="F12") menuaide.add_separator() menuaide.add_command(label=glb.language[8], underline=1, command=help_window, accelerator="F1") menubar.add_cascade(label=glb.language[8], menu=menuaide) # Affichage du menu Mafenetre.config(menu=menubar) # Insertion du titre # Image titre photo = PhotoImage(file="./res/UI/titre.png") photo_taille=photo.subsample(2,2) # Création d'un widget Frame appellé titre dans Mafenetre Titre = Frame(Mafenetre,borderwidth=0,relief=GROOVE, bg="black") Titre.pack(padx=0,pady=0) Titre1=Label(Titre, image=photo_taille, bg="black") Titre1.pack() # Insertion déco # Image deco photodeco = PhotoImage(file="./res/UI/2.png") photodeco_taille=photodeco.subsample(2,2)
btn_back = Button(canvas1, width="35", height="3", text="Back", bg="#cafafe", borderwidth=2, relief="solid", command=back_to_menu) root = Tk() root.configure(background="#e6ffff") root.title("M E N U") root.geometry("800x500") global background background = PhotoImage(file="sky1.png") global canvas1 canvas1 = Canvas(root, width=800, height=500) canvas1.configure(background="#f0f0f0") canvas1.pack() global canvas2 canvas2 = Canvas(root, width=800, height=500) canvas2.configure(background="#f0f0f0") global canvas3 canvas3 = Canvas(root, width=800, height=500) canvas3.configure(background="#f0f0f0") global canvas4 canvas4 = Canvas(root, width=800, height=500) canvas4.configure(background="#f0f0f0") global canvas5 canvas5 = Canvas(root, width=800, height=500)
def __init__(self): EasyFrame.__init__(self, title="FFVI Slot Machine", width=400, height=300, background=BACKGROUND_COMMON) self.setResizable(False) """ initialize application variables """ self.fonts = { "title": Font(family="Times New Roman", size=14), "info": Font(family="Verdana", size=8, slant="italic"), "score": Font(family="Fixedsys", size=18), "result": Font(family="Fixedsys", size=18) } self.values = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] self.images = [ PhotoImage(file="pic/0.gif"), PhotoImage(file="pic/1.gif"), PhotoImage(file="pic/2.gif"), PhotoImage(file="pic/3.gif"), PhotoImage(file="pic/4.gif"), PhotoImage(file="pic/5.gif"), PhotoImage(file="pic/6.gif"), PhotoImage(file="pic/7.gif"), PhotoImage(file="pic/8.gif"), PhotoImage(file="pic/9.gif") ] # If this is True, a decimal value will increase each time the player loses, increasing their chances of matching numbers the more they lose. Once they win, the value is reset. If False, winning will be completely random. self.boost = False self.boostBase = 0.0 # Starting chance to give the player a match self.boostStep = 0.0125 # Amount to increase chance of matching on each spin self.boostValue = self.boostBase # Actual value used to calculate a free match given to the player self.twoMult = 3.0 self.jackpotMult = 5.0 self.playerScore = 100 self.playCost = 10 self.lastOutcome = -1 self.slotValue = [0, 0, 0] """ GUI components """ # Label setup self.titleLabel = self.addLabel("Final Fantasy VI Slot Machine", 0, 0, font=self.fonts["title"], background=BACKGROUND_COMMON, foreground=FOREGROUND_TEXT, sticky="W") # self.infoLabel = self.addLabel("How to play:\nPlaying costs "+str(self.playCost)+" gil\nTwo-of-a-kind: Win "+str(self.twoMult)+"x\nThree-of-a-kind: Win "+str(self.jackpotMult)+"x", 1, 0, font = self.fonts["info"], background = BACKGROUND_COMMON, foreground = FOREGROUND_TEXT, sticky = "EW") self.infoLabel = self.addLabel( "%-0s" % "How to play:\nPlaying costs " + str(self.playCost) + " gil\nTwo-of-a-kind: Win " + str(self.twoMult) + "x\nThree-of-a-kind: Win " + str(self.jackpotMult) + "x", 1, 0, font=self.fonts["info"], background=BACKGROUND_COMMON, foreground=FOREGROUND_TEXT, sticky="EW") self.scoreLabel = self.addLabel(str(self.playerScore) + " gil", 2, 0, font=self.fonts["score"], sticky="EW", background=BACKGROUND_COMMON, foreground=FOREGROUND_TEXT) self.slotPanel = self.addPanel(3, 0, background=BACKGROUND_COMMON) self.slotFrame = [ self.slotPanel.addLabel("", 0, 0, sticky="W"), self.slotPanel.addLabel("", 0, 1, sticky="EW"), self.slotPanel.addLabel("", 0, 2, sticky="E") ] self.slotFrame[0]["image"] = self.images[0] self.slotFrame[1]["image"] = self.images[0] self.slotFrame[2]["image"] = self.images[0] self.boostLabel = self.addLabel("Boost = ", 4, 0, font=self.fonts["info"], background=BACKGROUND_COMMON, foreground=FOREGROUND_TEXT, sticky="EW") self.outcomeLabel = self.addLabel("Spin to Play", 5, 0, background=BACKGROUND_COMMON, foreground=FOREGROUND_TEXT, sticky="EW") self.outcomeLabel["font"] = self.fonts["result"] # Buttons to spin and reset the game self.buttonPanel = self.addPanel(6, 0, background=BACKGROUND_COMMON) self.spinButton = self.buttonPanel.addButton("Spin!", 0, 0, command=self.spin) self.resetButton = self.buttonPanel.addButton("Reset", 0, 1, command=self.reset) self.updateUI()
def leaderPack(): '''This function creates and packs our leader menu screen.''' global leaderCanvas, leaderListName, firstLead, leaderBg, leaderListScore # If if is the first load, it creates the elements # else it moves to the else block to update the scores if not firstLead: leaderBg = PhotoImage(file="assets/leader.png") leaderCanvas = Canvas(leaderFrame, width=w, height=h, bg="black") leaderCanvas.pack() leaderCanvas.create_image(0, 0, image=leaderBg, anchor="nw") back = Button(leaderFrame, text="Back", font=("Arial", 25), bg="white", command=leaderUnpack) leaderCanvas.create_window(80, 50, window=back) back = Button(leaderFrame, text="Reset Leaderboards", font=("Arial", 25), bg="white", command=resetLB) leaderCanvas.create_window(w / 2, 670, window=back) results = fileRead() tmpCoord = 200 leaderListName.clear() # Creates the different score texts and displays them for i in range(len(results)): leaderCanvas.create_text(270, tmpCoord, text=str(i + 1) + ".", fill="white", font=("Arial", 45)) leaderListName.append( leaderCanvas.create_text((w / 2) - 250, tmpCoord, text=results[i][0], fill="white", font=("Arial", 45), anchor="w")) leaderCanvas.create_text(650, tmpCoord, text=":", fill="white", font=("Arial", 45)) leaderListScore.append( leaderCanvas.create_text((w / 2) + 200, tmpCoord, text=results[i][1], fill="white", font=("Arial", 45), anchor="w")) tmpCoord += 50 firstLead = True else: results = fileRead() for i in range(len(results)): leaderCanvas.itemconfig(leaderListName[i], text=results[i][0]) leaderCanvas.itemconfig(leaderListScore[i], text=results[i][1]) mainMenuFrame.pack_forget() leaderFrame.pack()
c.itemconfig(score_text, text=str(score)) def show_time(time_left): c.itemconfig(time_text, text=str(time_left)) # <===== PROGRAM STARTS HERE HEIGHT = 600 WIDTH = 900 window = Tk() window.title('Bubble Blaster') imgicon = PhotoImage(file=os.path.abspath('bubbles.png')) window.tk.call('wm', 'iconphoto', window._w, imgicon) c = Canvas(window, width=WIDTH, height=HEIGHT, bg='darkblue') c.pack() ship_id = c.create_polygon(5, 5, 5, 25, 30, 15, fill='red') ship_id2 = c.create_oval(0, 0, 30, 30, outline='red') MID_X = WIDTH / 2 MID_Y = HEIGHT / 2 c.move(ship_id, MID_X, MID_Y) c.move(ship_id2, MID_X, MID_Y)
def updateimg(self): self.img = PhotoImage(file=self.plotter.get_file()) self.canvas.itemconfig(self.imgArea, image=self.img)
#color string table in Photoimage format #RRGGBB clr=[ ' #%02x%02x%02x' % (int(255*((i/255)**.25)),0,0) for i in range(256)] clr.append(' #000000') #append the color of the centre as index 256 #calculate mandelbrot x,y coordinates for each screen pixel xm=[xa + (xb - xa) * kx /x for kx in range(x)] ym=[ya + (yb - ya) * ky /y for ky in range(y)] #build the Photoimage string by calling mandel_pixel to index in the color table return" ".join((("{"+" ".join(clr[mandel_pixel(complex(i,j))] for i in xm))+"}" for j in ym)) #window size x=640 y=480 #corners of the mandelbrot plan to display xa = -2.0; xb = 1.0 ya = -1.27; yb = 1.27 #Tkinter window window = Tk() canvas = Canvas(window, width = x, height = y, bg = "#000000");canvas.pack() img = PhotoImage(width = x, height = y) canvas.create_image((0, 0), image = img, state = "normal", anchor = NW) #do the mandelbrot t1=clock() img.put(mandelbrot(xa,xb,ya,yb,x,y)) print(clock()-t1, ' seconds') mainloop()
class gui_view_tk(Tkinter.Tk): """ Class to manage the display of a saved text based grid map in a GUI - useful for large grids Grid text sample is below: ..#......2#XXXXX.............X.X......X. ..#......A#XXXX.............XX.......X.. ..#.A0000A#XXXX...X.XX......XXT......XXX ......111A#XXXX....X..X...XXXXX........X .....A1...#X..X..XXXXXXX...X.XX........X """ def __init__(self,parent): """ initialise tkinter with default parameters """ Tkinter.Tk.__init__(self,parent) self.parent = parent self.appWidth = 1900 # initial values self.appHeight = 1000 self.cell_width = 4 self.cell_height = 3 self.fname = '' self.screenWidth = self.winfo_screenwidth() self.screenHeight = self.winfo_screenheight() self.configure(bg='black') self.geometry('%dx%d+%d+%d' % (self.appWidth, self.appHeight, self.screenWidth - self.appWidth - 0, self.screenHeight - self.appHeight - 0)) WIDTH = self.appWidth HEIGHT = self.appHeight self.canvas = Canvas(self, width=WIDTH, height=HEIGHT, bg="#000000") self.canvas.pack() self.img = PhotoImage(width=WIDTH, height=HEIGHT) self.canvas.create_image(( WIDTH/2, HEIGHT/2), image=self.img, state="normal") #self.TEST_sin() # testing - draws a sin wave self.appWidth = 1900 # canvas.width self.appHeight = 1000 self.canvas.pack() def TEST_sin(self): for x in range(4 * self.appWidth): y = int(self.appHeight/2 + self.appHeight/4 * math.sin(x/80.0)) self.img.put("#ffffff", (x//4,y)) self.canvas.pack() def add_file(self, fname): self.fname = fname def show_grid_from_file(self, fname): """ reads a saved grid file and paints it on the canvas """ with open(fname, "r") as f: for y, row in enumerate(f): for x, val in enumerate(row): self.draw_cell(y, x, val) def draw_cell(self, row, col, val): """ draw a cell as position row, col containing val """ if val == 'T': self.paint_target(row,col) elif val == '#': self.paint_block(row,col) elif val == 'X': self.paint_hill(row,col) elif val == '.': self.paint_land(row,col) elif val in ['A']: self.paint_agent_location(row,col) elif val in ['1','2','3','4','5','6','7','8','9']: self.paint_agent_trail(row,col, val) def put_standard_block(self, y, x, val): """ prints a block, packing out around the y/x location with pixels up to cell width and cell height """ for j in range(0,self.cell_height): for i in range(0,self.cell_width): self.img.put(val, (x*self.cell_width+i, y*self.cell_height+j)) def paint_land(self, y, x): self.put_standard_block(y,x,'bisque') def paint_block(self, y, x): self.put_standard_block(y,x,'gray9') def paint_hill(self, y, x): self.put_standard_block(y,x,'green4') def paint_target(self, y, x): self.put_standard_block(y,x,'yellow') self.img.put('black', (x*self.cell_width+1, y*self.cell_height+1)) self.img.put('black', (x*self.cell_width+0, y*self.cell_height+1)) self.img.put('black', (x*self.cell_width+1, y*self.cell_height+0)) self.img.put('black', (x*self.cell_width+0, y*self.cell_height+0)) def paint_agent_trail(self, y, x, val): """ paint an agent trail as ONE pixel to allow for multiple agent trails to be seen in the same cell """ for j in range(1,self.cell_height-1): for i in range(1,self.cell_width-1): self.img.put(self.agent_color(val), (x*self.cell_width+i, y*self.cell_height+j)) #self.paint_agent_location(y,x,self.agent_color(val)) # old version - try to paint a single pixel trail but it looks too small #self.paint_land(y,x) # needed otherwise shows up black under dots - todo - fix this #self.img.put(self.agent_color(val), (x*self.cell_width, y*self.cell_height)) # +int(val) def paint_agent_location(self, y, x): self.put_standard_block(y,x,'red') def agent_color(self, val): """ gets a colour for agent 0 - 9 """ if val == '0': colour = 'blue' elif val == '1': colour = 'navy' elif val == '2': colour = 'firebrick' elif val == '3': colour = 'blue' elif val == '4': colour = 'blue2' elif val == '5': colour = 'blue4' elif val == '6': colour = 'gray22' elif val == '7': colour = 'gray57' elif val == '8': colour = 'red4' elif val == '9': colour = 'red3' return colour
def canvasPack(): '''This function creates and packs our game screen''' global snakeSize, snake, rectLine, rectNumber, xCoord, scoringStart global file, fileDict, x, loadSc, loadScore, bossCount, score global collided, food, foodNumber, fishImages, gameOver, toStartTxt global bossControl, unpauseControl, startControl, pauseControl global canvas, bossImage, fishImage, snakeLengthText, scoreText, gameFrame global cheat1Control, cheat2Control, cheat3Control, moveSpeed gameFrame = Frame(window) snakeSize = 20 x = 1 snake = [] rectLine = [] rectNumber = [] xCoord = [] collided = [] food = [] foodNumber = [] fishImages = [] gameOver = False paused = False scoringStart = False score = -10 fishImage = PhotoImage(file="assets/fish.png") canvas = Canvas(gameFrame, width=w, height=h, bg="black") canvas.pack() canvas.focus_set() # Sets the speed of the game according # to the platform being used osType = platform.system() if osType == "Darwin": moveSpeed = 4 elif osType == "Windows": moveSpeed = 2 else: moveSpeed = 2 snake.append( canvas.create_oval(w / 2, h / 2, w / 2 + snakeSize, (h / 2) + snakeSize, fill="white")) growSnake(30) toStartTxt = canvas.create_text(w / 2, 100, text="LEFT CLICK TO START", font=("Verdana", 50), fill="green") scoreText = canvas.create_text(w / 2, 30, text="SCORE : 0", font=("Verdana", 35), fill="white") # Give a custom score if a savegame is being loaded if loadSc: txt = "SCORE : " + str(loadScore) canvas.itemconfig(scoreText, text=txt) snakeLengthText = canvas.create_text(w / 2 + 35, (h / 2) + 10, text=len(snake), font=("Arial", 15), fill="white") rectGenerate() canvas.bind(cheat1Control, cheat) canvas.bind(cheat2Control, cheat) canvas.bind(cheat3Control, cheat) canvas.bind(startControl, start) window.after(1, block) # Store the existing leaderboards incase the game # closes unexpectedly file = open('assets/leader.txt', 'r') fileDict = file.read() fileDict = json.loads(fileDict) file.close() mainMenuFrame.pack_forget() gameFrame.pack()
texto.insert(INSERT, informacao, END) #============ Menu ========== lm = Label(main, bg="orange") lm.grid(row=0, column=1, sticky="W, E") main.grid_columnconfigure( 1, weight=1) #Cria uma label que sera o background dos botoes do menu . #====== Botoes Menu ========= lbesp1 = Label(lm, bg="orange") lbesp1.grid(row=0, column=0) #Cria uma label de espaçamento entre o logo e a borda. iconome = PhotoImage(file="img/nomeico.png") lbnome = Label(lm) lbnome.config(image=iconome, highlightthickness=0, bd=0) #Cria uma label que adiciona o logo. lbnome.grid(row=0, column=1) lbesp2 = Label(lm, bg="orange") lbesp2.grid(row=0, column=2) #Cria uma label de espaçamento entre logo e salve. icosalve = PhotoImage(file="img/saveicon.png") btsalve = Button(lm, command=salva) btsalve.config(image=icosalve, highlightthickness=0, bd=0) #configura botão salve e coloca uma imagem nele. btsalve.grid(row=0, column=3)
class Robot(): """Documentation du robot image: stocke l'image du robot (doit etre de type .gif) coord_.: contient les coordonnées actuels du robot """ def __init__(self, labyrinthe): # ------------ Coordonnées sur écran ------------ self.coord_x = labyrinthe.robot_start_x * labyrinthe.largeur_carre self.coord_y = labyrinthe.robot_start_y * labyrinthe.hauteur_carre # ------------ Coordonnées logique ------------ self.logic_coord_x = labyrinthe.robot_start_y self.logic_coord_y = labyrinthe.robot_start_x # ------------ Chargement des images ------------ self.image_up = PhotoImage(file="up.gif") self.image_down = PhotoImage(file="down.gif") self.image_right = PhotoImage(file="right.gif") self.image_left = PhotoImage(file="left.gif") # ------------ Mise à l'échelle ------------ self.displayimage_up = self.image_up.subsample(2, 2) self.displayimage_down = self.image_down.subsample(2, 2) self.displayimage_right = self.image_right.subsample(2, 2) self.displayimage_left = self.image_left.subsample(2, 2) # ------------ Création de l'image ------------ self.display = labyrinthe.laby.create_image(self.coord_x, self.coord_y, anchor='nw', image=self.displayimage_up) self.ref_labyrinthe = labyrinthe # ------------ Variables pour l'animation de déplacement ------------ self.anim_count = 0 self.anim = False # ------------ Variables pour l'algorithme ------------ self.direction_actuel = 'Up' # ATTENTION INUTILISE self.direction_ancienne = 'Up' def move(self, direction): if direction == 'Left': new_coord_x = self.logic_coord_x new_coord_y = self.logic_coord_y - 1 if direction == 'Up': new_coord_x = self.logic_coord_x - 1 new_coord_y = self.logic_coord_y if direction == 'Right': new_coord_x = self.logic_coord_x new_coord_y = self.logic_coord_y + 1 if direction == 'Down': new_coord_x = self.logic_coord_x + 1 new_coord_y = self.logic_coord_y if self.ref_labyrinthe.test_case_vide(new_coord_x, new_coord_y): self.logic_coord_x = new_coord_x self.logic_coord_y = new_coord_y self.coord_x = self.logic_coord_x * self.ref_labyrinthe.largeur_carre self.coord_y = self.logic_coord_y * self.ref_labyrinthe.hauteur_carre self.animation(direction) def animation(self, direction): for i in range(1, 11): if direction == 'Up': self.ref_labyrinthe.laby.itemconfig(self.display, image=self.displayimage_up) self.ref_labyrinthe.laby.move(self.display, 0, -4) if direction == 'Left': self.ref_labyrinthe.laby.itemconfig(self.display, image=self.displayimage_left) self.ref_labyrinthe.laby.move(self.display, -4, 0) if direction == 'Down': self.ref_labyrinthe.laby.itemconfig(self.display, image=self.displayimage_down) self.ref_labyrinthe.laby.move(self.display, 0, 4) if direction == 'Right': self.ref_labyrinthe.laby.itemconfig(self.display, image=self.displayimage_right) self.ref_labyrinthe.laby.move(self.display, 4, 0) self.ref_labyrinthe.laby.update() time.sleep(0.025) def algo_droite(self): """ Le robot regarde toujours vers la droite afin de savoir s'il peut y aller en fonction de sa direction de base.""" # Si il partait vers la haut if self.direction_ancienne == 'Up': # On regarde s'il peut maintenant tourner à droite (par rapport à l'écran) if self.ref_labyrinthe.test_case_vide(self.logic_coord_x + 1, self.logic_coord_y): # On peut aller à droite donc on y va self.logic_coord_x += 1 self.coord_x = self.logic_coord_x * self.ref_labyrinthe.largeur_carre self.direction_ancienne = 'Right' self.animation('Up') # TODO: POUR LES 3 AUTRES RAJOUTER AUSSI LES TESTES # Si il partait vers le bas if self.direction_ancienne == 'Down': # On regarde s'il peut maintenant tourner à gauche (par rapport à l'écran) if self.ref_labyrinthe.test_case_vide(self.logic_coord_x - 1, self.logic_coord_y): self.logic_coord_x -= 1 self.coord_x = self.logic_coord_x * self.ref_labyrinthe.largeur_carre self.direction_ancienne = 'Left' self.animation('Down') if self.direction_ancienne == 'Right': # On regarde s'il peut maintenant tourner vers le bas (par rapport à l'écran) if self.ref_labyrinthe.test_case_vide(self.logic_coord_x, self.logic_coord_y + 1): self.logic_coord_y += 1 self.coord_y = self.logic_coord_y * self.ref_labyrinthe.hauteur_carre self.direction_ancienne = 'Down' self.animation('Down') if self.direction_ancienne == 'Left': # On regarde s'il peut maintenant tourner vers le haut (par rapport à l'écran) if self.ref_labyrinthe.test_case_vide(self.logic_coord_x, self.logic_coord_y - 1): self.logic_coord_y -= 1 self.coord_y = self.logic_coord_y * self.ref_labyrinthe.hauteur_carre self.direction_ancienne = 'Up' self.animation('Down')
class Image(object): def __init__(self, name): filepath = "images" + os.sep + name + ".gif" self.image = PhotoImage(file = filepath) self.copy = PhotoImage(file = filepath) def applyImageFilter(self, newFilename, filterFunction): image = self.image # Go through each pixel in the original for row in range(image.height()): for col in range(image.width()): (red, green, blue) = self.getRGB(col, row) # getRGB takes x and then y (newRed, newGreen, newBlue) = filterFunction(col, row, red, green, blue) self.setRGB(col, row, newRed, newGreen, newBlue) self.saveCopyToFolder(newFilename) def saveCopyToFolder(self, newFilename): filename = "output" + os.sep + newFilename + ".gif" self.copy.write(filename, format="gif") def getRGB(self, x, y): image = self.image value = image.get(x, y) return value def setRGB(self, x, y, red, green, blue): image = self.copy color = hexColor(red, green, blue) image.put(color, to=(x,y)) def greyScaleFilter(self, x, y, red, green, blue): grey = ( red + green + blue ) // 3 return (grey, grey, grey) def sephiaFilter(self, x, y, red, green, blue): sred = 236 sgreen = 207 sblue = 113 newRed = (2*sred + red) // 3 newGreen = (2*sgreen + green) // 3 newBlue = (2*sblue + blue) // 3 return (newRed, newGreen, newBlue) def invertFilter(self, x, y, red, green, blue): return (255-red, 255-green, 255-blue) def sephia(self, newFilename): print("Applying sephia filter...") self.applyImageFilter(newFilename, self.sephiaFilter) print("Finished!") def greyScale(self, newFilename): print("Applying grey scale filter...") self.applyImageFilter(newFilename, self.greyScaleFilter) print("Finished!") def invert(self, newFilename): print("Applying invert filter...") self.applyImageFilter(newFilename, self.invertFilter) print("Finished!")
def __init__(self, name): filepath = "images" + os.sep + name + ".gif" self.image = PhotoImage(file = filepath) self.copy = PhotoImage(file = filepath)
from tkinter import PhotoImage saveIcon = PhotoImage(file=r"icons/tick.png") closeIcon = PhotoImage(file=r"icons/close.png")
loadFrame = Frame(window) leaderFrame = Frame(window) insFrame = Frame(window) ins2Frame = Frame(window) usernameFrame = Frame(window) pauseFrame = Frame(window) bossFrame = Frame(window) mainMenuFrame.pack() window.bind(bossControl, boss) # ***************** # Main Menu Frame # ***************** menuBg = PhotoImage(file="assets/menu.png") menuCanvas = Canvas(mainMenuFrame, width=w, height=h, bg="white") menuCanvas.pack() menuCanvas.create_image(0, 0, image=menuBg, anchor="nw") back = Button(text="Play Game", font=("Courier", 20), command=canvasPack, width=15, activeforeground="green") menuCanvas.create_window(w / 2, 310, window=back) back = Button(text="Load Game", font=("Courier", 20), command=loadPack, width=15, activeforeground="green")
class EguanaGUI(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() # if not EguanaInit.eguana_root_dir_exists(): # EguanaInit.create_eguana_root_dir() def initUI(self): self.parent.title("EGUANA") self.style = ttk.Style() self.style.theme_use("alt") self.photoName = "eguana.gif" self.frame = Frame(self, relief=FLAT, borderwidth=10,bg='#FADC46') self.frame.pack(fill=BOTH, expand=True) self.pack(fill=BOTH, expand=True) self.setupMenuBar() self.setupTopBar() def setupMenuBar(self): self.menubar = EguanaMenu(self.parent,self) self.parent.config(menu=self.menubar) def setupTopBar(self): self.supportedDevices = [] for fileName in [name for name in os.listdir('./machineConfig') if os.path.isfile('./machineConfig/' + name) and not name == 'eguanaMachineConfig.py' and name.endswith('.py')]: # try:{ components = fileName.split('.') fileName = components[0] className = fileName[0].upper() + fileName[1:] try: module = __import__("machineConfig."+fileName,fromlist=["machineConfig."]) classVar = getattr(module,className) except: continue self.supportedDevices.append(classVar()) # except: # pass self.selectMachineFrame = Frame(self.frame,relief=FLAT,bg='#FADC46') self.selectMachineFrame.pack(fill=BOTH,expand=True) self.setupSelectMachineButtons() def setupSelectMachineButtons(self): numDevices = len(self.supportedDevices) numColumns = 3 numRows = math.ceil((numDevices+1)/3) self.photo = PhotoImage(file="eguana.gif") self.photo = self.photo.subsample(2); self.photo_label = Label(self.selectMachineFrame,image=self.photo,borderwidth=0,highlightthickness=0) self.photo_label.configure(bg='#FADC46') self.photo_label.grid(row=int(numRows/2),column=1, sticky=N+S+E+W,padx=2,pady =2) self.photo_label.image = self.photo index = 0 for i in range(numRows): for j in range(numColumns): if not(j == 1 and i == int(numRows/2)) and (index < numDevices): device = self.supportedDevices[index] b = Button(self.selectMachineFrame,text=device.name,relief=RAISED, command=lambda device=device :self.machineButtonPressed(device)) b.grid(row=i,column=j, sticky=N+S+E+W,padx=2,pady =2) index += 1 for i in range(numRows): self.selectMachineFrame.rowconfigure(i,weight=1) for i in range(numColumns): self.selectMachineFrame.columnconfigure(i,weight=1) def machineButtonPressed(self,inputDevice): dirStr = filedialog.askdirectory() if len(dirStr) and inputDevice.isDirectoryValid(dirStr): inputDevice.setDirPath(dirStr) EguanaModel().machine = inputDevice self.selectMachineFrame.destroy() self.menubar.inputSelected() self.photo_label.destroy() dirStr = 'Input Path : '+dirStr self.selectPlotFrame = Frame(self.frame, relief=FLAT,bg='#FADC46') self.selectPlotFrame.pack(fill=BOTH,expand=True) self.selectPlotFrame.rowconfigure(0,weight=1) self.selectPlotFrame.rowconfigure(1,weight=2) self.selectPlotFrame.columnconfigure(0,weight=1) self.infoFrame = Frame(self.selectPlotFrame, relief=FLAT, bg='#FADC46') self.infoFrame.grid(row=0,column=0, sticky=N+S+E+W,padx=2,pady =2) self.machineNameLabel = Label(self.infoFrame, text=inputDevice.name,relief=FLAT) self.machineNameLabel.grid(row=0,column=0,columnspan=2, sticky=N+S+E+W,padx=2,pady =2) self.directoryLabel = Label(self.infoFrame, text="No project currently selected",relief=FLAT) self.directoryLabel.grid(row=1,column=0,columnspan=2, sticky=N+S+E+W,padx=2,pady =2) self.directoryLabel.config(text=dirStr) self.outputDirButton = Button(self.infoFrame,text="No output directory selected. Click to select an output directory ",relief=RAISED,fg='red',command=self.askOutputDirectory) self.outputDirButton.grid(row=2,column=0,columnspan=2, sticky=N+S+E+W,padx=2,pady =2) self.filterButton = Button(self.infoFrame,text="No filter selected. Click to select a filter",relief=RAISED,fg='red',command=self.selectFilter) self.filterButton.grid(row=3,column=0,columnspan=2, sticky=N+S+E+W,padx=2,pady =2) self.trialLabel = Label(self.infoFrame,text="Trial Number",relief=FLAT,justify=RIGHT,anchor=E) self.trialLabel.grid(row=4,column=0, sticky=N+S+E+W,padx=2,pady =2) vcmd = (self.master.register(self.validate),'%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W') self.trialEntry = Entry(self.infoFrame,validate = 'key', validatecommand = vcmd) self.trialEntry.grid(row=4,column=1, sticky=N+S+E+W,padx=2,pady =2) self.infoFrame.columnconfigure(0, weight=1) self.infoFrame.columnconfigure(1, weight=1) self.infoFrame.rowconfigure(0, weight=1) self.infoFrame.rowconfigure(1, weight=10) self.infoFrame.rowconfigure(2, weight=10) self.infoFrame.rowconfigure(3, weight=10) self.infoFrame.rowconfigure(4, weight=10) self.showPlotTools() def validate(self, action, index, value_if_allowed, prior_value, text, validation_type, trigger_type, widget_name): if len(value_if_allowed)==0 : return True if text in '0123456789.-+ ': try: float(value_if_allowed) return True except ValueError: return False else: return False def askOutputDirectory(self): dirStr = filedialog.askdirectory() if len(dirStr): dirStr = 'Output Path : '+dirStr self.outputDirButton.config(text=dirStr) def showPlotTools(self): f2= Frame(self.selectPlotFrame, relief=FLAT,bg='#FADC46') f2.grid(row=1,column=0,sticky=N+S+E+W,padx=10,pady =10) b1 = Button(f2,text='3D K',relief=RAISED,command= lambda:self.plotButtonPressed(1)) b1.grid(row=0, column=0,sticky=N+S+E+W,padx=5,pady =5) b2 = Button(f2,text='3D Dist',relief=RAISED,command=lambda:self.plotButtonPressed(2)) b2.grid(row=0, column=1,sticky=N+S+E+W,padx=5,pady =5) b3 = Button(f2,text='3D DP',relief=RAISED,command=lambda:self.plotButtonPressed(3)) b3.grid(row=0, column=2,sticky=N+S+E+W,padx=5,pady =5) b4 = Button(f2,text='2D K',relief=RAISED,command=lambda:self.plotButtonPressed(4)) b4.grid(row=1, column=0,sticky=N+S+E+W,padx=5,pady =5) b5 = Button(f2,text='2D Dist',relief=RAISED,command=lambda:self.plotButtonPressed(5)) b5.grid(row=1, column=1,sticky=N+S+E+W,padx=5,pady =5) b6 = Button(f2,text='2D DP',relief=RAISED,command=lambda:self.plotButtonPressed(6)) b6.grid(row=1, column=2,sticky=N+S+E+W,padx=5,pady =5) b1.config(state=EguanaModel().machine.plot3DKButtonState) b2.config(state=EguanaModel().machine.plot3DDstButtonState) b3.config(state=EguanaModel().machine.plot3DDpButtonState) b4.config(state=EguanaModel().machine.plot2DKButtonState) b5.config(state=EguanaModel().machine.plot2DDstButtonState) b6.config(state=EguanaModel().machine.plot2DDpButtonState) f2.columnconfigure(0, weight=1) f2.columnconfigure(1, weight=1) f2.columnconfigure(2, weight=1) f2.rowconfigure(0, weight=1) f2.rowconfigure(1, weight=1) def plotButtonPressed(self,number): trialNum = self.trialEntry.get() try: trialNum = int(trialNum) print(EguanaModel().machine.ifTrialExists(trialNum)) if EguanaModel().machine.ifTrialExists(trialNum): self.plotFigure(number) return True else: messagebox.showerror( "Trial Number Error", "The trial doesn't exist" ) return False except ValueError: messagebox.showerror( "Trial Number Error", "Error with the trial number" ) return False def plotFigure(self,number): m = CoilNumDialog(self.frame) if m.isSet(): print(m.getValues()) EguanaModel().machine.getDataForTrialNumber(number) def selectFilter(self): ffPopup = FilterFunctionPopup(self) if ffPopup.selectedFilter is not None: EguanaModel().filterFunction = ffPopup.selectedFilter ftPopup = FilterTypePopup(self,ffPopup.selectedFilter) if (ftPopup.selectedHeadFilterType is not None) and (ftPopup.selectedHeadFilterType is not None): self.menubar.setSelectedFilters(ffPopup.selectedFilter,ftPopup.selectedHeadFilterType,ftPopup.selectedJawFilterType) EguanaModel().filterTypeHead = ftPopup.selectedHeadFilterType EguanaModel().filterTypeJaw = ftPopup.selectedJawFilterType EguanaModel().filterFunction = ffPopup.selectedFilter buttonText = '{} - Jaw Filter : {} - Head Filter {}'.format(ffPopup.selectedFilter.name,ftPopup.selectedJawFilterType.name, ftPopup.selectedHeadFilterType.name) self.filterButton.config(text=buttonText) def updateSelectedFilters(self,ffName,ftHeadName,ftJawName): buttonText = '{} - Jaw Filter : {} - Head Filter {}'.format(ffName,ftHeadName,ftJawName) self.filterButton.config(text=buttonText) def changeImage(self): self.photo = PhotoImage(file=self.photoName) self.photo = self.photo.subsample(2); self.photo_label.image = self.photo self.photo_label.config(image=self.photo) def cursorPosition(self,event): if event.widget == self.openButton3D: if self.photoName == "eguana2.gif": self.photoName = "eguana.gif" self.changeImage() elif event.widget == self.openButton2D: if self.photoName == "eguana.gif": self.photoName = "eguana2.gif" self.changeImage()
def DealerDeatiles(self, Name): self.Name = Name self.DateEntryForUpdate.destroy() self.RsEntryForUpdate.destroy() self.ProductEntryForUpdate.destroy() self.NOMEntryForUpdate.destroy() self.NetEntryForUpdate.destroy() self.TotalEntryForUpdate.destroy() self.updateDealer.destroy() self.DealerShowImage.destroy() try: self.AddDealer.destroy() except: pass self.ChangeDealer.destroy() self.HoleView.destroy() self.ScrollHoleView.destroy() self.AddressLabel1.destroy() self.AddressLabel2.destroy() self.PhoneLabel.destroy() Deal = PhotoImage(file=position + "/Requirements/contacts.png") self.DealerShowImageDL = ttk.Label(self.frame_ce, image=Deal, background="white") self.DealerShowImageDL.image = Deal self.DealerShowImageDL.place(x=450, y=20) self.DealerName.place(x=470, y=220) try: self.HoleViewForMoney.destroy() self.DateEntryForMoneyUpdate.destroy() self.TotalEntryForMoneyUpdate.destroy() self.CreditEntryForMoneyUpdate.destroy() self.DebitEntryForMoneyUpdate.destroy() self.ScrollHoleMoneyView.destroy() except: pass self.DistributorNameReUpdate = StringVar() self.CompanyNameReUpdate = StringVar() self.PhoneNameForDisReUpdate = StringVar() with sql.connect(position + "/Pass/%s" % self.database) as DealerData: DD = DealerData.cursor() DD.execute( ''' SELECT * FROM %s WHERE %s = (?)''' % (self.DorC, self.CNorCN), (self.Name, )) self.dataForReUp = DD.fetchall() DealerData.commit() self.NameEntryForDisReUpdate = ttk.Entry( self.frame_ce, textvar=self.DistributorNameReUpdate, foreground="black", width=25, font=("Helvetica", 20)) self.NameEntryForDisReUpdate.place(x=360, y=300, height=50) self.NameEntryForDisReUpdate.insert(0, str(self.dataForReUp[0][2])) self.AddressEntryReUpdate = Text(self.frame_ce, foreground="black", width=25, font=("Helvetica", 20), relief="ridge") self.AddressEntryReUpdate.place(x=360, y=375, height=100) self.AddressEntryReUpdate.insert(END, str(self.dataForReUp[0][3])) self.PhoneEntryReUpdate = ttk.Entry( self.frame_ce, textvar=self.PhoneNameForDisReUpdate, foreground="black", width=25, font=("Helvetica", 20)) self.PhoneEntryReUpdate.place(x=360, y=495, height=50) self.PhoneEntryReUpdate.insert(0, str(self.dataForReUp[0][4])) def updateChangeReUp(event): if str(event)[1:6] == "Enter": ImageName = "/Requirements/UpdateUp.png" elif str(event)[1:6] == "Leave": ImageName = "/Requirements/Update.png" self.CustomerImageChangeReUp = PhotoImage(file=position + ImageName) self.updateCustomerReUp.configure( image=self.CustomerImageChangeReUp) self.updateCustomerReUp.image = self.CustomerImageChangeReUp self.CustomerImageReUp = PhotoImage(file=position + "/Requirements/Update.png") self.updateCustomerReUp = ttk.Label(self.frame_ce, image=self.CustomerImageReUp, background="white") self.updateCustomerReUp.image = self.CustomerImageReUp self.updateCustomerReUp.place(x=460, y=570) self.updateCustomerReUp.bind("<Enter>", updateChangeReUp) self.updateCustomerReUp.bind("<Leave>", updateChangeReUp) self.updateCustomerReUp.bind("<Button-1>", lambda event: self.ReUpdate(self.Name))
from tkinter import Tk, Label, PhotoImage, BOTH, RIGHT, LEFT root = Tk() label1 = Label(root, text='Peace & Love', background='black', width=20, height=5, foreground='white', font=('Helvetica', 18, 'italic')) label1.pack(side=LEFT) photo = PhotoImage(file='peace.gif') label2 = Label(root, image=photo) label2.pack(side=RIGHT, expand=True, fill=BOTH) root.mainloop()
def video_stream_loop(self) -> None: self.img: PhotoImage = PhotoImage(file=self.image_name) self.label.imgtk = self.img self.label.configure(image=self.img)
def changeImage(self): self.photo = PhotoImage(file=self.photoName) self.photo = self.photo.subsample(2); self.photo_label.image = self.photo self.photo_label.config(image=self.photo)
class Example(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() def initUI(self): self.parent.title("EGUANA") self.style = ttk.Style() self.style.theme_use("alt") self.photoName = "eguana.gif" self.frame = Frame(self, relief=FLAT, borderwidth=10,bg='#FADC46') self.frame.pack(fill=BOTH, expand=True) self.pack(fill=BOTH, expand=True) self.setupMenuBar() self.setupTopBar() def setupMenuBar(self): self.menubar = EguanaMenu(self.parent,self) self.parent.config(menu=self.menubar) def setupTopBar(self): self.openButton3D = Button(self.frame,text="Select Directory for 3D EMA",relief=RAISED,command=self.askDirectory) self.openButton3D.grid(row=0,column=0, sticky=N+S+E+W,padx=2,pady =2) self.openButton2D = Button(self.frame,text="Select Directory for 2D EMA",relief=RAISED,command=self.askDirectory); self.openButton2D.grid(row=2,column=2, sticky=N+S+E+W,padx=2,pady =2) self.p1Button = Button(self.frame,text="Placeholder",relief=RAISED) self.p1Button.grid(row=0,column=1, sticky=N+S+E+W,padx=2,pady =2) self.p2Button = Button(self.frame,text="Placeholder",relief=RAISED) self.p2Button.grid(row=0,column=2, sticky=N+S+E+W,padx=2,pady =2) self.p3Button = Button(self.frame,text="Placeholder",relief=RAISED) self.p3Button.grid(row=1,column=0, sticky=N+S+E+W,padx=2,pady =2) self.p4Button = Button(self.frame,text="Placeholder",relief=RAISED) self.p4Button.grid(row=1,column=2, sticky=N+S+E+W,padx=2,pady =2) self.p5Button = Button(self.frame,text="Placeholder",relief=RAISED) self.p5Button.grid(row=2,column=0, sticky=N+S+E+W,padx=2,pady =2) self.p6Button = Button(self.frame,text="Placeholder",relief=RAISED) self.p6Button.grid(row=2,column=1, sticky=N+S+E+W,padx=2,pady =2) self.openButton3D.bind('<Motion>',self.cursorPosition) self.openButton2D.bind('<Motion>',self.cursorPosition) self.photo = PhotoImage(file="eguana.gif") self.photo = self.photo.subsample(2); self.photo_label = Label(self.frame,image=self.photo,borderwidth=0,highlightthickness=0) self.photo_label.configure(bg='#FADC46') self.photo_label.grid(row=1,column=1, sticky=N+S+E+W,padx=2,pady =2) self.photo_label.image = self.photo self.frame.columnconfigure(0, weight=1) self.frame.columnconfigure(1, weight=1) self.frame.columnconfigure(2, weight=1) self.frame.rowconfigure(0, weight=1) self.frame.rowconfigure(1, weight=1) self.frame.rowconfigure(2, weight=1) def askDirectory(self): dirStr = filedialog.askdirectory() if len(dirStr): self.openButton3D.destroy() self.openButton2D.destroy() self.p1Button.destroy() self.p2Button.destroy() self.p3Button.destroy() self.p4Button.destroy() self.p5Button.destroy() self.p6Button.destroy() self.menubar.entryconfigure('Filter', state = 'active') self.photo_label.destroy() dirStr = 'Input Path : '+dirStr self.frame.grid_forget() self.infoFrame = Frame(self.frame, relief=FLAT, bg='#FADC46') self.infoFrame.grid(row=0,column=0,columnspan=3, sticky=N+S+E+W,padx=2,pady =2) self.directoryLabel = Label(self.infoFrame, text="No project currently selected",relief=FLAT) self.directoryLabel.grid(row=0,column=0,columnspan=2, sticky=N+S+E+W,padx=2,pady =2) self.directoryLabel.config(text=dirStr) self.outputDirButton = Button(self.infoFrame,text="No output directory selected. Click to select an output directory ",relief=RAISED,fg='red',command=self.askOutputDirectory) self.outputDirButton.grid(row=1,column=0,columnspan=2, sticky=N+S+E+W,padx=2,pady =2) self.filterButton = Button(self.infoFrame,text="No filter selected. Click to select a filter",relief=RAISED,fg='red',command=self.selectFilter) self.filterButton.grid(row=2,column=0,columnspan=2, sticky=N+S+E+W,padx=2,pady =2) self.trialLabel = Label(self.infoFrame,text="Trial Number",relief=FLAT,justify=RIGHT,anchor=E) self.trialLabel.grid(row=3,column=0, sticky=N+S+E+W,padx=2,pady =2) vcmd = (self.master.register(self.validate),'%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W') self.trialEntry = Entry(self.infoFrame,validate = 'key', validatecommand = vcmd) self.trialEntry.grid(row=3,column=1, sticky=N+S+E+W,padx=2,pady =2) self.infoFrame.columnconfigure(0, weight=1) self.infoFrame.columnconfigure(1, weight=1) self.infoFrame.rowconfigure(0, weight=1) self.infoFrame.rowconfigure(1, weight=1) self.infoFrame.rowconfigure(2, weight=1) self.infoFrame.rowconfigure(3, weight=1) self.showPlotTools() def validate(self, action, index, value_if_allowed, prior_value, text, validation_type, trigger_type, widget_name): if len(value_if_allowed)==0 : return True if text in '0123456789.-+ ': try: float(value_if_allowed) return True except ValueError: return False else: return False def askOutputDirectory(self): dirStr = filedialog.askdirectory() if len(dirStr): dirStr = 'Output Path : '+dirStr self.outputDirButton.destroy() self.outputDirLabel = Label(self.infoFrame, relief=FLAT) self.outputDirLabel.grid(row=1,column=0,columnspan=2, sticky=N+S+E+W,padx=2,pady =2) self.outputDirLabel.config(text=dirStr) def showPlotTools(self): f2= Frame(self.frame, relief=FLAT,bg='#FADC46') f2.grid(row=1,column=0,rowspan=2,columnspan=3,sticky=N+S+E+W,padx=10,pady =10) b1 = Button(f2,text='3D K',relief=RAISED,command= lambda:self.plotButtonPressed(1)) b1.grid(row=0, column=0,sticky=N+S+E+W,padx=5,pady =5) b2 = Button(f2,text='3D Dist',relief=RAISED,command=lambda:self.plotButtonPressed(2)) b2.grid(row=0, column=1,sticky=N+S+E+W,padx=5,pady =5) b3 = Button(f2,text='3D DP',relief=RAISED,command=lambda:self.plotButtonPressed(3)) b3.grid(row=0, column=2,sticky=N+S+E+W,padx=5,pady =5) b4 = Button(f2,text='2D K',relief=RAISED,command=lambda:self.plotButtonPressed(4)) b4.grid(row=1, column=0,sticky=N+S+E+W,padx=5,pady =5) b5 = Button(f2,text='2D Dist',relief=RAISED,command=lambda:self.plotButtonPressed(5)) b5.grid(row=1, column=1,sticky=N+S+E+W,padx=5,pady =5) b6 = Button(f2,text='2D DP',relief=RAISED,command=lambda:self.plotButtonPressed(6)) b6.grid(row=1, column=2,sticky=N+S+E+W,padx=5,pady =5) f2.columnconfigure(0, weight=1) f2.columnconfigure(1, weight=1) f2.columnconfigure(2, weight=1) f2.rowconfigure(0, weight=1) f2.rowconfigure(1, weight=1) def plotButtonPressed(self,number): trialNum = self.trialEntry.get() try: trialNum = float(trialNum) if trialNum < 16 and trialNum > 0: self.plotFigure(number) return True else: messagebox.showerror( "Trial Number Error", "The trial number is out of range" ) return False except ValueError: messagebox.showerror( "Trial Number Error", "Error with the trial number" ) return False def plotFigure(self,number): m = CoilNumDialog(self.frame) if m.isSet(): print(m.getValues()) def selectFilter(self): self.top = FilterPopup(self); def speech3DButtonPressed(self): self.menubar.filterSelected(0) self.top.destroy() if hasattr(self, 'filterLabel'): self.filterLabel.config(text="Filter : speech3D") else: self.filterLabel = Label(self.infoFrame, text="Filter : speech3D",relief=FLAT) self.filterLabel.grid(row=2,column=0,columnspan=2, sticky=N+S+E+W,padx=2,pady =2) self.filterButton.destroy() def speech2DButtonPressed(self): self.menubar.filterSelected(1) self.top.destroy() if hasattr(self, 'filterLabel'): self.filterLabel.config(text="Filter : speech2D") else: self.filterLabel = Label(self.infoFrame, text="Filter : speech2D ",relief=FLAT) self.filterLabel.grid(row=2,column=0,columnspan=2, sticky=N+S+E+W,padx=2,pady =2) self.filterButton.destroy() def swallow3DButtonPressed(self): self.menubar.filterSelected(2) self.top.destroy() if hasattr(self, 'filterLabel'): self.filterLabel.config(text="Filter : swallow3D") else: self.filterLabel = Label(self.infoFrame, text="Filter : swallow3D ",relief=FLAT) self.filterLabel.grid(row=2,column=0,columnspan=2, sticky=N+S+E+W,padx=2,pady =2) self.filterButton.destroy() def swallow2DButtonPressed(self): self.menubar.filterSelected(3) self.top.destroy() if hasattr(self, 'filterLabel'): self.filterLabel.config(text="Filter : swallow2D") else: self.filterLabel = Label(self.infoFrame, text="Filter : swallow2D ",relief=FLAT) self.filterLabel.grid(row=2,column=0,columnspan=2, sticky=N+S+E+W,padx=2,pady =2) self.filterButton.destroy() def changeImage(self): self.photo = PhotoImage(file=self.photoName) self.photo = self.photo.subsample(2); self.photo_label.image = self.photo self.photo_label.config(image=self.photo) def cursorPosition(self,event): if event.widget == self.openButton3D: if self.photoName == "eguana2.gif": self.photoName = "eguana.gif" self.changeImage() elif event.widget == self.openButton2D: if self.photoName == "eguana.gif": self.photoName = "eguana2.gif" self.changeImage()
from tkinter import Tk, Canvas, PhotoImage, mainloop WIDTH, HEIGHT, ITERATIONS = 400, 400, 400 window = Tk() canvas = Canvas(window, width=WIDTH, height=HEIGHT, bg="#000000") canvas.pack() img = PhotoImage(width=WIDTH, height=HEIGHT) canvas.create_image((WIDTH/2, HEIGHT/2), image=img, state="normal") def mandlebrot(c): z = complex(0,0) for i in range(ITERATIONS): z = z*z + c if (z.real*z.real + z.imag*z.imag) >= 4: return i return ITERATIONS for x in range(WIDTH): for y in range(HEIGHT): color = mandlebrot(complex((4*x/WIDTH) - 2.5,(4*y/HEIGHT) - 2)) color = color if color <= 255 else 255 img.put('#%02x%02x%02x' % (color%255,(40*(color//255))%4,10*((40*(color//255))//4)),(x,y)) mainloop()
class IO: def __init__(self, thread): # set up screen, width = 512, height = 256 self.mythread = thread self.screen = Tk() self.screen.title("Jarvis Simulator") self.screen.geometry("512x256+1600+500") self.screen.wm_maxsize(width=512, height=256) self.screen.wm_minsize(width=512, height=256) self.screen.wm_resizable(width=False, height=False) self.image = PhotoImage(width = 512, height = 256) self.label = Label(self.screen, image=self.image) self.label.grid() # set up keyboard for c in self.Keycodes.keys(): exec("self.screen.bind(\"<%s>\", self.%s)" % (c, c)) self.screen.bind("<Any-KeyPress>", self.KeyPressed) self.screen.bind("<Any-KeyRelease>", self.KeyReleased) system("xset r off") self.screen.protocol("WM_DELETE_WINDOW", self.delete_callback) def delete_callback(self): system("xset r on") self.mythread.stop() self.screen.destroy() KBD = 0 Keycodes = { "Return" : 128, "BackSpace" : 129, "Left" : 130, "Up" : 131, "Right" : 132, "Down" : 133, "Home" : 134, "End" : 135, "Prior" : 136, "Next" : 137, "Insert" : 138, "Delete" : 139, "Escape" : 140 } for i in range(1,13): k = { "F" + str(i) : 140+i } Keycodes.update(k) for key in Keycodes.keys(): code = Keycodes[key] exec("""def %s(self, event): self.KBD = %s if debugKBD: print(%s)""" % (key, code, code)) def KeyPressed(self, event): if event.char: self.KBD = ord(event.char) if debugKBD: print(str(ord(event.char))) def KeyReleased(self, event): self.KBD = 0 if debugKBD: print("Key Released.\n") def drawFill(self, color): horizontal_line = "{" + " ".join([color]*self.image.width()) + "}" self.image.put(" ".join([horizontal_line] * self.image.height())) def drawPoint(self, x, y, color): #~ print("Drawing %s point at (%i, %i)" % (color, x, y)) self.image.put(color, (x, y)) def drawmem(self, location, value): (y, x) = divmod(location,32) x = x * 16 memword = binary(value, bits=16) for i in range(0, 16): if memword[15-i] == '1': self.drawPoint(x+i, y, "green") else: self.drawPoint(x+i, y, "black")
def draw_gradient(canvas): img = PhotoImage(width=WIDTH, height=HEIGHT) canvas.create_image((WIDTH/2, HEIGHT//2), image=img, state="normal") # range(10) => (0, 1, 2, ..., 9) # range(5, 10) => (5, 6, 7, 8, 9) # range(5, 15, 2) => (5, 7, 9, 11, 13) for j in range(0, HEIGHT): for i in range(0, WIDTH): # RGB = red, green, blue # диапазон цвета: 0..255, 0x00..0xFF img.put("#%02x%02x%02x" % (i % 128, j % 128, 0), (i, j)) return img
class ImageFrame: 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')