def check_titles_fn(): show_titles_window = tk.Tk() show_titles_window.title("Check titles") show_titles_window.resizable(False, False) show_titles_window.eval( f"tk::PlaceWindow {show_titles_window.winfo_pathname(show_titles_window.winfo_id())} center" ) with open(r"data/all_reminds.json", "r") as ar: all_reminds = json.load(ar) list_of_titles = [] for i in range(len(all_reminds["data"])): list_of_titles.append(all_reminds["data"][i]["title"]) sf = ScrolledFrame(show_titles_window, width=170, height=150) sf.pack(side="top", expand=1, fill="y") sf.bind_arrow_keys(show_titles_window) sf.bind_scroll_wheel(show_titles_window) scroll_frame = sf.display_widget(tk.Frame) for i in range(len(list_of_titles)): current_title = list_of_titles[i] title_label = tk.Label( master=scroll_frame, text=f"{i}. {current_title}", font=fonts.Calibri_15, padx=10, ) title_label.grid(row=i, column=1, pady=5)
def __init__(self, root): sf = ScrolledFrame(root, width=640, height=480) sf.pack(side="top", expand=1, fill="both") # Bind the arrow keys and scroll wheel sf.bind_arrow_keys(root) sf.bind_scroll_wheel(root) # Create a frame within the ScrolledFrame self.frm_parent = sf.display_widget(Frame) # container = Frame(root) # canvas = tk.Canvas(container) # scrollbar = Scrollbar(container, orient="vertical", command=canvas.yview) # self.frm_parent = Frame(canvas) # # self.frm_parent.bind( # "<Configure>", # lambda e: canvas.configure( # scrollregion=canvas.bbox("all") # ) # ) # canvas.create_window((0, 0), window=self.frm_parent, anchor="nw") # # canvas.configure(yscrollcommand=scrollbar.set) # for i in range(50): # Label(scrollable_frame, text="Sample scrolling label").pack() # self.frm_parent = Frame() self.initialize_components() self.frm_child = FormChildQuiz(self.frm_parent)
def print_news(): db, cursor = db_conn() cursor.execute("SELECT title, description FROM newsdata") db_result = cursor.fetchall() # GUI data_frame = tk.Frame(window) data_frame.pack(side="left", expand=0, fill="y") sf = ScrolledFrame(data_frame, width=1128, bg='#ffffff') sf.pack(side="left", expand=1, fill="y") # Bind the arrow keys and scroll wheel sf.bind_arrow_keys(window) sf.bind_scroll_wheel(window) frame = sf.display_widget(tk.Frame) frame['bg'] = '#E8E7F7' frame['bd'] = 15 frame['relief'] = 'sunken' for news in db_result: # Title Label l = tk.Label(text=news[0], bg='#E8E7F7', fg='#3f0052', wraplength=1070, master=frame, font="-size 18 -weight bold", justify='left', pady='10') l.pack() # Description Label l = tk.Label(text=news[1], bg='#DEDEDE', fg='#3f0052', wraplength=1070, master=frame, font="-size 14", justify='left', padx='15') l.pack() # Separator l = tk.Label( text= '--------------------------------------------------------------------------------------------------', bg='#E8E7F7', fg='#3f0052', wraplength=1070, master=frame, font="-size 14", justify='left', pady='25') l.pack() button3['state'] = 'disabled' window.mainloop()
def beginSearch(event): global cursor global inner_frame global sf global authorKey #удаление прокручиваемого блока, если он существует if(not(inner_frame is None)): inner_frame.destroy() sf.destroy() sf1.configure(highlightbackground="#ffffff") #Создание прокручиваемого блока sf = ScrolledFrame(root, width=640, height=480, highlightthickness=5, highlightbackground="red") sf.itemId=0 sf.pack(side="top", expand=1, fill="both") sf.bind_arrow_keys(root) sf.bind_scroll_wheel(root) sf.bind("<Enter>", hoverFrame) inner_frame = sf.display_widget(Frame, True) #параметры обработанных статей author = "author" theme = "theme" name = "name" link = "link" author_inputted = getAuthor(authorKey.get()) print(author_inputted) keywords = [] for s in getKeywords(boolArr): keywords.append(s) command = "select Book.Name,Book.Author,Book.Cloud_Link, Book.Language, Book.Format from Book" command += """\njoin BookKeyWord on Book.Id = BookKeyWord.Book_Id\njoin KeyWord on BookKeyWord.KeyWord_Id = KeyWord.Id""" keywords_count = len(keywords) if keywords_count > 0: command = command + "\nwhere Keyword.Name = N'###KEYWORD###'" pattern = command for i in range(keywords_count): if i != 0: command = command + "\nintersect\n" + pattern.replace("###KEYWORD###",keywords[i]) else: command = command.replace("###KEYWORD###",keywords[i]) if not (author_inputted == "ЛЮБОЙ"): command = command + " and Book.Author = N'" + author_inputted + "'" else: if not (author_inputted == "ЛЮБОЙ"): command = command + "\nwhere Book.Author = N'" + author_inputted + "'" print(command) cursor.execute(command) for book in cursor.fetchall(): printArticle(book[1], book[0], book[2], book[3], book[4], inner_frame) """
class App(Frame): def __init__(self): Frame.__init__(self, highlightbackground='blue', highlightthickness=4) self.pack(side=TOP, expand=YES, fill=BOTH, anchor=NW) self.master.title('Canvas-and-Painters: Grid') #self.make_modelcanvasframe() #self.make_painterframe() leftframe = Frame(self) leftframe.pack(side=LEFT, expand=NO, fill=None, anchor=NW) self.gridw = GridWidget(leftframe) self.gridw.pack(side=TOP, anchor=NW, padx=3, pady=3) Button(leftframe, text='Small seed', command=self.small_seed).pack(side=LEFT, expand=YES) Button(leftframe, text='Step', command=self.step).pack(side=LEFT, expand=YES) self.bind_all('<s>', self.step) self.painterframe = ScrolledFrame(self) #self.paintertable = SimpleTable(self.painterframe) self.painterframe.display_widget(SimpleTable) self.painterframe.pack(side=LEFT, expand=YES, fill=BOTH) self.small_seed() def key(self, event): print(event) def small_seed(self): self.model = make_small_seed_model() self.draw_model() def draw_model(self): self.gridw.draw_gc(self.model.c) for row, (rpainter, activation) in enumerate( self.model.ltsoup.rpainters.items() ): #self.rightframe.set(row, 0, sstr(rpainter)) #self.rightframe.set(row, 1, str(activation)) pass def step(self, event=None): print(event) self.model.iteration() self.draw_model()
def beginSearch(event): global inner_frame global sf #удаление прокручиваемого блока, если он существует if(not(inner_frame is None)): inner_frame.destroy() sf.destroy() sf1.configure(highlightbackground="#ffffff") #Создание прокручиваемого блока sf = ScrolledFrame(root, width=640, height=480, highlightthickness=5, highlightbackground="red") sf.pack(side="top", expand=1, fill="both") sf.bind_arrow_keys(root) sf.bind_scroll_wheel(root) inner_frame = sf.display_widget(Frame, True) #параметры обработанных статей author = "author" theme = "theme" name = "name" link = "link" #themeInputted = inputTheme.get() authors_arrInputted = getAuthors(boolArrAuth) for s in authors_arrInputted: print(s+"\n") #получение массива выбранных ключевых слов keywords_arrInputted = getKeywords(boolArr) for s in keywords_arrInputted: print(s+"\n") for i in range(1,random.randint(0,16)): printArticle(author, theme, name, link, inner_frame)
#поле ввода темы #inputTheme = Entry(fr1, width = 70, font = "Arial 13") #inputTheme.pack(ipady = 8) #------------------------------------------------------------------------------------------------ #второй фрейм #------------------------------------------------------------------------------------------------ fr2 = Frame(bg="#ffffff", width = 100) #подсказка для пользователя Label(fr2, text="Автор:", width = 100, height = 2, font="Arial 13").pack() #Создание прокручиваемого блока для кчпичка авторов sf2 = ScrolledFrame(fr2, width=880, height=100, highlightthickness=5, highlightbackground="#ffffff") sf2.pack(side="top", expand=0) sf2.bind_arrow_keys(root) sf2.bind_scroll_wheel(root) frame_authors = sf2.display_widget(Frame, True) #значения выпадающего списка arrAuth = ["author1","author2","author3","author4", "author5", "author6"] #количество значений в списке(нужно для программы) length1 = len(arrAuth) #массив булеан значений, сопоставляемый списку boolArrAuth = [] for i in range(0, length1): boolArrAuth.append(BooleanVar()) boolArrAuth[i].set(0)
media_list = update_ml() root = tk.Tk() root.title("Nate's Media Manager") mainframe = tk.Frame(root, height=800, width=600) mainframe.pack(fill=BOTH, expand=True, padx=10, pady=10) command_frame = tk.Frame(mainframe, borderwidth=2) command_frame.pack(side=TOP, expand=False, fill=X) add_media_button = tk.Button(command_frame, text="Add Media Files", command=add_media_files) add_media_button.pack(side=LEFT) refresh_button = tk.Button(command_frame, text="Refresh", command=populate_ml) refresh_button.pack(side=RIGHT) media_list_frame = ScrolledFrame(mainframe, scrollbars='both') media_list_frame.pack(side=TOP, expand=True, fill=BOTH) inner_frame = media_list_frame.display_widget(Frame) name_header = tk.Label(inner_frame, text="Name", borderwidth=2, justify=CENTER, relief=GROOVE) name_header.grid(row=0, column=0, sticky=N, columnspan=True) root_header = tk.Label(inner_frame, text="Root", borderwidth=2, justify=CENTER, relief=GROOVE) root_header.grid(row=0, column=1, sticky=N, columnspan=True) watched_header = tk.Label(inner_frame, text="Watched", borderwidth=2, justify=CENTER, relief=GROOVE) watched_header.grid(row=0, column=2, sticky=N, columnspan=True) play_header = tk.Label(inner_frame, text="Play", borderwidth=2, justify=CENTER, relief=GROOVE) play_header.grid(row=0, column=3, sticky=N, columnspan=True) populate_ml()
def select_all(self, table, column, equals): if self.isConnected: self.repeat_login() try: self.mycursor.execute(f"SHOW COLUMNS FROM {table};") except mysql.connector.Error as err: self.fail_window(err) else: selectedwindow = tk.Tk() selectedwindow.title(table) scroll = ScrolledFrame(master=selectedwindow, width=720, height=720) scroll.pack() scrollframe = scroll.display_widget(tk.Frame) othercolumns = list() othertables = list() currentcolumns = list() restraints = list() constrained = False for x in self.mycursor: currentcolumns.append(x[0]) for x in currentcolumns: self.mycursor.execute( f"SELECT TABLE_NAME, COLUMN_NAME, CONSTRAINT_NAME, REFERENCED_TABLE_NAME, REFERENCED_COLUMN_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE REFERENCED_TABLE_SCHEMA = 'animalute' AND TABLE_NAME = '{table}' AND COLUMN_NAME = '{x}';" ) myresult = self.mycursor.fetchall() if myresult and othertables.count(myresult[0][3]) == 0: self.mycursor.execute( f"SHOW COLUMNS FROM {myresult[0][3]}") for y in self.mycursor: othertables.append(myresult[0][3]) othercolumns.append(y[0]) if myresult: restraints.append( [table, x, myresult[0][3], myresult[0][4]]) constrained = True print(othertables) print(othercolumns) print(currentcolumns) print(restraints) sql = "SELECT " if constrained: index = 0 for x in othertables: sql += f"{x}.{othercolumns[index]}, " index += 1 for x in currentcolumns: sql += f"{table}.{x}, " sql = sql[0:(len(sql) - 2)] sql += f" FROM {table} " if constrained: for x in restraints: sql += f"INNER JOIN {x[2]} ON {x[0]}.{x[1]} = {x[2]}.{x[3]} " if column: sql += f" WHERE {table}.{column} = '{equals.get()}'" print(column) print(equals.get()) print(sql) mycolumn = 0 for x in othercolumns: frame = tk.Frame(master=scrollframe, relief="groove", borderwidth=1, bg="crimson") label = tk.Label(master=frame, text=x, bg="crimson", fg="white") frame.grid(column=mycolumn, row=0, sticky="ew") label.pack() mycolumn += 1 for x in currentcolumns: frame = tk.Frame(master=scrollframe, relief="groove", borderwidth=1, bg="crimson") label = tk.Label(master=frame, text=x, bg="crimson", fg="white") frame.grid(column=mycolumn, row=0, sticky="ew") label.pack() mycolumn += 1 myrow = 1 try: self.mycursor.execute(sql) except mysql.connector.Error as err: self.fail_window(err) else: myresult = self.mycursor.fetchall() for y in myresult: mycolumn = 0 for x in y: frame = tk.Frame(master=scrollframe, relief="groove", borderwidth=1) label = tk.Label(master=frame, text=x) if myrow % 2: frame["bg"] = "aliceblue" label["bg"] = "aliceblue" else: frame["bg"] = "white" label["bg"] = "white" frame.grid(column=mycolumn, row=myrow, sticky="ew") label.pack() mycolumn += 1 myrow += 1 else: self.fail_window("Can not operate without connection!")
class ImageViewer(): def __init__(self, root_window, insta_id = None, insta_password = None): self.insta_bot_logged_in = False if insta_id is not None: self.insta_bot = Bot() self.camera_info = '' self.camera_hashtags = '' self.current_image_pil = None self.current_image_proxy_pil = None self.proxy_file_exists = None # Calling the Tk (The intial constructor of tkinter) self.root = root_window # The geometry of the box which will be displayed # on the screen self.root.geometry("1400x1000") #self.fr_buttons_scr = tk.Frame(self.root, relief=tk.RAISED, bd=2) #self.fr_buttons_scr.pack(side=tk.LEFT, fill=tk.Y) #self.fr_buttons = Scrollable(self.fr_buttons_scr) #self.fr_buttons_scr = ScrollableFrame(self.root, relief=tk.RAISED, bd=2) #self.fr_buttons_scr = ScrollableFrame(self.root, relief=tk.RAISED, bd=2) #self.fr_buttons_scr.pack(side=tk.LEFT, fill=tk.Y) #self.fr_buttons = self.fr_buttons_scr.scrollable_frame self.fr_buttons_scr = ScrolledFrame(self.root, width=600, relief=tk.RAISED, bd=2, scrollbars='vertical') self.fr_buttons_scr.pack(side=tk.LEFT, fill=tk.BOTH) self.fr_buttons_scr.bind_arrow_keys(root) self.fr_buttons_scr.bind_scroll_wheel(root) self.fr_buttons = self.fr_buttons_scr.display_widget(tk.Frame) #self.fr_buttons.grid(row=0, column=0, columnspan=1, sticky="ew", pady=5) self.sld_scale_val = tk.DoubleVar(value=1.0) self.sld_scale = tk.Scale(self.fr_buttons, from_ = 0.0, to = 4.0, resolution=0.1, orient=tk.HORIZONTAL, variable=self.sld_scale_val, command=self._scale_update) # range will be set at the end of the initialisation self.sld_imgidx_val = tk.IntVar(value=1) self.sld_imgidx = tk.Scale(self.fr_buttons, from_ = 1, to = 1, resolution=1, orient=tk.HORIZONTAL, variable=self.sld_imgidx_val, command=self._imgidx_update) self.chk_show_uploaded_val = tk.IntVar(value=1) self.chk_show_uploaded = tk.Checkbutton(self.fr_buttons, text='show uploaded', variable=self.chk_show_uploaded_val, command=self._on_show_tagged_untagged) self.chk_show_not_uploaded_val = tk.IntVar(value=1) self.chk_show_not_uploaded = tk.Checkbutton(self.fr_buttons, text='show not uploaded', variable=self.chk_show_not_uploaded_val, command=self._on_show_tagged_untagged) self.chk_show_untagged_val = tk.IntVar(value=1) self.chk_show_untagged = tk.Checkbutton(self.fr_buttons, text='show untagged', variable=self.chk_show_untagged_val, command=self._on_show_tagged_untagged) self.chk_use_proxy_val = tk.IntVar(value=1) self.chk_use_proxy = tk.Checkbutton(self.fr_buttons, text='Use proxy if available', variable=self.chk_use_proxy_val, command=self._on_use_proxy) self.chk_use_exif_val = tk.IntVar(value=0) self.chk_use_exif = tk.Checkbutton(self.fr_buttons, text='Use EXIF metadata if available (slow)', variable=self.chk_use_exif_val, command=self._on_use_exif) self.btn_last_edited = tk.Button(self.fr_buttons, text="Move to last edited", command=self._on_click_last_edited) self.btn_upload_insta = tk.Button(self.fr_buttons, text="Upload to Instagram", command=self._on_click_upload_insta) # root.quit for closing the app self.btn_exit = tk.Button(self.fr_buttons, text="Exit", command=self.root.quit) # We will have three button back ,forward and exit self.btn_fast_back = tk.Button(self.fr_buttons, text="<< Fast Backward", command=self.fast_back, state=tk.DISABLED) self.btn_back = tk.Button(self.fr_buttons, text="< Back", command=self.back, state=tk.DISABLED) self.txt_description = ScrolledText(self.fr_buttons, width=50, height=5, ) self.config = json.load(open(os.path.join(SCRIPT_DIRPATH, 'config.json'), 'r', encoding='utf8'), object_pairs_hook=OrderedDict) self.hashtag_groups = self.config['hashtag_groups'] self.hashtag_groups_indices = {k:i for i,k in enumerate(self.hashtag_groups.keys())} self.images_basedir = self.config['images_basedir'] self.images_proxydir = self.config['images_proxydir'] self.images_outputdir = self.config['images_outputdir'] self.hashtag_group_chkbtns = [] self.hashtag_group_chkbtn_vals = [] for idx, (key, val) in enumerate(self.hashtag_groups.items()): self.hashtag_group_chkbtn_vals.append(tk.IntVar()) # when using lambda, use default parameter idx=idx to avoid late-binding issue (otherwise `idx` is bound when the function is called) self.hashtag_group_chkbtns.append(tk.Checkbutton(self.fr_buttons, text=key, variable=self.hashtag_group_chkbtn_vals[idx], command=lambda idx=idx: self._hashtag_group_chkbtn_press(idx))) self.hashtag_group_chkbtns[idx].bind('<ButtonPress>', self._on_button_press) self.label_ratio = tk.Label(self.fr_buttons,text='crop ratio') self.radio_ratio_val = tk.IntVar() self.radio_ratio_none = tk.Radiobutton(self.fr_buttons, text="None", value=RATIO_NONE, variable=self.radio_ratio_val, command=self._on_ratio) self.radio_ratio_45 = tk.Radiobutton(self.fr_buttons, text="4:5", value=RATIO_45, variable=self.radio_ratio_val, command=self._on_ratio) self.radio_ratio_11 = tk.Radiobutton(self.fr_buttons, text="1:1", value=RATIO_11, variable=self.radio_ratio_val, command=self._on_ratio) self.radio_ratio_custom = tk.Radiobutton(self.fr_buttons, text="Custom", value=RATIO_CUSTOM, variable=self.radio_ratio_val, command=self._on_ratio) self.spin_ratio_x_val = tk.StringVar(value="3") self.spin_ratio_x = tk.Spinbox(self.fr_buttons,from_=1, to=30, textvariable=self.spin_ratio_x_val, justify=tk.CENTER) self.spin_ratio_y_val = tk.StringVar(value="2") self.spin_ratio_y = tk.Spinbox(self.fr_buttons,from_=1, to=30, textvariable=self.spin_ratio_y_val, justify=tk.CENTER) self.label_ratio_custom = tk.Label(self.fr_buttons,text=':') self.label_crop_x = tk.Label(self.fr_buttons,text='x') self.label_crop_y = tk.Label(self.fr_buttons,text='y') self.label_crop_size = tk.Label(self.fr_buttons,text='size') self.spin_crop_x_val = tk.StringVar(value='0.0') self.spin_crop_x = tk.Spinbox(self.fr_buttons,from_=-1.0, to=1.0, format='%.2f', increment=0.02, textvariable=self.spin_crop_x_val, justify=tk.CENTER) self.spin_crop_y_val = tk.StringVar(value='0.0') self.spin_crop_y = tk.Spinbox(self.fr_buttons,from_=-1.0, to=1.0, format='%.2f', increment=0.02, textvariable=self.spin_crop_y_val, justify=tk.CENTER) self.spin_crop_size_val = tk.StringVar(value='1.0') self.spin_crop_size = tk.Spinbox(self.fr_buttons,from_=0.0, to=2.0, format='%.2f', increment=0.02, textvariable=self.spin_crop_size_val, justify=tk.CENTER) # trace value changes self.spin_crop_x_val.trace_add('write', self._on_crop_xysize) self.spin_crop_y_val.trace_add('write', self._on_crop_xysize) self.spin_crop_size_val.trace_add('write', self._on_crop_xysize) self.chk_crop_preview_val = tk.IntVar() self.chk_crop_preview= tk.Checkbutton(self.fr_buttons, text='crop preview', variable=self.chk_crop_preview_val, command=self._on_click_crop_preview) self.btn_forward = tk.Button(self.fr_buttons, text="Forward >", command=self.forward) self.btn_fast_forward = tk.Button(self.fr_buttons, text="Fast Forward >>", command=self.fast_forward) self.txt_description_preview = ScrolledText(self.fr_buttons, width=50, height=20, state=tk.DISABLED) self.chk_is_proxy_val = tk.IntVar() self.chk_is_proxy = tk.Checkbutton(self.fr_buttons, text='proxy', variable=self.chk_is_proxy_val, state=tk.DISABLED, anchor=tk.W) self.chk_is_uploaded_val = tk.IntVar() self.chk_is_uploaded = tk.Checkbutton(self.fr_buttons, text='instagram uploaded', variable=self.chk_is_uploaded_val, state=tk.DISABLED, anchor=tk.W) self.fr_btn_widgets = [] # list of all the widgets in the left frame (in order), for grid (partially) and for binding click focus self.fr_btn_widgets.append(self.sld_scale) self.fr_btn_widgets.append(self.sld_imgidx) self.fr_btn_widgets.append(self.chk_show_uploaded) self.fr_btn_widgets.append(self.chk_show_not_uploaded) self.fr_btn_widgets.append(self.chk_show_untagged) self.fr_btn_widgets.append(self.chk_use_proxy) self.fr_btn_widgets.append(self.chk_use_exif) self.fr_btn_widgets.append(self.btn_last_edited) self.fr_btn_widgets.append(self.btn_upload_insta) self.fr_btn_widgets.append(self.btn_exit) self.fr_btn_widgets.append(self.btn_fast_back) self.fr_btn_widgets.append(self.btn_back) self.fr_btn_widgets.append(self.txt_description) self.fr_btn_widgets.extend(self.hashtag_group_chkbtns) #self.fr_btn_widgets.append(self.label_ratio) self.fr_btn_widgets.append(self.radio_ratio_none) self.fr_btn_widgets.append(self.radio_ratio_45) self.fr_btn_widgets.append(self.radio_ratio_11) self.fr_btn_widgets.append(self.radio_ratio_custom) self.fr_btn_widgets.append(self.spin_ratio_x) self.fr_btn_widgets.append(self.spin_ratio_y) self.fr_btn_widgets.append(self.spin_crop_size) self.fr_btn_widgets.append(self.spin_crop_x) self.fr_btn_widgets.append(self.spin_crop_y) self.fr_btn_widgets.append(self.chk_crop_preview) self.fr_btn_widgets.append(self.btn_forward) self.fr_btn_widgets.append(self.btn_fast_forward) self.fr_btn_widgets.append(self.txt_description_preview) # row_widget row_widget = 0 for widget in self.fr_btn_widgets[:13]: # until txt_description widget.grid(row=row_widget, column=0, columnspan=3, sticky="ew") row_widget += 1 for widget in self.hashtag_group_chkbtns: widget.grid(row=row_widget, column=0, columnspan=3, sticky="ew") row_widget += 1 self.label_ratio.grid(row=row_widget, column=0, columnspan=3, sticky="ew", pady=5) row_widget += 1 self.radio_ratio_none.grid(row=row_widget, column=0, sticky="ew") self.radio_ratio_45.grid(row=row_widget, column=1, sticky="ew") self.radio_ratio_11.grid(row=row_widget, column=2, sticky="ew") row_widget += 1 self.radio_ratio_custom.grid(row=row_widget, column=0, sticky="ew") self.spin_ratio_x.grid(row=row_widget, column=1, sticky="ew", padx=40) self.label_ratio_custom.grid(row=row_widget, column=1, sticky="ee") self.spin_ratio_y.grid(row=row_widget, column=2, sticky="ew",padx=40) row_widget += 1 self.label_crop_x.grid(row=row_widget, column=0, sticky="ew") self.label_crop_y.grid(row=row_widget, column=1, sticky="ew") self.label_crop_size.grid(row=row_widget, column=2, sticky="ew") row_widget += 1 self.spin_crop_x.grid(row=row_widget, column=0, sticky="ew", padx=15) self.spin_crop_y.grid(row=row_widget, column=1, sticky="ew", padx=15) self.spin_crop_size.grid(row=row_widget, column=2, sticky="ew", padx=15) row_widget += 1 self.chk_crop_preview.grid(row=row_widget, column=0, columnspan=3, sticky="ew") row_widget += 1 self.btn_forward.grid(row=row_widget, column=0, columnspan=3, sticky="ew") row_widget += 1 self.btn_fast_forward.grid(row=row_widget, column=0, columnspan=3, sticky="ew") row_widget += 1 self.txt_description_preview.grid(row=row_widget, column=0, columnspan=3, sticky="ew") row_widget += 1 self.chk_is_proxy.grid(row=row_widget, column=0, columnspan=3, sticky="ew") row_widget += 1 self.chk_is_uploaded.grid(row=row_widget, column=0, columnspan=3, sticky="ew") self._sqlite_connect() self._sqlite_create_table() self._read_image_list(self.images_basedir) self.canvas = tk.Canvas(self.root, width=300, height=200)#, bg="white") self.canvas.pack(expand=tk.YES, fill=tk.BOTH) self.img_idx = 0 self._change_image() # set self.sld_imgidx range self.sld_imgidx.configure(to=self.image_count()) self._key_bind() def __del__(self): self._sqlite_close() self.insta_bot.logout() def _read_image_list(self, basedir: str): self.image_relpath_list = [] for root, dirs, files in os.walk(basedir): reldir = root.replace(basedir, '') if reldir.startswith(os.sep): reldir = reldir[1:] self.image_relpath_list.extend(sorted([os.path.join(reldir,f).replace(os.sep, '/') for f in files if f.lower().endswith('jpg')])) def get_insta_description(self): text = self.txt_description.get('1.0', tk.END).strip() num_hashtags_desc = text.count('#') text += '\n\n' + self.camera_info + '\n\n' hashtags = '' for idx, (key, val) in enumerate(self.hashtag_groups.items()): if self.hashtag_group_chkbtn_vals[idx].get() == 1: hashtags += val hashtags += ' ' hashtags += self.camera_hashtags num_hashtags = hashtags.count('#') if num_hashtags_desc + num_hashtags > 30: hashtags_list = hashtags.split(' ') random.shuffle(hashtags_list) hashtags_list = hashtags_list[:30-num_hashtags_desc] hashtags = ' '.join(hashtags_list) return text + hashtags def _update_description_preview(self): text = self.get_insta_description() self.txt_description_preview['state'] = tk.NORMAL self.txt_description_preview.delete(1.0,tk.END) self.txt_description_preview.insert(tk.END,text) self.txt_description_preview['state'] = tk.DISABLED def _save_txt_description(self): '''Save when modification is detected only ''' #self._update_description_preview() text = self.txt_description.get('1.0', tk.END).strip() is_modified = self.txt_description.edit_modified() if is_modified: #self._sqlite_upsert_description(text) self._sqlite_upsert_one_field('description', text) # reset the flag self.txt_description.edit_modified(False) def _save_hashtag_groups(self): group_keys = [] for idx, (key, val) in enumerate(self.hashtag_groups.items()): if self.hashtag_group_chkbtn_vals[idx].get() == 1: group_keys.append(key) self._sqlite_upsert_one_field('hashtag_groups', SQL_SEPARATOR.join(group_keys)) def _save_crop_ratio(self): ratio_mode = self.radio_ratio_val.get() if ratio_mode == RATIO_NONE: text = 'none' elif ratio_mode == RATIO_45: text = '4:5' elif ratio_mode == RATIO_11: text = '1:1' else: text = self.spin_ratio_x_val.get() + ":" + self.spin_ratio_y_val.get() self._sqlite_upsert_one_field('crop_ratio', text) def _save_crop_x(self): x_offset = float(self.spin_crop_x_val.get()) self._sqlite_upsert_one_field('crop_x_offset', x_offset) def _save_crop_y(self): y_offset = float(self.spin_crop_y_val.get()) self._sqlite_upsert_one_field('crop_y_offset', y_offset) def _save_crop_size(self): crop_size = float(self.spin_crop_size_val.get()) self._sqlite_upsert_one_field('crop_size', crop_size) def _sqlite_upsert_one_field(self, column, value): '''Updates the field with the current file path. Updates the last updated timestamp automatically. ''' last_updated_ts = datetime.utcnow().timestamp() self.sqlite_cursor.execute(f'''INSERT INTO insta_tags(file_relpath, {column}, last_updated_utc) VALUES(?,?,?) ON CONFLICT(file_relpath) DO UPDATE SET {column}=excluded.{column}, last_updated_utc=excluded.last_updated_utc;''', (self.image_relpath_list[self.img_idx], value, last_updated_ts)) self.sqlite_conn.commit() def _sqlite_connect(self): self.sqlite_conn = sqlite3.connect(self.config['database_path']) self.sqlite_cursor = self.sqlite_conn.cursor() def _sqlite_create_table(self): self.sqlite_cursor.execute('''CREATE TABLE IF NOT EXISTS insta_tags ( file_relpath TEXT PRIMARY KEY, description TEXT, hashtag_groups TEXT, crop_ratio TEXT DEFAULT none, crop_size REAL DEFAULT 1.0, crop_x_offset REAL DEFAULT 0.0, crop_y_offset REAL DEFAULT 0.0, is_insta_uploaded INTEGER DEFAULT 0, last_updated_utc REAL )''') self.sqlite_conn.commit() def _sqlite_close(self): self.sqlite_conn.close() def _key_bind(self): self.root.bind('<Left>', self._back_event) self.root.bind('<Right>', self._forward_event) self.root.protocol("WM_DELETE_WINDOW", self._on_close) self.root.bind('<Configure>', self._on_change_window_size) # unbind tab function for the text widget self.txt_description.bind('<Tab>', self._focus_next_widget) self.txt_description.bind('<FocusOut>', self._on_focus_out) self.txt_description.bind('<<TextModified>>', self._on_txt_modified) self.spin_crop_size.bind('<FocusOut>', self._on_focus_out) self.spin_crop_x.bind('<FocusOut>', self._on_focus_out) self.spin_crop_y.bind('<FocusOut>', self._on_focus_out) # move focus when pressing widgets self.root.bind('<ButtonPress>', self._on_button_press) for widget in self.fr_btn_widgets: widget.bind('<ButtonPress>', self._on_button_press) # self.chk_show_tagged. # self.chk_show_untagged.bind('<ButtonPress>', self._on_button_press) # self.btn_last_edited.bind('<ButtonPress>', self._on_button_press) # self.btn_upload_insta.bind('<ButtonPress>', self._on_button_press) # self.btn_exit.bind('<ButtonPress>', self._on_button_press) # self.btn_back.bind('<ButtonPress>', self._on_button_press) # self.btn_forward.bind('<ButtonPress>', self._on_button_press) def _forward_event(self, event): self.forward() def _back_event(self, event): self.back() def _hashtag_group_chkbtn_press(self, idx): self._update_description_preview() self._save_hashtag_groups() def _focus_next_widget(self, event): '''To unbind tab key on the text widget ''' event.widget.tk_focusNext().focus() return("break") def _on_show_tagged_untagged(self): if self.chk_show_uploaded_val.get() == 0 and self.chk_show_not_uploaded_val.get() == 0: self.btn_last_edited['state'] = tk.DISABLED else: self.btn_last_edited['state'] = tk.NORMAL def _on_use_proxy(self): if self.chk_use_proxy_val.get() == 0: self.chk_is_proxy_val.set(0) else: _, is_proxy = self.get_image() self.chk_is_proxy_val.set(is_proxy) self._scale_update() def _on_use_exif(self): if self.chk_use_exif_val.get() == 0: self.camera_info = '' self.camera_hashtags = '' else: self._read_camera_exif() self._update_description_preview() def _on_click_last_edited(self): pass def _on_click_upload_insta(self): # process image # image = self.get_original_image() crop_xywh = self.get_crop_xywh(image) img = self.get_scaled_cropped_image(image, 1.0, crop_xywh, resample=Image.LANCZOS) img = watermark_signature(img).convert('RGB') output_filepath = os.path.join(self.images_outputdir, self.image_relpath_list[self.img_idx]) output_dirpath = os.path.dirname(output_filepath) os.makedirs(output_dirpath, exist_ok=True) img.save(output_filepath, quality=95) logger.info('Image saved to %s', output_filepath) #caption = self.get_insta_description() caption = self.txt_description_preview.get('1.0', tk.END).strip() logger.info('Instagram caption: %s', caption) if not self.insta_bot_logged_in: # True / False self.insta_bot_logged_in = self.insta_bot.login(username=insta_id, password=insta_password) if not self.insta_bot_logged_in: logger.error('Failed to log in to Instagram') return #self.insta_bot.upload_photo(output_filepath, caption) self.insta_bot.upload_photo(output_filepath, caption) os.rename(output_filepath + '.REMOVE_ME', output_filepath) self._sqlite_upsert_one_field('is_insta_uploaded', 1) self.chk_is_uploaded_val.set(1) def _on_close(self): self._save_txt_description() self._save_crop_size() self._save_crop_x() self._save_crop_y() self.root.destroy() def _on_focus_out(self, event): '''Save the description when the text box is out of focus ''' if event.widget == self.txt_description: logger.info('Description text focus out: Saving..') self._save_txt_description() elif event.widget == self.spin_crop_size: logger.info('Crop size focus out: Saving..') self._save_crop_size() elif event.widget == self.spin_crop_x: logger.info('Crop x focus out: Saving..') self._save_crop_x() elif event.widget == self.spin_crop_y: logger.info('Crop y focus out: Saving..') self._save_crop_y() def _on_txt_modified(self, event): '''Update preview as soon as description is modified ''' if event.widget == self.txt_description: self._update_description_preview() def _on_button_press(self, event): '''Move focus ''' event.widget.focus() def _on_crop_xysize(self, var, indx, mode): if self.chk_crop_preview_val.get() == 1: self._scale_update() else: self._refresh_canvas() def _ratio_disability_update(self): ratio_mode = self.radio_ratio_val.get() if ratio_mode == RATIO_NONE: self.spin_crop_x['state'] = tk.DISABLED self.spin_crop_y['state'] = tk.DISABLED self.spin_crop_size['state'] = tk.DISABLED self.chk_crop_preview['state'] = tk.DISABLED else: self.spin_crop_x['state'] = tk.NORMAL self.spin_crop_y['state'] = tk.NORMAL self.spin_crop_size['state'] = tk.NORMAL self.chk_crop_preview['state'] = tk.NORMAL if ratio_mode == RATIO_CUSTOM: self.spin_ratio_x['state'] = tk.NORMAL self.spin_ratio_y['state'] = tk.NORMAL else: self.spin_ratio_x['state'] = tk.DISABLED self.spin_ratio_y['state'] = tk.DISABLED def _on_ratio(self): self._ratio_disability_update() if self.chk_crop_preview_val.get() == 1: self._scale_update() else: self._refresh_canvas() logger.info('Ratio changed: Saving..') self._save_crop_ratio() def point_to_canvas(self, image: Image.Image, x, y): '''Convert image point coordinate to canvas coordinate Considers scaling and canvas offset (image is centre aligned) ''' canvas_width = self.canvas.winfo_width() canvas_height = self.canvas.winfo_height() image_width, image_height = image.size scale = self.sld_scale_val.get() # adding canvas offset canvas_x = x * scale + (canvas_width - image_width * scale)/2 canvas_y = y * scale + (canvas_height - image_height * scale)/2 if self.chk_crop_preview_val.get() == 1: # image centre - crop centre is the another offset crop_xywh = self.get_crop_xywh(image) crop_centre_x = crop_xywh[0] + crop_xywh[2]/2 crop_centre_y = crop_xywh[1] + crop_xywh[3]/2 canvas_x += (image_width/2 - crop_centre_x)*scale canvas_y += (image_height/2 - crop_centre_y)*scale return round(canvas_x), round(canvas_y) def rectangle_to_canvas(self, image: Image.Image, x, y, w, h): x1, y1, x2, y2 = self.xywh_to_xyxy(x, y, w, h) canvas_x1, canvas_y1 = self.point_to_canvas(image, x1,y1) canvas_x2, canvas_y2 = self.point_to_canvas(image, x2,y2) return canvas_x1, canvas_y1, canvas_x2, canvas_y2 def get_crop_xywh(self, image: Image.Image): ratio_mode = self.radio_ratio_val.get() if ratio_mode == RATIO_NONE: return None else: if ratio_mode == RATIO_45: ratio_x = 4 ratio_y = 5 elif ratio_mode == RATIO_11: ratio_x = 1 ratio_y = 1 else: # RATIO_CUSTOM ratio_x = int(self.spin_ratio_x_val.get()) ratio_y = int(self.spin_ratio_y_val.get()) crop_x_offset = float(self.spin_crop_x_val.get()) crop_y_offset = float(self.spin_crop_y_val.get()) crop_size = float(self.spin_crop_size_val.get()) crop_ratio = ratio_x / ratio_y image_width, image_height = image.size image_ratio = image_width / image_height if image_ratio > crop_ratio: # image is wider. crop_size==1 should be matching image's height. # base width and height when crop_size==1 crop_base_height = image_height crop_base_width = crop_base_height / ratio_y * ratio_x else: # image is narrower. crop_size==1 should be matching image's width. # base width and height when crop_size==1 crop_base_width = image_width crop_base_height = crop_base_width / ratio_x * ratio_y crop_centre_x = image_width / 2 + (crop_x_offset * image_width / 2) crop_centre_y = image_height / 2 + (crop_y_offset * image_height / 2) crop_width = crop_base_width * crop_size crop_height = crop_base_height * crop_size crop_x1 = crop_centre_x - (crop_width / 2) crop_y1 = crop_centre_y - (crop_height / 2) return crop_x1, crop_y1, crop_width, crop_height def xywh_to_xyxy(self, x, y, w, h): return x, y, x+w, y+h def get_scaled_cropped_image(self, image: Image.Image, scale, crop_xywh, resample=Image.BICUBIC): if crop_xywh is not None: new_image_size = tuple(map(lambda x: round(x*scale), crop_xywh[2:])) crop_xyxy = tuple(map(round, self.xywh_to_xyxy(*crop_xywh))) # perform padding when crop is out of border image_width, image_height = image.size padding = None if crop_xyxy[0] < 0: if padding is None: padding = [0,0,0,0] padding[0] = -crop_xyxy[0] if crop_xyxy[1] < 0: if padding is None: padding = [0,0,0,0] padding[1] = -crop_xyxy[1] if crop_xyxy[2] > image_width: if padding is None: padding = [0,0,0,0] padding[2] = crop_xyxy[2] - image_width if crop_xyxy[3] > image_height: if padding is None: padding = [0,0,0,0] padding[3] = crop_xyxy[3] - image_height if padding is None: current_image_pil_scaled = image.resize(new_image_size, box=crop_xyxy, resample=resample) else: logger.warning('white padding applied to the image borders') padding = tuple(padding) crop_xyxy_padded = (crop_xyxy[0] + padding[0], crop_xyxy[1] + padding[1], crop_xyxy[2] + padding[0], crop_xyxy[3] + padding[1]) # padding on the left and top sides makes the box shift, but not the right and bottom sides. current_image_pil_scaled = ImageOps.expand(image, border=padding, fill=(255,255,255)).resize(new_image_size, box=crop_xyxy_padded, resample=resample) else: if scale == 1.0: # use the original and do not make a copy current_image_pil_scaled = image else: new_image_size = tuple(map(lambda x: round(x*scale), image.size)) current_image_pil_scaled = image.resize(new_image_size, resample=resample) return current_image_pil_scaled def _imgidx_update(self, event=None): index = self.sld_imgidx_val.get() - 1 self.jump(index) def _scale_update(self, event=None): '''Manipulate original image 1. Apply scaling 2. Apply crop preview 3. Apply proxy ''' scale = self.sld_scale_val.get() image, use_proxy = self.get_image() crop_xywh = self.get_crop_xywh(image) if self.chk_crop_preview_val.get() == 1 and crop_xywh is not None: self.current_image_pil_scaled = self.get_scaled_cropped_image(image, scale, crop_xywh, resample=Image.BILINEAR) else: if scale == 1.0: # use the original and do not make a copy self.current_image_pil_scaled = image else: new_image_size = tuple(map(lambda x: round(x*scale), image.size)) self.current_image_pil_scaled = image.resize(new_image_size, resample=Image.BILINEAR) self.current_image = ImageTk.PhotoImage(self.current_image_pil_scaled) self._refresh_canvas() def _refresh_canvas(self): '''DO NOT change the image itself but change the positioning ''' #self.canvas.create_image(0,0,image=self.current_image, anchor=tk.NW) self.canvas.delete(tk.ALL) #self.canvas.create_image(0,0,image=self.current_image, anchor=tk.CENTER) canvas_width = self.canvas.winfo_width() canvas_height = self.canvas.winfo_height() self.canvas.create_image(canvas_width/2,canvas_height/2,image=self.current_image, anchor=tk.CENTER) #self.label.configure(image=self.label.image) # crop image, use_proxy = self.get_image() crop_xywh = self.get_crop_xywh(image) if crop_xywh is not None: canvas_crop_xyxy = self.rectangle_to_canvas(image, *crop_xywh) is_crop_preview = self.chk_crop_preview_val.get() if is_crop_preview == 0: # draw rectangle self.canvas.create_rectangle(*canvas_crop_xyxy, dash=(3,3), outline="blue", width=2) def _on_change_window_size(self, event): # refresh self._refresh_canvas() def _on_click_crop_preview(self): # refresh self._scale_update() def get_original_image(self): if self.current_image_pil is None: self.current_image_pil, _, _ = exif_transpose_delete_exif(Image.open(self.current_image_path)) return self.current_image_pil def get_image(self): ''' Gets image (get proxy if user sets it and file available) Returns: image (PIL) is_proxy (bool) ''' use_proxy = bool(self.chk_use_proxy_val.get()) if use_proxy: if self.current_image_proxy_pil is None: if self.proxy_file_exists is None: proxy_path = os.path.join(self.images_proxydir, self.image_relpath) if os.path.isfile(proxy_path): self.proxy_file_exists = True self.current_image_proxy_pil, _, _ = exif_transpose_delete_exif(Image.open(proxy_path)) return self.current_image_proxy_pil, True else: self.proxy_file_exists = False return self.get_original_image(), False elif not self.proxy_file_exists: return self.get_original_image(), False else: raise NotImplementedError() else: return self.current_image_proxy_pil, True else: return self.get_original_image(), False def _read_camera_exif(self): self.camera_info = '' self.camera_hashtags = '' try: with exiftool.ExifTool() as et: metadata = et.get_metadata(self.current_image_path) except json.decoder.JSONDecodeError: return for key, val in self.config['exif'].items(): if 'exif_field' in val.keys(): if val['exif_field'] in metadata.keys(): metavalue = str(metadata[val['exif_field']]) if 'format' in val.keys(): self.camera_info += val['format'].replace("%s", metavalue) + '\n' if 'hashtag' in val.keys(): self.camera_hashtags += val['hashtag'].replace("%s", metavalue) + ' ' if 'hashtags' in val.keys(): if metavalue in val['hashtags'].keys(): self.camera_hashtags += val['hashtags'][metavalue] + ' ' if 'conditional_hashtags' in val.keys(): for condition in val['conditional_hashtags'].keys(): if eval(metavalue + condition): self.camera_hashtags += val['conditional_hashtags'][condition] + ' ' elif 'exif_fields' in val.keys(): metavalues = [] bypass_format = False for key2 in val['exif_fields']: if key2 in metadata.keys(): metavalues.append(metadata[key2]) else: logger.warning('%s not found in EXIF of file %s', key2, self.image_relpath) bypass_format = True if not bypass_format and 'format' in val.keys(): formatted_str = val['format'] for i, metaval in enumerate(metavalues): formatted_str = formatted_str.replace("%{:d}".format(i+1), str(metaval)) self.camera_info += formatted_str + '\n' else: raise ValueError() #@profile def _change_image(self): # This is a Linux path with / no matter what OS you use. self.image_relpath = self.image_relpath_list[self.img_idx] # This is an OS dependent path with / or \. self.current_image_path = os.path.join(self.images_basedir, self.image_relpath.replace('/', os.sep)) self.current_image_pil = None self.current_image_proxy_pil = None self.proxy_file_exists = None use_proxy = bool(self.chk_use_proxy_val.get()) pil, is_proxy = self.get_image() self.chk_is_proxy_val.set(int(is_proxy)) self.current_image = ImageTk.PhotoImage(pil) # this is replaced by scaled image self._scale_update() self.root.title("({:d}/{:d}) {:s}".format(self.img_idx+1, self.image_count(), self.image_relpath)) # read exif if self.chk_use_exif_val.get() == 1: self._read_camera_exif() # check db self.sqlite_cursor.execute('SELECT * FROM insta_tags WHERE file_relpath=?', (self.image_relpath,)) db_imageinfo = self.sqlite_cursor.fetchone() logger.info("Loaded info from DB: %s", str(db_imageinfo)) self.initialise_widgets() if db_imageinfo is not None: if db_imageinfo[SQL_DESCRIPTION] is not None: self.txt_description.insert(tk.END,db_imageinfo[SQL_DESCRIPTION]) if db_imageinfo[SQL_HASHTAG_GROUPS] is not None: for hashtag_group in db_imageinfo[SQL_HASHTAG_GROUPS].split(SQL_SEPARATOR): idx = self.hashtag_groups_indices[hashtag_group] self.hashtag_group_chkbtn_vals[idx].set(1) if db_imageinfo[SQL_CROP_RATIO] == 'none': self.radio_ratio_val.set(RATIO_NONE) elif db_imageinfo[SQL_CROP_RATIO] == '4:5': self.radio_ratio_val.set(RATIO_45) elif db_imageinfo[SQL_CROP_RATIO] == '1:1': self.radio_ratio_val.set(RATIO_11) else: ratio_xy = db_imageinfo[SQL_CROP_RATIO].split(':') if len(ratio_xy) != 2: raise ValueError(f'Unknown ratio {db_imageinfo[SQL_CROP_RATIO]}') self.radio_ratio_val.set(RATIO_CUSTOM) self.spin_ratio_x_val.set(ratio_xy[0]) self.spin_ratio_y_val.set(ratio_xy[1]) self.spin_crop_size_val.set(db_imageinfo[SQL_CROP_SIZE]) self.spin_crop_x_val.set(db_imageinfo[SQL_CROP_X_OFFSET]) self.spin_crop_y_val.set(db_imageinfo[SQL_CROP_Y_OFFSET]) self._ratio_disability_update() if db_imageinfo[SQL_IS_INSTA_UPLOADED] is not None: self.chk_is_uploaded_val.set(db_imageinfo[SQL_IS_INSTA_UPLOADED]) else: self.chk_is_uploaded_val.set(0) self._update_description_preview() # reset the modified flag self.txt_description.edit_modified(False) def initialise_widgets(self): self.txt_description.delete(1.0,tk.END) # initialise hashtag groups (set to False) for hashtag_group_val in self.hashtag_group_chkbtn_vals: hashtag_group_val.set(0) self.radio_ratio_val.set(RATIO_NONE) self.spin_crop_size_val.set(1.0) self.spin_crop_x_val.set(0.0) self.spin_crop_y_val.set(0.0) self._ratio_disability_update() def image_count(self): return len(self.image_relpath_list) def _forward_back_disability_update(self, fast_count=20): if self.img_idx >= self.image_count() - 1: self.btn_forward['state'] = tk.DISABLED else: self.btn_forward['state'] = tk.NORMAL if self.img_idx >= self.image_count() - fast_count: self.btn_fast_forward['state'] = tk.DISABLED else: self.btn_fast_forward['state'] = tk.NORMAL if self.img_idx > 0: self.btn_back['state'] = tk.NORMAL else: self.btn_back['state'] = tk.DISABLED if self.img_idx > fast_count: self.btn_fast_back['state'] = tk.NORMAL else: self.btn_fast_back['state'] = tk.DISABLED def jump(self, imgidx): ''' Jump to the img index ''' if self.img_idx == imgidx: return if imgidx < 0: return if imgidx >= self.image_count(): return self._save_txt_description() self._save_crop_size() self._save_crop_x() self._save_crop_y() self.img_idx = imgidx self._change_image() self._forward_back_disability_update() self.txt_description.focus() self.sld_imgidx_val.set(imgidx+1) def forward(self, count = 1): ''' if self.img_idx >= self.image_count() - count: return self._save_txt_description() self._save_crop_size() self._save_crop_x() self._save_crop_y() self.img_idx += count self._change_image() self._forward_back_disability_update() self.txt_description.focus() ''' self.jump(self.img_idx + count) def back(self, count = 1): ''' if self.img_idx < count: return self._save_txt_description() self._save_crop_size() self._save_crop_x() self._save_crop_y() self.img_idx -= count self._change_image() self._forward_back_disability_update() self.txt_description.focus() ''' self.jump(self.img_idx - count) def fast_forward(self): self.forward(20) def fast_back(self): self.back(20)
class MainGUI: def __init__(self, sql_database_name, sql_table_name): # self.master = master + in übergabe (self, master) #conn = sqlite3.connect(sql_database_name + '.db') conn = sqlite3.connect(sql_database_name) df = pd.read_sql_query("SELECT *, oid FROM " + sql_table_name, conn) cursor = conn.cursor() cursor.execute("SELECT *, oid FROM " + sql_table_name) self.db_records = cursor.fetchall() self.db_records_listing = [] for self.db_record in self.db_records: self.db_records_listing.append(len(self.db_records)) print("Anzahl Einträge: " + str(len(self.db_records_listing))) conn.commit() conn.close() win = tk.Tk() win.title('Datenbank - Anzahl der Einträge: ' + str(len(self.db_records_listing))) # scrollable Frame self.sf_database = ScrolledFrame(win, width=500, height=500) self.sf_database.pack(expand=1, fill="both") # Create a frame within the ScrolledFrame self.db_inner_frame = self.sf_database.display_widget(Frame) #win.resizable(width=0, height=0) self.tree = ttk.Treeview(self.db_inner_frame, selectmode="browse", height=30) self.tree.pack(fill="both", expand=1) #self.tree.pack(side='left') #vsb = ttk.Scrollbar(win, orient="vertical", command=self.tree.yview) #vsb.pack(side='right', fill='y') #self.tree.configure(yscrollcommand=vsb.set) hsb = ttk.Scrollbar(win, orient="horizontal", command=self.tree.xview) hsb.pack(side='bottom', fill='x') self.tree['show'] = 'headings' self.tree["columns"] = df.columns.values.tolist() for i, header in enumerate(df.columns.values.tolist()): self.tree.column(i, width=100) self.tree.heading(i, text=header) for row in df.iterrows(): self.tree.insert("", 'end', values=list(row[1])) # self.tree.bind("<Button-3>", self.preClick) # self.tree.bind("<Button-1>", self.onLeft) #self.tree["displaycolumns"] = df.columns.values.tolist()[0:(len(self.db_records_listing)-7)] # Alle Spalten-Einträge in Datenbank Übersicht zeigen self.tree["displaycolumns"] = df.columns.values.tolist()
def print_news(): news_data = [] files = glob.glob("*.json") for data_file in files: f = open(data_file) try: data = json.load(f) # data1= json.dump(data) if data["status"] == "ok" and data["totalResults"] > 0: news_data.append(data) except: print('Error') # GUI data_frame = tk.Frame(window) data_frame.pack(side="left", expand=0, fill="y") sf = ScrolledFrame(data_frame, width=1178, bg='#ffffff') sf.pack(side="left", expand=1, fill="y") # Bind the arrow keys and scroll wheel sf.bind_arrow_keys(window) sf.bind_scroll_wheel(window) frame = sf.display_widget(tk.Frame) frame['bg'] = '#E8E7F7' frame['bd'] = 15 frame['relief'] = 'sunken' for news_list in news_data: for news in news_list['articles']: # Title Label l = tk.Label(text=news['title'].title(), fg='#3f0052', wraplength=1120, master=frame, font="-size 18 -weight bold", justify='left', pady='10') l.pack() # Description Label l = tk.Label(text=news['description'], bg='#DEDEDE', fg='#3f0052', wraplength=1120, master=frame, font="-size 14", justify='left', padx='15') l.pack() # Separator l = tk.Label( text= '--------------------------------------------------------------------------------------------------', fg='#3f0052', wraplength=1120, master=frame, font="-size 14", justify='left', pady='25') l.pack() window.mainloop()
pady='4') lb.pack() root.update_idletasks() root.update() sf.yview_moveto(1) comment.delete() root = tk.Tk() root.geometry('470x550+0+0') root.title('Reddit Birthday Bot') data_frame = tk.Frame(root) data_frame.pack(side="left", expand=0, fill="both") sf = ScrolledFrame(data_frame, width=450, bg='#ffffff') sf.pack(side="left", expand=1, fill="both") sf.bind_arrow_keys(root) sf.bind_scroll_wheel(root) frame = sf.display_widget(tk.Frame) frame['bg'] = '#d7d5f7' frame['bd'] = 15 frame['relief'] = 'sunken' frame['width'] = 450 frame.pack_propagate(1) b = tk.Button(master=data_frame, text='Run', fg='#8132B6', bg='#D0C5D8', width=14, height=2,
def weekly_rateing(handle_for_rate): try: phase = get_all(handle_for_rate) phase.get_problem() phase.get_probelms_for_phase() def search_max_problem(id, level): webbrowser.open("http://codeforces.com/problemset/problem/" + level + '/' + str(id)) weekly_window = Toplevel() weekly_window.geometry("505x700") weekly_window.title('weekly raiting') week_scroll = ScrolledFrame( weekly_window, width=494, height=700, bg="#231e1e", scrollbars="vertical", ) week_scroll.pack( expand=1, fill="y", ) week_scroll.bind_arrow_keys(weekly_window) week_scroll.bind_scroll_wheel(weekly_window) inner_week_frame = week_scroll.display_widget(Frame) ## main window inner_week_frame.config(background="black", ) ############################################## info_fr = Frame(inner_week_frame, height=350, width=490, background="#231e1e") phase.get_info() image = wget.download("http:" + str(phase.image)) image = ImageTk.PhotoImage(size=20, image=Image.open( phase.image.split('/')[-1])) # l = Button(info_fr,image=image).place(rely=0) picture = Label(info_fr, image=image).place(rely=0.25, relx=0.05) system("del /f " + str(phase.image.split('/')[-1])) account_name = Label(info_fr, text="name: " + str(phase.name)).place(rely=0.05, relx=0.3) country = Label(info_fr, text="country: " + (str(phase.country))).place(rely=0.15, relx=0.3) city = Label(info_fr, text="city: " + (str(phase.city))).place(rely=0.25, relx=0.3) organization = Label(info_fr, text="Organization: " + (str(phase.Organization))).place(rely=0.35, relx=0.3) friends = Label(info_fr, text="friend of: " + (str(phase.friends))).place(rely=0.45, relx=0.3) rank = Label(info_fr, text="Rank: " + (str(phase.Rank))).place(rely=0.55, relx=0.3) rating = Label(info_fr, text="Rating: " + (str(phase.Rating))).place(rely=0.65, relx=0.3) register = Label(info_fr, text="registered: " + (str(phase.registered))).place( rely=0.75, relx=0.3) info_fr.pack(pady=1) info_fr.pack(pady=1) phase.phase1_info() phase1_fr = Frame( inner_week_frame, width=490, height=300, bg="#231e1e", ) cur1 = Label(phase1_fr, text="Phase1:", font=('arial', 30), bg='#231e1e', fg='red').place(relx=0, rely=0.05) solved1 = Label(phase1_fr, text="problems solved: " + str(len(phase.phase1_solved)), bg="#231e1e").place(relx=0, rely=0.22) submittions1 = Label(phase1_fr, text="Submitions: " + str(phase.phase1_submitions), bg="#231e1e").place(relx=0, rely=0.32) mxrated1 = Label(phase1_fr, text="Matx Rate Problem: " + str(phase.phase1_max_rated_problem), bg="#231e1e").place(relx=0, rely=0.42) av1 = Label(phase1_fr, text="problems Average Rate : " + str(phase.phase1_av), bg="#231e1e").place(relx=0, rely=0.52) const1 = Label(phase1_fr, text="contests Participation: " + str(phase.phase1_contestcount), bg="#231e1e").place(relx=0, rely=0.62) vir1 = Label(phase1_fr, text="virtual participation: " + str(phase.phase1_virtual_count), bg="#231e1e").place(relx=0, rely=0.72) phase1_fr.pack(pady=1) ####################################################################################### phase.phase2_info() phase2_fr = Frame( inner_week_frame, width=490, height=300, bg="#231e1e", ) cur2 = Label(phase2_fr, text="Phase2:", font=('arial', 30), bg='#231e1e', fg='red').place(relx=0, rely=0.05) solved2 = Label(phase2_fr, text="problems solved: " + str(len(phase.phase2_solved)), bg="#231e1e").place(relx=0, rely=0.22) submittions2 = Label(phase2_fr, text="Submitions: " + str(phase.phase2_submitions), bg="#231e1e").place(relx=0, rely=0.32) mxrated2 = Label(phase2_fr, text="Matx Rate Problem: " + str(phase.phase2_max_rated_problem), bg="#231e1e").place(relx=0, rely=0.42) av2 = Label(phase2_fr, text="problems Average Rate : " + str(phase.phase2_av), bg="#231e1e").place(relx=0, rely=0.52) conts2 = Label(phase2_fr, text="contests Participation: " + str(phase.phase2_contestcount), bg="#231e1e").place(relx=0, rely=0.62) vir2 = Label(phase2_fr, text="virtual participation: " + str(phase.phase2_virtual_count), bg="#231e1e").place(relx=0, rely=0.72) phase2_fr.pack(pady=1) ############################################### phase.phase3_info() phase3_fr = Frame(inner_week_frame, width=490, height=300, bg="#231e1e") cur3 = Label(phase3_fr, text="Phase3:", font=('arial', 30), bg='#231e1e', fg='red').place(relx=0, rely=0.05) solved3 = Label(phase3_fr, text="problems solved: " + str(len(phase.phase3_solved)), bg='#231e1e').place(relx=0, rely=0.22) submittions3 = Label(phase3_fr, text="Submitions: " + str(phase.phase3_submitions), bg='#231e1e').place(relx=0, rely=0.32) mxrated3 = Label(phase3_fr, text="Matx Rate Problem: " + str(phase.phase3_max_rated_problem), bg='#231e1e').place(relx=0, rely=0.42) av3 = Label(phase3_fr, text="problems Average Rate : " + str(phase.phase3_av), bg='#231e1e').place(relx=0, rely=0.52) const3 = Label(phase3_fr, text="contests Participation: " + str(phase.phase3_contestcount), bg='#231e1e').place(relx=0, rely=0.62) vir3 = Label(phase3_fr, text="virtual participation: " + str(phase.phase3_virtual_count), bg='#231e1e').place(relx=0, rely=0.72) phase3_fr.pack(pady=1) weekly_window.mainloop() except HTTPError: warnning = Tk() warnning.geometry("300x100") warnning.title('warnning') warnning.configure(bg="pink") warnning.iconbitmap('error.ico') l = Label(warnning, text="not valid handle ", font=('arial', 20), fg='red', bg="pink").pack() warnning.mainloop() except URLError: warnning = Tk() warnning.geometry("300x100") warnning.configure(bg="gray") warnning.iconbitmap('error.ico') warnning.title('warnning') l = Label(warnning, text="please check internet", font=('arial', 20), fg='red', bg='gray').pack() warnning.mainloop()
def search_result(handle): ##### pop up of search window #url = "https://userpic.codeforces.com/591099/avatar/e5d251220ca54303.jpg" try: account = get_all(handle) res_file = Toplevel() res_file.geometry("520x700") res_sf = ScrolledFrame( res_file, width=500, height=700, bg="#231e1e", scrollbars="vertical", ) res_sf.pack( expand=1, fill="y", ) res_sf.bind_arrow_keys(res_file) res_sf.bind_scroll_wheel(res_file) inner_frame = res_sf.display_widget(Frame) ## main window inner_frame.config(background="black", ) ############################################################################## info_fr = Frame(inner_frame, height=350, width=490, background="#231e1e") account.get_info() image = wget.download("http:" + str(account.image)) image = ImageTk.PhotoImage(size=20, image=Image.open( account.image.split('/')[-1])) # l = Button(info_fr,image=image).place(rely=0) picture = Label(info_fr, image=image).place(rely=0.25, relx=0.05) system("del /f " + str(account.image.split('/')[-1])) account_name = Label(info_fr, text="name: " + str(account.name)).place( rely=0.05, relx=0.3) country = Label(info_fr, text="country: " + (str(account.country))).place(rely=0.15, relx=0.3) city = Label(info_fr, text="city: " + (str(account.city))).place(rely=0.25, relx=0.3) organization = Label(info_fr, text="Organization: " + (str(account.Organization))).place(rely=0.35, relx=0.3) friends = Label(info_fr, text="friend of: " + (str(account.friends))).place(rely=0.45, relx=0.3) rank = Label(info_fr, text="Rank: " + (str(account.Rank))).place(rely=0.55, relx=0.3) rating = Label(info_fr, text="Rating: " + (str(account.Rating))).place( rely=0.65, relx=0.3) register = Label(info_fr, text="registered: " + (str(account.registered))).place(rely=0.75, relx=0.3) info_fr.pack(pady=1) ############################################################################### account.get_problem() languages_fr = Frame(inner_frame, height=30 * len(account.languages) + 20, width=490, background="#231e1e") i = 3 Label(languages_fr, text="languages:", font=('arial', 20), fg='red', bg="#231e1e").place(rely=0, relx=0) for language in account.languages: Label(languages_fr, text=str(language) + ":" + str(account.languages[language]), fg='white', bg="#231e1e").place(relx=0.1, rely=0.5 / len(account.languages) * i) i += 1 languages_fr.pack(pady=1) ############################################## vlen = 50 * len(account.verdict) + 10 verdicts_fr = Frame(inner_frame, height=vlen, width=490, background="#231e1e") i = 3 Label(verdicts_fr, text="verdicts:", font=('arial', 20), fg='red', bg="#231e1e").place(rely=0, relx=0) for verdict in account.verdict: if verdict == "OK": Label(verdicts_fr, text="accepted" + ":" + str(account.verdict["OK"]), fg='white', bg="#231e1e").place(relx=0.1, rely=0.3 / len(account.verdict) * i) if verdict != "OK": Label(verdicts_fr, text=str(verdict) + ":" + str(account.verdict[verdict]), fg='white', bg="#231e1e").place(relx=0.1, rely=0.3 / len(account.verdict) * i) i += 2 verdicts_fr.pack(pady=1) ################################################# llen = 50 * len(account.solved_level) + 10 levels_fr = Frame(inner_frame, height=llen, width=490, background="#231e1e") i = 5 Label(levels_fr, text="levels:", font=('arial', 20), fg='red', bg="#231e1e").place(rely=0, relx=0) for level in account.solved_level: Label(levels_fr, fg='white', bg="#231e1e", text=str(level) + ":" + str(account.solved_level[level])).place( relx=0.1, rely=0.3 / (len(account.solved_level)) * i) i += 2 levels_fr.pack(pady=1) ##################################################### t_height = 100 * len(account.solved_tages) / 6 tags_fr = Frame( inner_frame, width=490, height=t_height, bg="#231e1e", ) t = Label(tags_fr, text="tags:", font=('arial', 20), fg='red', bg="#231e1e").place(rely=0.0, relx=0) i = 2 j = 0 for tag in account.solved_tages: Label(tags_fr, text=str(tag), bg='#2' + str(i * j + 10) + 'e1e', fg='#F' + str(i * j + 10) + 'e1e').place( rely=(1.5 / len(account.solved_tages)) * i, relx=0.5 * j) if j < 1: j += 1 else: j = 0 i += 1 tags_fr.pack(pady=1) ###################################################### extras_fr = Frame(inner_frame, height=350, width=490, background="#231e1e") account.get_contest() t = Label(extras_fr, text="Extra:", font=('arial', 20), fg='red', bg="#231e1e").place(rely=0.0, relx=0) Label(extras_fr, text='tryed: ' + str(account.tryed_problem), fg='white', bg="#231e1e").place(rely=0.15) Label( extras_fr, fg='white', bg="#231e1e", text='solved problems: ' + str(account.tryed_problem - len(account.unsolved_problem))).place( rely=0.25) Label(extras_fr, fg='white', bg="#231e1e", text='nomber of contests: ' + str(account.number_of_contests)).place(rely=0.35) Label(extras_fr, fg='white', bg="#231e1e", text='Best rank: ' + str(account.Best_Rank)).place(rely=0.45) Label(extras_fr, fg='white', bg="#231e1e", text='worst rank: ' + str(account.worst_Rank)).place(rely=0.55) Label(extras_fr, fg='white', bg="#231e1e", text='max up: ' + str(account.max_up)).place(rely=0.65) Label(extras_fr, fg='white', bg="#231e1e", text='max down: ' + str(account.max_down)).place(rely=0.75) extras_fr.pack(pady=1) ############################################## unslen = 30 * (len(account.unsolved_problem) + 1) / 2 + 100 unsolved_fr = Frame(inner_frame, width=490, height=unslen, background="#231e1e") i = 5 def serach_problem(index, contestid): webbrowser.open("http://codeforces.com/problemset/problem/" + str(contestid) + '/' + str(index)) j = 0 unstext = Label(unsolved_fr, text="unsolved practice problems:", font=('arial', 20)).place(rely=0, relx=0) print(len(account.unsolved_problem)) for problem in account.unsolved_problem: Button(unsolved_fr, bg='brown', text=str(problem['index']) + '-' + str(problem['contestId']), command=lambda: serach_problem(problem['index'], problem[ 'contestId'])).place(rely=0.05 * i, relx=0.5 * j) if j == 1: j = -1 if j == -1: i += 3 j += 1 unsolved_fr.pack(pady=1) # image = wget.download("http:"+str(account.image)) # image=ImageTk.PhotoImage(Image.open(account.image.split('/')[-1])) # cann = Label(fr, width=20, height=10, borderwidth=0, highlightthickness=0, relief='ridge', text='hi', bg='white') # cann.pack() # cann.place(relx=0.01, rely=0.2) # system("rm "+account.image.split('/')[-1]) # can = Canvas(inner_frame,bg='black') # can.create_window(0, 0, anchor=NW, window=fr) # can.pack(pady=0, padx=0) # can.pack() res_file.mainloop() # inner_frame. ############################################################### # get_all(handle) except HTTPError: warnning = Tk() warnning.geometry("300x100") warnning.title('warnning') warnning.configure(bg="pink") warnning.iconbitmap('error.ico') l = Label(warnning, text="not valid handle ", font=('arial', 20), fg='red', bg="pink").pack() warnning.mainloop() except URLError: warnning = Tk() warnning.geometry("300x100") warnning.configure(bg="gray") warnning.iconbitmap('error.ico') warnning.title('warnning') l = Label(warnning, text="please check internet", font=('arial', 20), fg='red', bg='gray').pack() warnning.mainloop()
or config['CURRENT']['gui'] == 'Display all'): gui = 'Display all' elif config['CURRENT']['gui'] == 'Display used': gui = 'Display used' else: gui = 'CLI mode' except: gui = 'Display all' if gui != 'CLI mode': root = Tk() root.attributes('-alpha', 0) root.title('Forensic Version Checker') sf = ScrolledFrame(root, scrollbars='vertical') sf.pack(side='top', expand=True, fill='both') sf.bind_scroll_wheel(root) inner_frame = sf.display_widget(Frame) icon = 'iVBORw0KGgoAAAANSUhEUgAAASwAAAEsCAMAAABOo35HAAACYVBMVEUAAAAA/wCA/4BV/1WA/0Bm/zOA/1Vt/0mA/0Bx/zmA/010/0aA/0B2/zuA/0l3/0SA/0B4/zyA\ /0d5/0OA/0B5/z2A80Z69EOA9EB69T2A9UV79kKA9kB79j5790KA90B89z6A+ER8+EKA+EB8+D55+EN8+EF8+T55+UN9+UF6+UB9+T56+UN9+kF6+kB9+j57+kB9+kN9+kF9+0N7\ +0J9+0F7+0B7+0J9+0F890B+90N890J8+EB8+EJ++EF8+EB8+EF8+EB7+EJ8+EF7+UF7+UJ8+UF7+UF8+UB7+UJ9+UB9+UF7+UB9+UB7+kJ9+kF7+kB9+kB9+kF9+kB9+kF8+kB8\ +kJ9+kF9+EJ7+EF8+EB7+EJ7+UF7+UJ7+UF8+UB8+UF7+UF8+UJ9+UF8+UF9+UB8+UJ9+UF8+UF9+UB8+UJ9+UF8+UF8+kJ9+kF8+kJ9+kF8+kF8+kF7+EF8+EF8+EF8+EF7+EJ8\ +UF8+UF8+UF8+UF8+UJ8+UF8+UF8+UF8+UF9+UF8+UJ9+UF8+UF9+UB8+UJ9+UF8+UF9+UB8+UJ9+UF8+UF7+UB7+UF8+UF7+kB8+kF8+kF8+kF8+EF8+EF8+EB8+EF8+EF8+UF8\ +UB8+UF8+UF8+UB8+UF8+UF8+UJ8+UF8+UJ8+UF8+UJ9+UF9+UF8+UJ7+UF8+UF8+UF8+UF8+UF8+UF8+UF8+UF8+UF8+UF8+kF8+kF8+EF8+EF8+UF8+UF8+UF8+UF8+UF8+UF8\ +UF8+UF8+UF8+UF8+UF8+UF8+UF8+UF8+UF8+UF8+UF8+UF8+UF8+UH////fFht9AAAAyXRSTlMAAQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB0fICEiIyQlJicpKissLS4v\ MDE0NTc5Ojs8Pj9AQUJERkdISkxNTk9RUlNUVVhaW1xdXl9gYmRmZ2lqbG5vdHZ4ent9foCBgoOEhYaHiImKjI2QkZKUlZaYmpueoKGio6Slpqiqq6ytrq+wsbKztLW2uLm6u72/\ wMHCw8TFxsfIyszNzs/S1NbX2drb3uDh4uPk5ebn6Onq6+zt7u/w8fLz9PX29/j5+vv8/f64aNKjAAAAAWJLR0TK87Q25gAABpZJREFUeNrt3ftbFFUcgPGDiBCYJYoX1LTI1Mgi\ 8VqYpamtaBkqFmmlppVZKUqS2R0ttQumdvFuIKUIKpmCmAsLLHz/q37QeQR2Z+bMsFxm531/dZ+zZz8unOXszlmliIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIj6p0ETcvIC\ cV9ezoRBPZWate1si/ikljMf5LqXSll7XnxWZWGKux+/VVfFh10pcPHj+PBJ8WnHJzq1eu6m+Lb6PGdWi1vEx4VedGK1JCy+rvV5favs2+Lzbk3VtUqrFN9XkaqJVYyVyMd6VtPD\ UIm0Pa6FdQApEZH9OlaTO4ASEWnP0sB6H6c7bdbAqoLp7h/V9lYTUTIab4u1DCSjgC3WJpCMNthi7QHJqNQW6zuQjPbZYpWDZFRui3UYJKPDYIEFFlhggQUWWGCBBRZYYPVb7XV/\
class TkinterThread(threading.Thread): """Thread responsible for creating and running the Tkinter window.""" CREATE_WINDOW_TIMEOUT = 5 # Seconds WINDOW_HEIGHT = 500 # Pixels BAR_WIDTH = 100 # Pixels def __init__(self, test): super(TkinterThread, self).__init__() self.test = test self.setDaemon(True) self.finish_preperation_event = threading.Event() self.frame = None self.inner_frame = None def iterate_over_tests(self, test, window, depth=0, row=count()): """Recursively populate the given frame with the tests' widgets.""" self.create_tree_bar(test, window, depth, next(row)) if test.IS_COMPLEX: for sub_test in test: self.iterate_over_tests(sub_test, window, depth + 1, row) def create_tree_bar(self, test, window, depth, row): """Create progress bar for a test in an hierarchical form.""" name = test.data.name if test.IS_COMPLEX: total = test._expected_time else: avg_time = test._expected_time if avg_time: total = int(avg_time) * 10 else: total = 10 name += " (No statistics)" label = tkinter.Label(window, text=name, height=1) style = Style() style.theme_use('clam') style_name = "{}.Horizontal.TProgressbar".format(test.identifier) style.configure(style_name, foreground='red', background='red') progress = Progressbar(window, orient=tkinter.HORIZONTAL, maximum=total, length=self.BAR_WIDTH, mode='determinate', style=style_name) test.progress_bar = ProgressContainer(test, progress, style_name) label.grid(column=depth, row=row) progress.grid(column=depth + 1, row=row) def run(self): """Create a Tkinter window, populate it with widgets, and run it.""" window = tkinter.Tk() window.resizable(False, False) self.frame = ScrolledFrame(window, scrollbars="vertical", height=self.WINDOW_HEIGHT) self.frame.pack() self.inner_frame = self.frame.display_widget(tkinter.Frame) self.iterate_over_tests(self.test, self.inner_frame) self.finish_preperation_event.set() window.mainloop() def start(self): """Create and run the window, sync until it's up ready.""" super(TkinterThread, self).start() self.finish_preperation_event.wait(timeout=self.CREATE_WINDOW_TIMEOUT) # Adjust the window's width while self.inner_frame.winfo_width() <= 1: time.sleep(0.01) self.frame['width'] = self.inner_frame.winfo_width()
def manager_window(self): tk.Label(self.window, text="Steam Discount Manager", bd=4, font=font.Font(family='Helvetica', size=14, weight='bold')).pack() frame = tk.Frame(self.window) tk.Label(frame, text=f'Data from: {self.data_modification_time}', font=font.Font(family='Helvetica', size=12, weight='normal')).pack(side=tk.LEFT) tk.Label(frame, text=' ', font=12).pack(side=tk.LEFT) button = tk.Button(frame, text='UPDATE', bd=4, font=12, command=lambda: [self.update_button_fun()]) button.pack() frame.pack() tk.Label(self.window, text='', font=12).pack() outer_frame = tk.Frame(self.window) self.make_table_header(outer_frame) sf = ScrolledFrame(outer_frame, width=1100, height=500) sf.bind_scroll_wheel(self.window) sf.pack() inner_frame = sf.display_widget(tk.Frame) for i in range(self.current_data.shape[0]): frame = tk.Frame(inner_frame) row = list(self.current_data.iloc[i]) for j in range(len(self.columns)): l_box = tk.Listbox(frame, width=self.columns_width[j], height=1, justify=tk.CENTER, font=font.Font(family='Helvetica', size=12, weight='normal')) l_box.insert(0, self.format_element(self.columns[j], row[j])) if i % 2 == 1: l_box.itemconfig(0, bg='gray90') if row[0] in self.priority_titles: l_box.itemconfig(0, fg='red') l_box.pack(side=tk.LEFT) frame.pack() tk.Label(outer_frame, text=f"Titles: {self.current_data.shape[0]}", bd=4, font=font.Font(family='Helvetica', size=12, weight='normal')).pack(anchor='w') outer_frame.pack() i = 0 spinbox_values = [tk.IntVar() for _ in range(4)] frame = tk.Frame(self.window) tk.Label(frame, text='Filters:', bd=4, font=font.Font(family='Helvetica', size=12, weight='bold')).pack() for column in list(self.columns_parameters.keys()): tk.Label(frame, text=f'{column}:', font=font.Font(family='Helvetica', size=12, weight='normal')).pack(side=tk.LEFT) tk.Spinbox(frame, from_=self.columns_parameters[column][0], to=self.columns_parameters[column][1], textvariable=spinbox_values[i], width=6, bd=4, font=12, increment=self.columns_parameters[column][2], state="readonly", readonlybackground='white').pack(side=tk.LEFT) if self.user_prefs_dictionary[column] is not None: spinbox_values[i].set(self.user_prefs_dictionary[column]) tk.Label(frame, text=' ', font=12).pack(side=tk.LEFT) i += 1 button = tk.Button( frame, text='SELECT', bd=4, font=12, command=lambda: [ self.filter_button_fun( tuple([value.get() for value in spinbox_values])) ]) button.pack() frame.pack() frame = tk.Frame(self.window) tk.Label(frame, text='\n', font=12).pack() tk.Label(frame, text='Sorting:', bd=4, font=font.Font(family='Helvetica', size=12, weight='bold')).pack() sort_by_column_value = tk.StringVar(value="Name") if self.user_prefs_dictionary["Sort Column"] is not None: sort_by_column_value.set(self.user_prefs_dictionary["Sort Column"]) tk.Label(frame, text='Sort by:', bd=4, font=font.Font(family='Helvetica', size=12, weight='normal')).pack(side=tk.LEFT) combobox = ttk.Combobox(frame, width=20, textvariable=sort_by_column_value, state="readonly") combobox['values'] = self.columns combobox.pack(side=tk.LEFT) tk.Label(frame, text=' ', font=12).pack(side=tk.LEFT) type_sort_value = tk.StringVar(value="Descending") if self.user_prefs_dictionary["Sort Type"] is not None: type_sort_value.set(self.user_prefs_dictionary["Sort Type"]) tk.Label(frame, text='Type:', bd=4, font=font.Font(family='Helvetica', size=12, weight='normal')).pack(side=tk.LEFT) combobox = ttk.Combobox(frame, width=15, textvariable=type_sort_value, state="readonly") combobox['values'] = self.sort_types combobox.pack(side=tk.LEFT) tk.Label(frame, text=' ', font=12).pack(side=tk.LEFT) button = tk.Button(frame, text='SORT', bd=4, font=12, command=lambda: [ self.sort_button_fun(sort_by_column_value.get(), type_sort_value.get()) ]) button.pack() frame.pack() self.window_config() self.window.mainloop()
class GuiMainWindow: def __init__(self, master): self.master = master master.geometry = '800x710' master.title('ilias - Test-Generator v2.0') # -------------------------- Set PATH for Project self.project_root_path = pathlib.Path().absolute() self.img_file_path_create_folder = os.path.normpath( os.path.join(self.project_root_path, 'ILIAS-Fragentest_tst_Daten', '1590475954__0__tst_1944463', 'objects')) self.img_file_path = os.path.normpath( os.path.join(self.project_root_path, 'ILIAS-Fragentest_tst_Daten', '1590475954__0__tst_1944463', 'objects')) self.emtpy_xml_file_path_read = os.path.normpath( os.path.join(self.project_root_path, 'empty_xml_files', 'empty_xml.xml')) self.ilias_questionpool_for_import = os.path.normpath( os.path.join(self.project_root_path, 'ILIAS-Fragenpool_zum_Import')) # # # -------------------------- Check if Files are in correct position # print("\n") # print("## Project Files inside this Project Folder?") # print("##") # print("## Testfragen -> orig_tst_file: " + str(os.path.exists(self.tst_file_path_read))) # print("## Testfragen -> orig_qti_file: " + str(os.path.exists(self.qti_file_path_read))) # print("## Testfragen -> 1590475954__0__tst_1944463.xml: " + str(os.path.exists(self.tst_file_path_write))) # print("## Testfragen -> 1590475954__0__qti_1944463.xml: " + str(os.path.exists(self.qti_file_path_write))) # print("## Poolfragen -> orig_qpl_file: " + str(os.path.exists(self.qpl_file_pool_path_read))) # print("## Poolfragen -> orig_qti_file: " + str(os.path.exists(self.qti_file_pool_path_read))) # print("## Poolfragen -> Vorlage_für_Fragenpool: " + str(os.path.exists(os.path.normpath(os.path.join(self.project_root_path, "Vorlage_für_Fragenpool", 'orig_1596569820__0__qpl_2074808'))))) # print("-------------------------------------------------------") # -------------------------- Set size of windows # Main-window self.window_width = 800 self.window_height = 800 # Main-window self.multiplechoice_width = 800 self.multiplechoice_height = 800 # Database-window self.database_width = 800 self.database_height = 800 # Settings-window self.settings_width = 800 self.settings_height = 800 # Taxonomy-window self.taxonomy_width = 1000 self.taxonomy_height = 800 # <------------ CREATE TABS AND TABCONTROL -----------> self.tabControl = ttk.Notebook(app) # Create Tab Control # ---- Tab for Formula - Questions self.formelfrage_tab_ttk = ttk.Frame(self.tabControl) # Create a tab self.tabControl.add(self.formelfrage_tab_ttk, text='Formelfrage') # Add the tab # ---- Tab for Formula permutation - Questions self.formelfrage_permutation_tab_ttk = ttk.Frame( self.tabControl) # Create a tab self.tabControl.add(self.formelfrage_permutation_tab_ttk, text='Formelfrage Permutation') # Add the tab # ---- Tab for Single Choice - Questions self.singlechoice_tab_ttk = ttk.Frame(self.tabControl) # Create a tab self.tabControl.add(self.singlechoice_tab_ttk, text='Single Choice') # Add the tab # ---- Tab for Multiple Choice - Questions self.multiplechoice_tab_ttk = ttk.Frame( self.tabControl) # Create a tab self.tabControl.add(self.multiplechoice_tab_ttk, text='Multiple Choice') # Add the tab # ---- Tab for MatchingQuestion - Questions self.zuordnungsfrage_tab_ttk = ttk.Frame( self.tabControl) # Create a tab self.tabControl.add(self.zuordnungsfrage_tab_ttk, text='Zuordnungsfrage') # Add the tab ####### CREATE SCROLLABLE FRAME ON TABS # Create a ScrolledFrame widget self.scrolledframe_formelfrage = ScrolledFrame( self.formelfrage_tab_ttk, width=self.window_width, height=self.window_height) self.scrolledframe_formelfrage.pack(expand=1, fill="both") self.scrolledframe_formelfrage_permutation = ScrolledFrame( self.formelfrage_permutation_tab_ttk, width=self.window_width, height=self.window_height) self.scrolledframe_formelfrage_permutation.pack(expand=1, fill="both") self.scrolledframe_singlechoice = ScrolledFrame( self.singlechoice_tab_ttk, width=self.window_width, height=self.window_height) self.scrolledframe_singlechoice.pack(expand=1, fill="both") self.scrolledframe_multiplechoice = ScrolledFrame( self.multiplechoice_tab_ttk, width=self.window_width, height=self.window_height) self.scrolledframe_multiplechoice.pack(expand=1, fill="both") self.scrolledframe_zuordnungsfrage = ScrolledFrame( self.zuordnungsfrage_tab_ttk, width=self.window_width, height=self.window_height) self.scrolledframe_zuordnungsfrage.pack(expand=1, fill="both") # Create a frame within the ScrolledFrame self.formelfrage_tab = self.scrolledframe_formelfrage.display_widget( Frame) self.formelfrage_permutation_tab = self.scrolledframe_formelfrage_permutation.display_widget( Frame) self.singlechoice_tab = self.scrolledframe_singlechoice.display_widget( Frame) self.multiplechoice_tab = self.scrolledframe_multiplechoice.display_widget( Frame) self.zuordnungsfrage_tab = self.scrolledframe_zuordnungsfrage.display_widget( Frame) self.tabControl.pack(expand=1, fill="both") # ---Init Variable Matrix #### ----- Create Databases --- test_generator_modul_datenbanken_erstellen.CreateDatabases.__init__( self, self.project_root_path) test_generator_modul_datenbanken_erstellen.CreateDatabases.create_database_formelfrage( self) test_generator_modul_datenbanken_erstellen.CreateDatabases.create_database_formelfrage_permutation( self) test_generator_modul_datenbanken_erstellen.CreateDatabases.create_database_singlechoice( self) test_generator_modul_datenbanken_erstellen.CreateDatabases.create_database_multiplechoice( self) test_generator_modul_datenbanken_erstellen.CreateDatabases.create_database_zuordnungsfrage( self) test_generator_modul_datenbanken_erstellen.CreateDatabases.create_database_test_settings_profiles( self) #Formelfrage_GUI.__init__(self) test_generator_modul_formelfrage.Formelfrage.__init__( self, app, self.formelfrage_tab, self.project_root_path) test_generator_modul_singlechoice.SingleChoice.__init__( self, app, self.singlechoice_tab, self.project_root_path) test_generator_modul_multiplechoice.MultipleChoice.__init__( self, app, self.multiplechoice_tab, self.project_root_path) test_generator_modul_zuordnungsfrage.Zuordnungsfrage.__init__( self, app, self.zuordnungsfrage_tab, self.project_root_path) test_generator_modul_formelfrage_permutation.Formelfrage_Permutation.__init__( self, app, self.formelfrage_permutation_tab, self.project_root_path)
class CardsArea(tk.Frame): def __init__(self, master, app, *args, **kwargs): tk.Frame.__init__(self, master, *args, **kwargs) self.app = app self.currentPageNumber = 1 self.numberOfPages = 1 self.areaMode = FULL_MODE # or 'simple' self.TABLE_HEIGHT = int(self.app.winfo_screenheight() * 0.5) self.TABLE_WIDTH = int(self.app.winfo_screenwidth() * 0.4) # self.table = CardsGrid(self) self.scrolledFrameContainter = tk.Frame(self) self.scrolledFrameContainter.pack(fill=tk.BOTH, expand=1) self.scrolledFrame = ScrolledFrame(self.scrolledFrameContainter, height=self.TABLE_HEIGHT, width=self.TABLE_WIDTH) self.scrolledFrame.pack(fill=tk.BOTH, expand=1) self.scrolledFrame.bind_arrow_keys(self) self.scrolledFrame.bind_scroll_wheel(self.scrolledFrameContainter) self.table = self.scrolledFrame.display_widget(tk.Frame) self.statusPanel = tk.LabelFrame(self) self.statusPanel.pack(fill=tk.X, anchor=tk.E, side=tk.BOTTOM) self.statusPanel.toLeftButton = tk.Button(self.statusPanel, text='\u21E6 Prev', font='Helvetica 12 bold', command=self.to_prev_page) self.statusPanel.toRightButton = tk.Button(self.statusPanel, text='\u21E8 Next', font='Helvetica 12 bold', command=self.to_next_page) self.statusPanel.currentPageLabel = tk.Label(self.statusPanel, text='Page %d of %d' % (self.currentPageNumber, self.numberOfPages) ) def set_mode_full(self): self.areaMode = FULL_MODE def set_mode_simple(self): self.areaMode = SIMPLE_MODE def init_panels(self): if self.table.winfo_exists() == 0: # self.table = CardsGrid(self) self.table = self.table = ScrolledFrame(self, width=self.TABLE_WIDTH, height=self.TABLE_HEIGHT) self.table.pack(fill=tk.BOTH) if self.statusPanel.winfo_exists() == 0: self.statusPanel = tk.LabelFrame(self) self.statusPanel.pack(fill=tk.X) def show_page(self, page_number=1): rows_per_page = self.app.userCardsControlPanel.rowsPerPageVar.get() cols_per_page = self.app.userCardsControlPanel.colsPerPageVar.get() if self.areaMode == FULL_MODE: # number_of_records = self.app.userCards.size number_of_records = self.app.userCards.arrFilterSize elif self.areaMode == SIMPLE_MODE: number_of_records = self.app.simpleCards.size() else: number_of_records = self.app.simpleCards.size() left_index = (page_number - 1) * rows_per_page * cols_per_page right_index = page_number * rows_per_page * cols_per_page - 1 if number_of_records - 1 < right_index: right_index = number_of_records - 1 self.numberOfPages = ceil(number_of_records / (rows_per_page * cols_per_page)) for elem in self.table.winfo_children(): if type(elem) == UserCardView: elem.destroy() cur_record_num = left_index cur_row_num = 1 cur_col_num = 1 while cur_record_num <= right_index and cur_record_num < number_of_records: if self.areaMode == FULL_MODE: cur_card = UserCardView(self.table, self.app, self.app.userCards.get(cur_record_num)) elif self.areaMode == SIMPLE_MODE: cur_card = SimpleCardView(self.table, self.app.simpleCards[cur_record_num]) else: cur_card = SimpleCardView(self.table, self.app.simpleCards[cur_record_num]) cur_card.grid(row=cur_row_num, column=cur_col_num, padx=10, pady=10) cur_col_num += 1 if cur_col_num > cols_per_page: cur_col_num = 1 cur_row_num += 1 cur_record_num += 1 self.draw_status_elements() def draw_status_elements(self): if self.statusPanel.toLeftButton.winfo_ismapped() == 0: self.statusPanel.toLeftButton.pack(side=tk.LEFT) if self.statusPanel.currentPageLabel.winfo_ismapped() == 0: self.statusPanel.currentPageLabel.pack(side=tk.LEFT, fill=tk.X, expand=1) if self.statusPanel.toRightButton.winfo_ismapped() == 0: self.statusPanel.toRightButton.pack(side=tk.RIGHT) if self.currentPageNumber <= 1: self.statusPanel.toLeftButton['state'] = tk.DISABLED else: self.statusPanel.toLeftButton['state'] = tk.NORMAL if self.currentPageNumber >= self.numberOfPages: self.statusPanel.toRightButton['state'] = tk.DISABLED else: self.statusPanel.toRightButton['state'] = tk.NORMAL self.statusPanel.currentPageLabel['text'] = 'Page %d of %d' % (self.currentPageNumber, self.numberOfPages) def to_prev_page(self): if self.currentPageNumber > 1: self.currentPageNumber -= 1 self.show_page(page_number=self.currentPageNumber) def to_next_page(self): if self.currentPageNumber < self.numberOfPages: self.currentPageNumber += 1 self.show_page(page_number=self.currentPageNumber)
self.clvlentry[x + 1].set(self.closevllist[x]) self.slvlentry[x + 1].set(self.salesvllist[x]) def savelist(self): brandlist.opbtsalist = self.closebtlist[:] #copying whole list closebtlist---->opbtlist #-------------------------------------------calculation end-------------------------------- wall = Frame(tasmac) wall.pack(fill="both") #----------------------------------------note book layout-------------------------------- tablayout = Notebook(wall, width=50, height=620) #------------------------------------------scroll frame---------------------------------- #------------------------------------------tab1 starts----------------------------------- scrolltab1 = ScrolledFrame(tablayout, width=20, height=40) scrolltab1.pack(side="top", expand=1, fill="both") #-------------------------------------------scroll display widget------------------------ tab1 = scrolltab1.display_widget(tk.Frame) #-------------------------------------------tab1 body------------------------------------ #entry variable list box is bind to the entry box to store the value entered to the Entry widget sno_var = [] ml180mrp120bna_var = [] ml180mrp120_ent = [] ml180mrp120ent_var = [] head_var = [] temp = [] ml180mrp120len = len(brandlist.ml180120) headlen = len(brandlist.tableheadlist) len120 = ml180mrp120len + 1 #-------------append entry variable to list using length---------- for i in range(
def compare_result(handle1, handle2): #url = "https://userpic.codeforces.com/591099/avatar/e5d251220ca54303.jpg" try: account1 = get_all(handle1) account1.get_info() account2 = get_all(handle2) account2.get_info() compare_window = Toplevel() compare_window.geometry("810x700") compare_scroll = ScrolledFrame( compare_window, width=800, height=700, bg="#231e1e", scrollbars="vertical", ) compare_scroll.pack( expand=1, fill="y", ) compare_scroll.bind_arrow_keys(compare_window) compare_scroll.bind_scroll_wheel(compare_window) inner_compare_frame = compare_scroll.display_widget( Frame) ## main window inner_compare_frame.config(background="black", ) ############################################## 1 ########################################################### info1_fr = Frame( inner_compare_frame, width=390, height=250, bg="#231e1e", ) image = wget.download("http:" + str(account1.image)) image = ImageTk.PhotoImage(size=20, image=Image.open( account1.image.split('/')[-1])) # l = Button(info1_fr,image=image).place(rely=0) picture = Label(info1_fr, image=image).place(rely=0.25, relx=0.05) system("del /f " + str(account1.image.split('/')[-1])) account_name = Label(info1_fr, text="name: " + str(account1.name)).place(rely=0.05, relx=0.3) country = Label(info1_fr, text="country: " + (str(account1.country))).place(rely=0.15, relx=0.3) city = Label(info1_fr, text="city: " + (str(account1.city))).place(rely=0.25, relx=0.3) organization = Label(info1_fr, text="Organization: ").place(rely=0.35, relx=0.3) orgnization_info = Label(info1_fr, text=(str( account1.Organization))).place(rely=0.45, relx=0.38) friends = Label(info1_fr, text="friend of: " + (str(account1.friends))).place(rely=0.55, relx=0.3) rank = Label(info1_fr, text="Rank: " + (str(account1.Rank))).place(rely=0.65, relx=0.3) rating = Label(info1_fr, text="Rating: " + (str(account1.Rating))).place(rely=0.75, relx=0.3) register = Label(info1_fr, text="registered: " + (str(account1.registered))).place(rely=0.85, relx=0.3) info1_fr.grid(column=0, row=0, pady=1, padx=1) ####################2################# info2_fr = Frame( inner_compare_frame, width=390, height=250, bg="#231e1e", ) image2 = wget.download("http:" + str(account2.image)) image2 = ImageTk.PhotoImage(size=20, image=Image.open( account2.image.split('/')[-1])) # l = Button(info2_fr,image=image).place(rely=0) picture = Label(info2_fr, image=image2).place(rely=0.25, relx=0.05) system("del /f " + str(account2.image.split('/')[-1])) account_name = Label(info2_fr, text="name: " + str(account2.name)).place(rely=0.05, relx=0.3) country = Label(info2_fr, text="country: " + (str(account2.country))).place(rely=0.15, relx=0.3) city = Label(info2_fr, text="city: " + (str(account2.city))).place(rely=0.25, relx=0.3) organization = Label(info2_fr, text="Organization: ").place(rely=0.35, relx=0.3) organization_info = Label(info2_fr, text=(str( account2.Organization))).place(rely=0.45, relx=0.38) friends = Label(info2_fr, text="friend of: " + (str(account2.friends))).place(rely=0.55, relx=0.3) rank = Label(info2_fr, text="Rank: " + (str(account2.Rank))).place(rely=0.65, relx=0.3) rating = Label(info2_fr, text="Rating: " + (str(account2.Rating))).place(rely=0.75, relx=0.3) register = Label(info2_fr, text="registered: " + (str(account2.registered))).place(rely=0.85, relx=0.3) info2_fr.grid(column=1, row=0, pady=1, padx=1) #################################################################################################################### account1.get_problem() account2.get_problem() languages1_fr = Frame( inner_compare_frame, width=390, height=30 * max(len(account2.languages), len(account1.languages)) + 80, bg="#231e1e", ) v = Label(languages1_fr, text="languages:", font=('arial', 20), fg='red', bg="#231e1e").place(rely=0.0, relx=0) i = 4 for language in account1.languages: Label(languages1_fr, text=str(language) + ": " + str(account1.languages[language]), bg='#231e1e', fg='white').place(relx=0.1, rely=0.05 * i) i += 2 languages1_fr.grid(column=0, row=1, pady=1, padx=1) ####################################### languages2_fr = Frame( inner_compare_frame, width=390, height=30 * max(len(account2.languages), len(account1.languages)) + 80, bg="#231e1e", ) l2 = Label(languages2_fr, text="languages:", font=('arial', 20), fg='red', bg="#231e1e").place(rely=0.0, relx=0) i = 4 for language in account2.languages: Label(languages2_fr, text=str(language) + ":" + str(account2.languages[language]), bg='#231e1e', fg='white').place(relx=0.1, rely=0.05 * i) i += 2 languages2_fr.grid(column=1, row=1, pady=1, padx=1) #################################################################################################################### verdicts1_fr = Frame( inner_compare_frame, width=390, height=30 * max(len(account2.verdict), len(account1.verdict)) + 60, bg="#231e1e", ) v = Label(verdicts1_fr, text="verdicts:", font=('arial', 20), fg='red', bg="#231e1e").place(rely=0.0, relx=0) i = 3 if "OK" in account1.verdict: Label(verdicts1_fr, text="accepted" + ":" + str(account1.verdict["OK"]), bg='#231e1e', fg='white').place(relx=0.1, rely=0.05 * i) else: Label(verdicts1_fr, text="accepted: 0", bg='#231e1e', fg='white').place(relx=0.1, rely=0.05 * i) i = 5 for verdict in account1.verdict: if verdict != "OK": Label(verdicts1_fr, text=str(verdict) + ":" + str(account1.verdict[verdict]), bg='#231e1e', fg='white').place(relx=0.1, rely=0.05 * i) i += 2 verdicts1_fr.grid(column=0, row=2, pady=1, padx=1) ################################################## verdicts2_fr = Frame( inner_compare_frame, width=390, height=30 * max(len(account2.verdict), len(account1.verdict)) + 60, bg="#231e1e", ) v = Label(verdicts2_fr, text="verdicts:", font=('arial', 20), fg='red', bg="#231e1e").place(rely=0.0, relx=0) i = 3 if "OK" in account2.verdict: Label(verdicts2_fr, text="accepted" + ":" + str(account2.verdict["OK"]), bg='#231e1e', fg='white').place(relx=0.1, rely=0.05 * i) else: Label(verdicts2_fr, text="accepted: 0", bg='#231e1e', fg='white').place(relx=0.1, rely=0.05 * i) i = 5 for v in account2.verdict: if v != "OK": Label(verdicts2_fr, text=str(v) + ":" + str(account2.verdict[v]), bg='#231e1e', fg='white').place(relx=0.1, rely=0.05 * i) i += 2 verdicts2_fr.grid(column=1, row=2, pady=1, padx=1) #################################################################################################################### level1_fr = Frame( inner_compare_frame, width=390, height=60 * max(len(account2.solved_level), len(account1.solved_level)), bg="#231e1e") l1 = Label(level1_fr, text="levels:", font=('arial', 20), fg='red', bg="#231e1e").place(rely=0.0, relx=0) i = 4 for level in account1.solved_level: Label(level1_fr, text=str(level) + ":" + str(account1.solved_level[level]), bg='#231e1e', fg='white').place(relx=0.1, rely=0.05 * i) i += 1 level1_fr.grid(row=3, column=0, pady=1, padx=1) ############################################### level2_fr = Frame( inner_compare_frame, width=390, height=60 * max(len(account2.solved_level), len(account1.solved_level)), bg="#231e1e", ) l2 = Label(level2_fr, text="levels:", font=('arial', 20), fg='red', bg="#231e1e").place(rely=0.0, relx=0) i = 3 for level in account2.solved_level: Label(level2_fr, text=str(level) + ":" + str(account2.solved_level[level]), bg='#231e1e', fg='white').place(relx=0.1, y=20 * i) i += 1 level2_fr.grid(row=3, column=1, pady=1, padx=1) #################################################################################################################### account1.get_problem() account2.get_problem() t_height = 100 * max(len(account2.solved_tages), len(account1.solved_tages)) / 6 tags1_fr = Frame( inner_compare_frame, width=390, height=t_height, bg="#231e1e", ) t = Label(tags1_fr, text="tags:", font=('arial', 20), fg='red', bg="#231e1e").place(rely=0.0, relx=0) i = 3 j = 0 for tag in account1.solved_tages: Label(tags1_fr, text=str(tag), bg='#2' + str(i * j + 10) + 'e1e', fg='#F' + str(i * j + 10) + 'e1e').place(y=(0.02 / 300) * h * i * 400, x=0.5 * j * 400) if j < 1: j += 1 else: j = 0 i += 1 tags1_fr.grid(row=4, column=0, pady=1, padx=1) ################################################ tags2_fr = Frame( inner_compare_frame, width=390, height=t_height, bg="#231e1e", ) t = Label(tags2_fr, text="tags:", font=('arial', 20), fg='red', bg="#231e1e").place(rely=0.0, relx=0) #t1=Frame(tags2_fr,bg='#231e1e') i = 3 j = 0 for tag in account2.solved_tages: Label(tags2_fr, text=str(tag), bg='#2' + str(i * j + 10) + 'e1e', fg='#F' + str(i * j + 10) + 'e1e').place(y=(0.02 / 300) * h * i * 400, x=0.5 * j * 400) if j < 1: j += 1 else: j = 0 i += 1 #t1.pack() tags2_fr.grid(row=4, column=1, pady=1, padx=1) #################################################################################################################### extras1_fr = Frame( inner_compare_frame, width=390, height=300, bg="#231e1e", ) account1.get_contest() Label(extras1_fr, text='tryed: ' + str(account1.tryed_problem), fg='red', bg="#231e1e").place(rely=0.05) Label(extras1_fr, text='solved problems: ' + str(account1.tryed_problem - len(account1.unsolved_problem)), fg='red', bg="#231e1e").place(rely=0.15) Label(extras1_fr, text='nomber of contests: ' + str(account1.number_of_contests), fg='red', bg="#231e1e").place(rely=0.25) Label(extras1_fr, text='Best rank: ' + str(account1.Best_Rank), fg='red', bg="#231e1e").place(rely=0.35) Label(extras1_fr, text='worst rank: ' + str(account1.worst_Rank), fg='red', bg="#231e1e").place(rely=0.45) Label(extras1_fr, text='max up: ' + str(account1.max_up), fg='red', bg="#231e1e").place(rely=0.55) Label(extras1_fr, text='max down: ' + str(account1.max_down), fg='red', bg="#231e1e").place(rely=0.65) extras1_fr.grid(row=5, column=0, pady=1, padx=1) ############################################ extras2_fr = Frame( inner_compare_frame, width=390, height=300, bg="#231e1e", ) account2.get_contest() Label(extras2_fr, text='tryed: ' + str(account2.tryed_problem), fg='red', bg="#231e1e").place(rely=0.05) Label(extras2_fr, text='solved problems: ' + str(account2.tryed_problem - len(account2.unsolved_problem)), fg='red', bg="#231e1e").place(rely=0.15) Label(extras2_fr, text='nomber of contests: ' + str(account2.number_of_contests), fg='red', bg="#231e1e").place(rely=0.25) Label(extras2_fr, text='Best rank: ' + str(account2.Best_Rank), fg='red', bg="#231e1e").place(rely=0.35) Label(extras2_fr, text='worst rank: ' + str(account2.worst_Rank), fg='red', bg="#231e1e").place(rely=0.45) Label(extras2_fr, text='max up: ' + str(account2.max_up), fg='red', bg="#231e1e").place(rely=0.55) Label(extras2_fr, text='max down: ' + str(abs(account2.max_down)), fg='red', bg="#231e1e").place(rely=0.65) extras2_fr.grid(row=5, column=1, pady=1, padx=1) #################################################################################################################### unsolved1_fr = Frame( inner_compare_frame, width=390, height=30 * max(len(account1.unsolved_problem), len(account2.unsolved_problem)) / 1.5 + 40, bg="#231e1e", ) i = 4 def serach_problem(index, contestid): webbrowser.open("http://codeforces.com/problemset/problem/" + str(contestid) + '/' + str(index)) un1 = Label(unsolved1_fr, text='unsolved:', font=('arial', 20), bg="#231e1e", fg='red').place(rely=0.0, relx=0) j = 0 for problem in account1.unsolved_problem: Button(unsolved1_fr, text=str(problem['index']) + '-' + str(problem['contestId']), bg='brown', command=lambda: serach_problem(problem['index'], problem[ 'contestId'])).place(y=0.4 * i * 10, relx=0.5 * j) if j == 1: j = -1 j += 1 if j == 0: i += 1 unsolved1_fr.grid(row=6, column=0, pady=1, padx=1) #################################### unsolved2_fr = Frame( inner_compare_frame, width=390, height=30 * max(len(account1.unsolved_problem), len(account2.unsolved_problem)) / 1.5 + 40, bg="#231e1e", ) i = 4 def serach_problem(index, contestid): webbrowser.open("http://codeforces.com/problemset/problem/" + str(contestid) + '/' + str(index)) un2 = Label(unsolved2_fr, text='unsolved:', font=('arial', 20), bg="#231e1e", fg='red').place(rely=0.0, relx=0) j = 0 for problem in account2.unsolved_problem: Button(unsolved2_fr, bg='brown', text=str(problem['index']) + '-' + str(problem['contestId']), command=lambda: serach_problem(problem['index'], problem[ 'contestId'])).place(y=0.4 * i * 10, relx=0.5 * j) if j == 1: j = -1 j += 1 if j == 0: i += 5 unsolved2_fr.grid(row=6, column=1, pady=1, padx=1) compare_window.mainloop() except HTTPError: warnning = Tk() warnning.geometry("300x100") warnning.title('warnning') warnning.configure(bg="pink") warnning.iconbitmap('error.ico') l = Label(warnning, text="not valid handle ", font=('arial', 20), fg='red', bg="pink").pack() warnning.mainloop() except URLError: warnning = Tk() warnning.geometry("300x100") warnning.configure(bg="gray") warnning.iconbitmap('error.ico') warnning.title('warnning') l = Label(warnning, text="please check internet", font=('arial', 20), fg='red', bg='gray').pack() warnning.mainloop()
def print_news(): news_data = [] files = glob.glob("*.json") for data_file in files: f = open(data_file) try: data = json.load(f) news_data.append(data) except: print('Error') # GUI # canvas.pack(side='left', fill='y') # vsb = tk.Scrollbar(window, orient="vertical", command=canvas.yview) # vsb.pack(side='right', fill='y') # canvas.configure(yscrollcommand=vsb.set) # canvas.bind('<Configure>', on_configure) # data_frame = tk.Frame(window, bg='#d7d5f7', height='800', width='1200', bd=0) # canvas.create_window((0, 0), window=data_frame, anchor='nw') data_frame = tk.Frame(window) data_frame.pack(side="left", expand=0, fill="y") sf = ScrolledFrame(data_frame, width=1150, height=250, bg='#ffffff') sf.pack(side="left", expand=1, fill="y") # Bind the arrow keys and scroll wheel sf.bind_arrow_keys(data_frame) sf.bind_scroll_wheel(data_frame) frame = sf.display_widget(tk.Frame) frame['bg'] = '#d7d5f7' frame['bd'] = 15 frame['relief'] = 'sunken' for news_list in news_data: for news in news_list['articles']: print(news['description']) l = tk.Label(text=news['title'].title(), fg='#3f0052', bg='#d7d5f7', wraplength=1120, master=frame, font="-size 18 -weight bold", justify='left', pady='10') l.pack() l = tk.Label(text=news['description'], bg='#d7d5f7', fg='#3f0052', wraplength=1120, master=frame, font="-size 14", justify='left', padx='15') l.pack() l = tk.Label( text= '--------------------------------------------------------------------------------------------------', bg='#d7d5f7', fg='#3f0052', wraplength=1120, master=frame, font="-size 14", justify='left', pady='25') l.pack() window.mainloop()