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 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 put_songs(self): # Set height and width of scroll frame sf_width = 7 / 10 * self.width sf_height = 4 / 5 * self.height # Create scrolled frame and place it sf = ScrolledFrame(self.root, width=sf_width, height=sf_height) sf.place(x=(1 / 5 * self.width), y=(1 / 15 * self.height)) # Bind the arrow keys and scroll wheel sf.bind_arrow_keys(self.root) sf.bind_scroll_wheel(self.root) # Create a frame within the ScrolledFrame inner_frame = sf.display_widget(Frame) # Getting the number of songs and creating the appropriate number of rows and columns number_of_songs = len(os.listdir(self.folder)) num_cols = 4 row_temp = float(number_of_songs / num_cols) if not row_temp.is_integer(): num_rows = int(row_temp) + 1 else: num_rows = int(row_temp) # Creating a list of all the songs songs = list() song_folders = os.listdir('D:\\SongPlayer\\songs\\') for folder in song_folders: songs.append(MusicInterpreter(self.folder, folder)) # Creating a list of pics pics = list() pic_counter = 0 # Determining the size of the icon icon_size_dimension = int(sf_width / num_cols) music_counter = 0 # Looping through the songs and creating a button for each song for row in range(num_rows): for column in range(num_cols): # This if statement determines if there are more songs to make if music_counter < number_of_songs: music = songs[music_counter] mir = Image.open(music.getPic()).resize((icon_size_dimension, icon_size_dimension), Image.ANTIALIAS) pics.append(ImageTk.PhotoImage(mir)) # Creates the music button MI = MusicIcon(self, inner_frame, music, pics[pic_counter], icon_size_dimension) w = MI.get_button() music_counter += 1 pic_counter += 1 # putting it in grid layout w.grid(row=row, column=column, padx=0, pady=0)
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 create_column(currentValue): show_scroll=tk.Label(canvas,text="Choose word to replace" ,bg='#6DD5ED', bd=10) show_scroll.place(relx=0.5, rely=0.4, relwidth=0.8, relheight=0.05, anchor='n') sf = ScrolledFrame(canvas) sf.place(relx=0.5, rely=0.45, relwidth=0.8, relheight=0.35, anchor='n') # Bind the arrow keys and scroll wheel sf.bind_arrow_keys(canvas) sf.bind_scroll_wheel(canvas) # Create a frame within the ScrolledFrame inner_frame = sf.display_widget(tk.Frame) global general_checkbuttons general_checkbuttons = {} col=3 counterX=0 counterY=0 arrayAns=[] # print(currentValue) # currentValue=["A","B","C","D","A","B","C","D","A","B","C","D","A","B","C","D"] root.grid_columnconfigure(4, minsize=50) for i in range(len(currentValue)): for y in range(col): if counterX % col!= 0 or i==0: cal=i%col cb = tk.Checkbutton(inner_frame, font=(None, 12),variable=currentValue[i],text=currentValue[i], wraplength=250) cb.grid(row=counterY, column=cal, sticky="w", pady=1, padx=1) general_checkbuttons[i] = cb break elif counterX %col ==0: cal=i%col counterY+=1 cb = tk.Checkbutton(inner_frame, font=(None, 12),variable=currentValue[i],text=currentValue[i], wraplength=250) cb.grid(row=counterY, column=cal, sticky="w", pady=1, padx=1) general_checkbuttons[i] = cb break counterX+=1 frameSearch=tk.Frame(canvas,bd=5,bg="#6DD5ED") frameSearch.place(rely=0.80,relx=0.1,relwidth=0.74, relheight=0.04) entrySearch=tk.Entry(frameSearch) entrySearch.place(relwidth=1) entrySearch.insert(0, 'Search for words') entrySearch.bind("<FocusIn>", lambda args: entrySearch.delete('0', 'end')) entrySearch.bind("<KeyPress>", lambda args: valueSearch(entrySearch.get(),currentValue)) buttonWord = tk.Button(canvas, text='Choose Word', command=lambda:extractChecked(general_checkbuttons,currentValue,True)) buttonWord.place(rely=0.80,relx=0.84)
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()
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 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 __init__(self, parent): super().__init__(parent) self['text'] = 'Links' self.update_idletasks() h = self.parent.winfo_reqheight() w = self.parent.winfo_reqwidth() self._flow = None self._grid_rows_descr: List[Dict] = [] self._possible_input: List[str] = [] self._active_wd_idx = -1 self.grid() self.rowconfigure(0, weight=1) self.rowconfigure(1, weight=1) self._infovar = StringVar() self._info_entry = Entry(self, name='flow_info', textvariable=self._infovar, width=35) self._info_entry.grid(row=0, column=0, padx=PADX, pady=PADY, sticky=N + W + E) self._info_desr = { 'getter': self._infovar.get, 'setter': self._infovar.set, 'wd': self._info_entry } # Content will be scrolable self._content = ScrolledFrame(self, use_ttk=True, height=int(h / 5), width=int((w / 2))) self._content.grid(row=1, column=0, padx=PADX, pady=PADY_S, sticky=W + E) # Create the params frame within the ScrolledFrame self._links_view = self._content.display_widget(Frame) return
def _build(self): self._label_selected = Label(master=self, text=f'{lang["pu_curr_elements"]}', bg='darkgray') self._label_selected.place(in_=self, x=10, y=10) container = ScrolledFrame(master=self, bg='darkgray', width=465, height=75, borderwidth=1, relief="solid", scrollbars="vertical") container.place(in_=self, x=10, y=30) self._frame_selected = container.display_widget(Frame, bg='darkgray', width=465) self._label_choice = Label(master=self, text=f'{lang["pu_choice_elements"]}', bg='darkgray') self._label_choice.place(in_=self, x=10, y=110) container = ScrolledFrame(master=self, bg='darkgray', width=465, height=75, borderwidth=1, relief="solid", scrollbars="vertical") container.place(in_=self, x=10, y=130) self._frame_choice = container.display_widget(Frame, bg='darkgray', width=465) super()._build() self._resize() pass
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 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)
atexit.register(exit_handler) 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()
#Label(fr1, text = "Тема:", width = 30, height = 2, font = "Arial 13").pack(side = LEFT) #поле ввода темы #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())
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 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!")
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()
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)
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()
class DataView(View): def __init__(self, parent): super().__init__(parent) self['text'] = 'Data' # self['bg'] = 'green' h = self.parent.winfo_reqheight() w = self.parent.winfo_reqwidth() self.grid() # self.grid_propagate(False) self.rowconfigure(0, weight=1) self.rowconfigure(1, weight=1) # self.rowconfigure(2, weight=1) # self.columnconfigure(0, pad=15) self.columnconfigure(0, weight=1) # Last existing output self._data_last = Frame(self, height=int(h*0.3), highlightbackground='gray', highlightthickness=1) self._data_last.grid(row=0, column=0, padx=PADX, pady=PADY_S, sticky=W + E + N + S) self._data_last.columnconfigure(0, weight=1) self._data_last.rowconfigure(0, weight=1) self._data_last.grid_propagate(False) # self._last_view = Label(self._data_last, name='last image') # Setup canvas inside the frame # self._canvas_data_last = Canvas(self._data_last, bg='green') # self._canvas_data_last.grid(row=0, column=0, padx=PADX_S, pady=PADY_S, sticky=W + E + N + S) #Add PIL image to the Canvas # canvas.create_image(10,10,anchor=NW,image=img) # Preview content will be scrolable self.content = ScrolledFrame(self, height=int(h*0.3), use_ttk=True) # Bind the arrow keys and scroll wheel # self.content.bind_arrow_keys(self) # self.content.bind_scroll_wheel(self) self.content.grid(row=1, column=0, padx=PADX, pady=PADY_S, sticky=W + E + N + S) # Create the preview frame within the ScrolledFrame self.preview_view = self.content.display_widget(Frame) # self.data_actions = Frame(self, height=int(h*0.2), highlightbackground='gray', highlightthickness=1) # self.data_actions.grid(row=2, column=0, padx=PADX, pady=PADY_S, sticky=W + E + S) # self.data_actions.columnconfigure(0, weight=1) # self.data_actions.columnconfigure(1, weight=1) # self.data_actions.columnconfigure(2, weight=1) # self.data_actions.columnconfigure(3, weight=1) # self.data_actions.columnconfigure(4, weight=1) # self._preview_height = DEFAULT_VIEW_SIZE # self._preview_width = DEFAULT_VIEW_SIZE # self.scale_frame = LabelFrame(self.data_actions, text='Preview size:') # self.scale_frame.grid(row=0, column=0, columnspan=4, padx=PADX_S, pady=PADY_S, sticky=W+E) # self.scale_frame.columnconfigure(0, weight=1) # self.scale_frame.columnconfigure(1, weight=1) # self.scale_frame.columnconfigure(2, weight=1) # self.scale_frame.columnconfigure(3, weight=1) # self.var_h = IntVar() # self.var_h.set(self._preview_height) # self.scale_h = Scale(self.scale_frame, from_=50, to=500, resolution=50, variable=self.var_h, orient=HORIZONTAL, length=400) # self.scale_h.grid(row=0, column=0, columnspan=3, padx=PADX_S, pady=PADY_S, sticky=W+E) # self.scale_h.bind("<ButtonRelease-1>", self._set_h) # self.var_fixed_size = BooleanVar() # self.fixed_size = Checkbutton(self.scale_frame, variable=self.var_fixed_size, text='Fixed size', onvalue=True, offvalue=False, command=self._fix_size) # self.fixed_size.grid(row=0, column=3, padx=PADX_S, pady=PADY_S, sticky=W+E) # self.btn_save = Button(self.data_actions, text='Save', width=BTNW_S, command=self._save) # self.btn_save.grid(row=0, column=4, padx=PADX, pady=PADY) self._out = None self._idx_map :Dict = {} self._grid_rows: List[Widget] = [] self._storage: FlowStorage = None self._last_view = None return @property def storage(self) -> FlowStorage: return self._storage @storage.setter def storage(self, storage) -> None: self._storage = storage return def clear_view(self) -> None: self._out = None self._idx_map = {} for row in self._grid_rows: row.grid_remove() self._grid_rows.clear() self.content.scroll_to_top() if self._last_view is not None: self._last_view.grid_remove() return def default(self) -> None: # if self.var_fixed_size.get(): # return self._preview_height = DEFAULT_VIEW_SIZE self._preview_width = DEFAULT_VIEW_SIZE # self.var_h.set(self._preview_height) self._preview() return def _preview_size(self, image) -> Tuple[int,int]: (h, w) = image.shape[:2] ratio = w/h if h > self._preview_height: h = self._preview_height w = int(h*ratio) elif w > self._preview_width: w = self._preview_width h = int(w/ratio) elif h < self._preview_height and w < self._preview_width: h = self._preview_height w = int(h*ratio) else: pass return (w, h) def _fit_image(self, image): dim = self._preview_size(image) image = cv2.resize(image, dim, interpolation=cv2.INTER_NEAREST) return image def _preview_image_list(self, parent, image: List[np.ndarray], name: str) -> Widget: image = cv2.hconcat(image) return self._preview_image(parent, image, name) def _preview_image(self, parent, image: np.ndarray, name: str) -> Widget: preview = self._fit_image(image) pil_image = Image.fromarray(preview) photo = ImageTk.PhotoImage(pil_image) view = Label(parent, name=name, image=photo) view.image = photo return view def _preview_object(self, parent, data: any, name: str) -> Widget: view = Label(parent, name=name, border=1) # text = json.dumps(data, indent = 3) # df = pd.DataFrame(data) view.config(text = data) return view def _get_preview(self, ref_type: FlowDataType) -> Callable: views = { FlowDataType.NP_ARRAY: self._preview_image, FlowDataType.LIST_NP_ARRAYS: self._preview_image_list } return views.get(ref_type, self._preview_object) def _clear_preview(self, idx: int) -> None: if len(self._grid_rows) > 0: self._out = None # map idx to preview idx row_idx = self._get_row_idx(f'{idx}') if row_idx == WITHOUT_PREVIEW_DATA: return row_idx = max(len(self._idx_map)-1, self._get_row_idx(f'{idx}')) try: # remove idx mapping for the idx self._idx_map.pop(f'{row_idx}') # remove existing preview item with the idx res = self._grid_rows.pop(row_idx) res.grid_remove() except IndexError: pass return def update_result(self, idx: int, state_id: str) -> None: self._show_last(state_id) self. _clear_preview(idx) return def _create_row_output_container(self, row_idx: int, title: str) -> Widget: state_frame = LabelFrame(self.preview_view, name=f'--{row_idx}--', text=title) state_frame.grid(row=row_idx, column=0, sticky=W) state_frame.rowconfigure(0, pad=15) state_frame.columnconfigure(0, weight=1) state_frame.columnconfigure(0, pad=15) # state_frame.columnconfigure(1, weight=1) # state_frame.columnconfigure(1, pad=15) return state_frame def _create_preview(self, row_idx, title, out_data, out_refs) -> None: preview_frame = self._create_row_output_container(row_idx, title) # previews for a state outputs for i, ref in enumerate(out_refs): (ref_extr, ref_intr, ref_type) = ref data = out_data.get(ref_intr) if data is None: continue preview = self._get_preview(ref_type) # convert to a conventional format (without '.') name = ref_extr.replace('.', '-') widget = preview(preview_frame, data, name) widget.grid(row=i, column=0, sticky=W) widget.bind('<Button-1>', self._on_click) try: # remove existing item with the row_idx self._grid_rows.pop(row_idx) except IndexError: pass # set new one self._grid_rows.insert(row_idx, preview_frame) # Scroll view if need self.update_idletasks() h = preview_frame.winfo_height() self.content.focus_set() self.content.yview(SCROLL, h, UNITS) return def _get_row_idx(self, state_id: str) -> int: row_idx = self._idx_map.get(state_id, WITHOUT_PREVIEW_DATA) return row_idx @staticmethod def _parse_out_refs(refs) -> Tuple[str, str]: parts =refs[0][0].split('-') state_id = parts[0] title = '-'.join(parts[0:len(parts)-1]) return state_id, title def _show_last(self, state_id: str) -> None: out_data = self._storage.get_state_output_data(state_id) refs = self._storage.get_state_output_refs(state_id) if out_data is None or refs is None: return out_refs = [(ref.ext_ref, ref.int_ref, ref.data_type) for ref in refs] if len(out_refs) > 0: ref = out_refs[0] (ref_extr, ref_intr, ref_type) = ref data = out_data.get(ref_intr) if data.dtype == np.dtype('uint8'): pil_image = Image.fromarray(data) photo = ImageTk.PhotoImage(pil_image) self._last_view = Label(self._data_last, name='last image', image=photo) self._last_view.image = photo self._last_view.grid(row=0, column=0, padx=PADX_S, pady=PADY_S, sticky=W + E + N + S) else: self._last_view.grid_remove() # self._canvas_data_last.create_image(x1=10, y1=10, anchor=NW, image=photo) return def _preview(self) -> None: if self._out is None: return (out_refs, out_data) = self._out if len(out_refs) > 0: state_id, title = self._parse_out_refs(out_refs) row_idx = self._get_row_idx(state_id) self._create_preview(row_idx, title, out_data, out_refs) return def _map_idx_to_row_idx(self, idx: int) -> None: preview_row = len(self._idx_map) (out_refs, out_data) = self._out if len(out_refs) == 0 and len(out_data) == 0: # No data for preview self._idx_map[f'{idx}'] = WITHOUT_PREVIEW_DATA return # map idx to row_idx self._idx_map[f'{idx}'] = min(idx, preview_row) return def _show_preview(self, idx: int, state_id: str) -> None: out_data = self._storage.get_state_output_data(state_id) refs = self._storage.get_state_output_refs(state_id) if out_data is None or refs is None: return out_refs = [(ref.ext_ref, ref.int_ref, ref.data_type) for ref in refs] self._out = (out_refs, out_data) self._map_idx_to_row_idx(idx) self._preview() return def show_result(self, idx: int, state_id: str) -> None: self._show_preview(idx, state_id) self._show_last(state_id) return def _on_click(self, event) -> None: event.widget.focus_set() active_widget_name = event.widget._name print(active_widget_name) for row in self._grid_rows: for child in row.children: if child == active_widget_name: self._plot(child) return def _plot(self, name: str) -> None: parts = name.split('-') state_id = parts[0] + '-' + parts[2] key = parts[3] data_dict = self._storage.get_state_output_data(state_id) data = data_dict.get(key) plot_dlg = PlotDialog(self, name, data) return def _set_h(self, event) -> None: self._preview_height = self.scale_h.get() self._preview() return def _fix_size(self) -> None: # self.scale_h['state'] = NORMAL # if self.var_fixed_size.get() == True: # self.scale_h['state'] = DISABLED return def _save(self) -> None: print('save') return # TODO: # https://stackoverflow.com/questions/28005591/how-to-create-a-scrollable-canvas-that-scrolls-without-a-scroll-bar-in-python def _move(self, preview_frame): deltay = self._preview_height deltax = self._preview_width # make sure we don't move beyond our scrollable region (x0,y0,x1,y1) = self.content._canvas.coords() deltay = 0 if (deltay > 0 and y1 >= 400) else deltay deltay = 0 if (deltay < 0 and y0 <= -400) else deltay deltax = 0 if (deltax > 0 and x1 >= 400) else deltax deltax = 0 if (deltax < 0 and x0 <= -400) else deltax # move the item, then scroll it into view self.content._canvas.move(preview_frame, deltax, deltay) self._make_visible(preview_frame) def _make_visible(self, preview_frame) -> None: # determine the bounding box of the visible area of the screen (cx0,cy0) = (self.content._canvas.canvasx(0), self.content._canvas.canvasy(0)) (cx1,cy1) = (self.content._canvas.canvasx(self.content._canvas.cget("width")), self.content._canvas.canvasy(self.content._canvas.cget("height"))) # determine the bounding box of the thing to be made visible (x0,y0,x1,y1) = self.content._canvas.coords(preview_frame) # determine how far off the screen the object is deltax = x0-cx0 if x0 <= cx0 else x1-cx1 if x1 >= cx1 else 0 deltay = y0-cy0 if y0 <= cy0 else y1-cy1 if y1 >= cy1 else 0 # scroll the canvas to make the item visible self.canvas.xview("scroll", int(deltax), "units") self.canvas.yview("scroll", int(deltay), "units") return
class CoronaDB: def __init__(self, master): self.master = master self.createWidgets() def createWidgets(self): style = ttk.Style() style.theme_use("clam") style.configure( "LightText.TFrame", background=COLOUR_SECONDARY, foreground=COLOUR_LIGHT_TEXT, ) style.configure( "LightText.TLabel", background=COLOUR_PRIMARY, foreground=COLOUR_LIGHT_TEXT, ) style.configure( "Button.TButton", background=COLOUR_SECONDARY, foreground=COLOUR_PRIMARY, ) self.corona_label = ttk.Label(self.master, text='Corona Virus Data Calculator', style="LightText.TLabel", font=('helvetica', 20)) self.corona_label.grid(row=0, sticky='N', padx=50, pady=25) self.button = ttk.Button(text='Show(Country)', command=self.getcorona, style="Button.TButton") self.button.grid(row=2, sticky='W', padx=50, pady=5) self.button1 = ttk.Button(text='Show(All)', command=self.allcompare, style="Button.TButton") self.button1.grid(row=2, sticky='E', padx=50, pady=5) # self.corona_frame = ttk.Frame(self.master, borderwidth = 5, width=500, height=250, relief='groove', style="LightText.TFrame") # self.corona_frame.grid_propagate(False) # self.corona_frame.grid(row=3, sticky='w', padx=50, pady=5) self.corona_frame = ScrolledFrame(self.master, borderwidth = 5, width=400, height=220, bg='black') self.corona_frame.grid(row=4, sticky='w', padx=50, pady=5) # Bind the arrow keys and scroll wheel self.corona_frame.bind_arrow_keys(self.master) self.corona_frame.bind_scroll_wheel(self.master) self.inner_frame = self.corona_frame.display_widget(Frame) options = [ "World", "Czech Republic", "India", "United States of America", "Spain", "Italy", "France", "Germany", "China", "United Kingdom", "Turkey", "Belgium", "Switzerland", "Netherlands", "Canada", "Brazil", "Portugal", "Austria", "Pakistan", ] self.clicked = StringVar() self.clicked.set(options[0]) self.drop = OptionMenu(self.master, self.clicked, *options) self.drop.config(bg = "#808080") self.drop["menu"].config(bg="white") self.drop.grid(row=1, sticky='W', padx=50, pady=5) def allcompare(self): if self.inner_frame.grid_slaves(): self.clearContents() endpoint = "https://api.covid19api.com/summary" response = requests.get(endpoint) corona = response.json() dict = {} for data in corona['Countries']: new_dict = {**dict, **{data['Country']: data['TotalConfirmed']}} dict = new_dict sorted_data = sorted(dict.items(), key=operator.itemgetter(1),reverse=True) i = 1 for item in sorted_data: text_val1 = item[0] text_val2 = item[1] ttk.Label(self.inner_frame, borderwidth = 3, width = 20, text=text_val1, font=('helvetica', 16), style="Button.TButton", wraplength=500).grid(row=i, column=2) ttk.Label(self.inner_frame, borderwidth = 3, width = 20, text=text_val2, font=('helvetica', 16), style="Button.TButton", wraplength=500).grid(row=i, column=4) i = i + 1 def getcorona(self): if self.inner_frame.grid_slaves(): self.clearContents() endpoint = "https://api.covid19api.com/summary" response = requests.get(endpoint) corona = response.json() # corona data in json format dd_clicked = self.clicked.get() keys = {'NewConfirmed': 'New Confirmed', 'TotalConfirmed': 'Total Cases', 'NewDeaths': 'New Deaths', 'TotalDeaths': 'Total Deaths', 'NewRecovered': 'New Recovered', 'TotalRecovered': 'Total Recovered'} if dd_clicked != "World": for country_data in corona['Countries']: if country_data['Country'] == dd_clicked: i = 1 for item in keys: text_val1 = keys[item] text_val2 = str(country_data[item]) ttk.Label(self.inner_frame, borderwidth = 3, width = 20, text=text_val1, font=('helvetica', 16), style="Button.TButton", wraplength=500).grid(row=i, column=2) ttk.Label(self.inner_frame, borderwidth = 3, width = 20, text=text_val2, font=('helvetica', 16), style="Button.TButton", wraplength=500).grid(row=i, column=4) i = i + 1 else: i = 1 for item in keys: text_val1 = keys[item] text_val2 = str(corona['Global'][item]) ttk.Label(self.inner_frame, borderwidth = 3, width = 20, text=text_val1, font=('helvetica', 16), style="Button.TButton", wraplength=500).grid(row=i, column=2) ttk.Label(self.inner_frame, borderwidth = 3, width = 20, text=text_val2, font=('helvetica', 16), style="Button.TButton", wraplength=500).grid(row=i, column=4) i = i + 1 def clearContents(self): for widget in self.inner_frame.grid_slaves(): widget.destroy()
def createWidgets(self): style = ttk.Style() style.theme_use("clam") style.configure( "LightText.TFrame", background=COLOUR_SECONDARY, foreground=COLOUR_LIGHT_TEXT, ) style.configure( "LightText.TLabel", background=COLOUR_PRIMARY, foreground=COLOUR_LIGHT_TEXT, ) style.configure( "Button.TButton", background=COLOUR_SECONDARY, foreground=COLOUR_PRIMARY, ) self.corona_label = ttk.Label(self.master, text='Corona Virus Data Calculator', style="LightText.TLabel", font=('helvetica', 20)) self.corona_label.grid(row=0, sticky='N', padx=50, pady=25) self.button = ttk.Button(text='Show(Country)', command=self.getcorona, style="Button.TButton") self.button.grid(row=2, sticky='W', padx=50, pady=5) self.button1 = ttk.Button(text='Show(All)', command=self.allcompare, style="Button.TButton") self.button1.grid(row=2, sticky='E', padx=50, pady=5) # self.corona_frame = ttk.Frame(self.master, borderwidth = 5, width=500, height=250, relief='groove', style="LightText.TFrame") # self.corona_frame.grid_propagate(False) # self.corona_frame.grid(row=3, sticky='w', padx=50, pady=5) self.corona_frame = ScrolledFrame(self.master, borderwidth = 5, width=400, height=220, bg='black') self.corona_frame.grid(row=4, sticky='w', padx=50, pady=5) # Bind the arrow keys and scroll wheel self.corona_frame.bind_arrow_keys(self.master) self.corona_frame.bind_scroll_wheel(self.master) self.inner_frame = self.corona_frame.display_widget(Frame) options = [ "World", "Czech Republic", "India", "United States of America", "Spain", "Italy", "France", "Germany", "China", "United Kingdom", "Turkey", "Belgium", "Switzerland", "Netherlands", "Canada", "Brazil", "Portugal", "Austria", "Pakistan", ] self.clicked = StringVar() self.clicked.set(options[0]) self.drop = OptionMenu(self.master, self.clicked, *options) self.drop.config(bg = "#808080") self.drop["menu"].config(bg="white") self.drop.grid(row=1, sticky='W', padx=50, pady=5)
def __init__(self, parent): super().__init__(parent) self['text'] = 'Data' # self['bg'] = 'green' h = self.parent.winfo_reqheight() w = self.parent.winfo_reqwidth() self.grid() # self.grid_propagate(False) self.rowconfigure(0, weight=1) self.rowconfigure(1, weight=1) # self.rowconfigure(2, weight=1) # self.columnconfigure(0, pad=15) self.columnconfigure(0, weight=1) # Last existing output self._data_last = Frame(self, height=int(h*0.3), highlightbackground='gray', highlightthickness=1) self._data_last.grid(row=0, column=0, padx=PADX, pady=PADY_S, sticky=W + E + N + S) self._data_last.columnconfigure(0, weight=1) self._data_last.rowconfigure(0, weight=1) self._data_last.grid_propagate(False) # self._last_view = Label(self._data_last, name='last image') # Setup canvas inside the frame # self._canvas_data_last = Canvas(self._data_last, bg='green') # self._canvas_data_last.grid(row=0, column=0, padx=PADX_S, pady=PADY_S, sticky=W + E + N + S) #Add PIL image to the Canvas # canvas.create_image(10,10,anchor=NW,image=img) # Preview content will be scrolable self.content = ScrolledFrame(self, height=int(h*0.3), use_ttk=True) # Bind the arrow keys and scroll wheel # self.content.bind_arrow_keys(self) # self.content.bind_scroll_wheel(self) self.content.grid(row=1, column=0, padx=PADX, pady=PADY_S, sticky=W + E + N + S) # Create the preview frame within the ScrolledFrame self.preview_view = self.content.display_widget(Frame) # self.data_actions = Frame(self, height=int(h*0.2), highlightbackground='gray', highlightthickness=1) # self.data_actions.grid(row=2, column=0, padx=PADX, pady=PADY_S, sticky=W + E + S) # self.data_actions.columnconfigure(0, weight=1) # self.data_actions.columnconfigure(1, weight=1) # self.data_actions.columnconfigure(2, weight=1) # self.data_actions.columnconfigure(3, weight=1) # self.data_actions.columnconfigure(4, weight=1) # self._preview_height = DEFAULT_VIEW_SIZE # self._preview_width = DEFAULT_VIEW_SIZE # self.scale_frame = LabelFrame(self.data_actions, text='Preview size:') # self.scale_frame.grid(row=0, column=0, columnspan=4, padx=PADX_S, pady=PADY_S, sticky=W+E) # self.scale_frame.columnconfigure(0, weight=1) # self.scale_frame.columnconfigure(1, weight=1) # self.scale_frame.columnconfigure(2, weight=1) # self.scale_frame.columnconfigure(3, weight=1) # self.var_h = IntVar() # self.var_h.set(self._preview_height) # self.scale_h = Scale(self.scale_frame, from_=50, to=500, resolution=50, variable=self.var_h, orient=HORIZONTAL, length=400) # self.scale_h.grid(row=0, column=0, columnspan=3, padx=PADX_S, pady=PADY_S, sticky=W+E) # self.scale_h.bind("<ButtonRelease-1>", self._set_h) # self.var_fixed_size = BooleanVar() # self.fixed_size = Checkbutton(self.scale_frame, variable=self.var_fixed_size, text='Fixed size', onvalue=True, offvalue=False, command=self._fix_size) # self.fixed_size.grid(row=0, column=3, padx=PADX_S, pady=PADY_S, sticky=W+E) # self.btn_save = Button(self.data_actions, text='Save', width=BTNW_S, command=self._save) # self.btn_save.grid(row=0, column=4, padx=PADX, pady=PADY) self._out = None self._idx_map :Dict = {} self._grid_rows: List[Widget] = [] self._storage: FlowStorage = None self._last_view = None return
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 run(self): def open_button_path_fun(path): return path tk.Label(self.window, text='File Size Inspector', font=font.Font(family='Helvetica', size=14, weight='bold')).grid(row=0, column=0) tk.Label(self.window, text='').grid(row=1, column=0) frame = tk.Frame(self.window) tk.Label(frame, text=f'Current path: {Path(self.data_prepare_object.current_path).shorten_path_if_necessary()}', font=font.Font(family='Helvetica', size=12, weight='normal')).grid(row=0, column=0) tk.Label(frame, text=' ').grid(row=0, column=1) tk.Button(frame, text='CHANGE', command=lambda: [self.change_button_function()]).grid(row=0, column=2) frame.grid(row=2, column=0) tk.Label(self.window, text='').grid(row=3, column=0) sf = ScrolledFrame(self.window, width=520, height=425) sf.grid(row=5, column=0) sf.bind_arrow_keys(self.window) sf.bind_scroll_wheel(self.window) sf.focus() inner_frame = sf.display_widget(tk.Frame) frame = tk.Frame(inner_frame) i = 0 for header_name in list(self.fields_width_dictionary.keys()): l_box = tk.Listbox(frame, bg=self.window['bg'], justify=tk.CENTER, relief=tk.GROOVE, width=self.fields_width_dictionary[header_name], height=1, font=font.Font(family='Helvetica', size=10, weight='bold')) l_box.insert(0, header_name) l_box.grid(row=0, column=i) i += 1 frame.grid(row=5, column=0, sticky='W') if len(list(self.data_prepare_object.selected_elements_dictionary.keys())) > self.max_number_of_elements_on_screen: tk.Label(self.window, text=f'Showing {self.max_number_of_elements_on_screen} largest elements from this directory.', fg='#e67300', font=font.Font(family='Helvetica', size=10, weight='normal')).grid(row=4, column=0) i = 0 paths = list(self.data_prepare_object.selected_elements_dictionary.keys()) for entry_path in paths: frame = tk.Frame(inner_frame) content_dictionary = dict(zip(self.fields, [self.data_prepare_object.selected_elements_dictionary[entry_path].name, self.data_prepare_object.selected_elements_dictionary[entry_path].type, f'{self.data_prepare_object.selected_elements_dictionary[entry_path].size} {self.data_prepare_object.selected_elements_dictionary[entry_path].size_unit}'])) j = 0 for column_name in list(content_dictionary.keys()): l_box_name = tk.Listbox(frame, width=self.fields_width_dictionary[column_name], height=1, font=font.Font(family='Helvetica', size=10, weight='normal')) l_box_name.insert(0, content_dictionary[column_name]) l_box_name.grid(row=0, column=j) j += 1 if self.data_prepare_object.selected_elements_dictionary[entry_path].can_open: button = tk.Button(frame, text='OPEN', command=lambda c=i: [self.move_function(partial(open_button_path_fun, paths[c]).args[0])]) button.grid(row=0, column=i+3) frame.grid(row=i+7, column=0, sticky='W') i += 1 if i > self.max_number_of_elements_on_screen: break previous_location = Path(self.data_prepare_object.current_path).get_path_previous_location() if previous_location is not None: tk.Button(self.window, text='BACK', font=10, command=lambda: [self.move_function(previous_location)]).grid(row=i+8, column=0) self.window_on_top_update() self.adjust_window_position() self.window.mainloop()
lists=[] master2 = Tk() master2.title("Class Selection") master2.geometry("500x500+300+300") frame1=Frame(master2,bd=10,height=500,padx=10,pady=10,width=1500) v = StringVar(frame1) frame1.pack() slotA=[] slotB=[] slotC=[] slotD=[] slotE=[] slotF=[] slotG=[] slotH=[] sf = ScrolledFrame(master2, width=640, height=480) sf.pack(side="top", expand=1, fill="both") # Bind the arrow keys and scroll wheel sf.bind_arrow_keys(master2) sf.bind_scroll_wheel(master2) # Create a frame within the ScrolledFrame frame2 = sf.display_widget(Frame) classes=['No Classroom','A1-3','A1-NKN','A5-1','A5-2','A5-4','A5-5','A9-1','SC-NKN','G-106,107','A10-1a','A10-1b','A10-1c','A10-1d','A10-2a','A10-2b','A10-2c','A10-3a','A10-3b','A10-3c','Hall A','Hall B','Hall C','A13-1A','A13-3A','A13-2A','A13-2B','A13-2C','A13-2D'] def ConstraintCheck(var,i,name,slot,*args): for j in range(len(slot)): if(i==j): continue elif(var.get()!="No Classroom" and var.get()==slot[j][1]):
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()
self.clbtentry120[x + 1].set(self.closebtlist[x]) 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----------
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()