def populate_dbs(self): def select_db(): self.selected_db_var = db_var selected_db = str(db_var.get()) self.db_entry.delete(0, "end") self.db_entry.insert(0, selected_db) # we add the drop button, only if a radio-button is pressed self.drop_db_btn = Button(self.dbs_frm, text="Drop database", command=self.drop_db) self.drop_db_btn.grid(row=db_counter, column=2, pady=10, ipadx=5, ipady=2) db_var = StringVar() db_list = self.client.database_names( ) # we get the available database names of this connection db_counter = 0 read_write.log_message("[INFO] (frames.DbFrame) : DBs found: " + str(db_list)) for name in db_list: r = Radiobutton(self.dbs_frm, text=name, variable=db_var, value=name, command=select_db) r.grid(row=db_counter, column=2, pady=2) db_counter += 1
def populate_collections(self): def select_collection(): self.selected_collection_var = collection_var selected_collection = str(collection_var.get()) self.collection_entry.delete(0, "end") self.collection_entry.insert(0, selected_collection) # we add the drop button, only if a radio-button is pressed self.drop_collection_btn = Button(self.collections_frm, text="Drop collection", command=self.drop_collection) self.drop_collection_btn.grid(row=collection_counter, column=2, pady=10, ipadx=5, ipady=2) collection_var = StringVar() collection_list = [ ] # we get the available collection names of this connection but # only if a database name already exists if self.db_entry.get() is not "": collection_list = self.client[self.db_entry.get( )].collection_names(include_system_collections=False) collection_counter = 0 # this counter is responsible to place the radio-buttons into correct row for name in collection_list: r = Radiobutton(self.collections_frm, text=name, variable=collection_var, value=name, command=select_collection) r.grid(row=collection_counter, column=2, pady=2) collection_counter += 1
def _setup_widgets(self): l = Label(self.fr, text="Dont't forget click and hover, \n \ or see more by using the radio buttons") l.grid(column=0, row=0, columnspan=3, padx=5, pady=2, sticky='n') themes = sorted(list(self.style.theme_names())) # Create rasio buttons which will display themes self.theme_val = StringVar() for ix, val in enumerate(themes): themes_rb = Radiobutton(self.fr, value=val, text=val, variable=self.theme_val, command=self._change_theme) themes_rb.grid(column=0, row=ix + 1, padx=5, pady=2, sticky='nw') states = [ 'active', 'alternate', 'background', 'disabled', 'focus', 'invalid', 'pressed', 'readonly', 'selected' ] # Create rasio buttons which will display widget states self.state_val = StringVar() for iy, state in enumerate(states): st_rb = Radiobutton(self.fr, value=state, text=state, variable=self.state_val, command=self._change_state) st_rb.grid(column=1, row=iy + 1, padx=5, pady=5, sticky='nw') # selected widget, if using scrollbar place in own frame self.but = Button(self.fr, text='Button State') self.but.grid(column=3, row=ix + 2, padx=5, pady=5)
def __init__(self, parent, values, callback, **kwargs): super().__init__(parent, **kwargs) self.callback = callback self.selected_option = StringVar(self.frame) self.selected_option.set(values[0]) self.options = [] for value in values: option = Radiobutton(self.frame, text=value, value=value, variable=self.selected_option, command=self._option_changed) option.grid(padx=5, pady=5, sticky=W) self.options.append(option)
def _create_file_format_btn(self, btn_text, var_value, parent, column): ''' Creates and grids Radiobutton used for choosing solution file format. Args: btn_text (str): text displayed next to the Radiobutton. var_value (int): value of the IntVar associated with this Radiobutton. parent (Tk object): parent of this Radiobutton. column (int): column index where this Radiobutton should be gridded. ''' sol_format_btn = Radiobutton(parent, text=btn_text, variable=self.solution_format_var, value=var_value) sol_format_btn.grid(row=2, column=column, sticky=W+N, padx=2)
def _create_file_format_btn(self, btn_text, var_value, parent, column): ''' Creates and grids Radiobutton used for choosing solution file format. Args: btn_text (str): text displayed next to the Radiobutton. var_value (int): value of the IntVar associated with this Radiobutton. parent (Tk object): parent of this Radiobutton. column (int): column index where this Radiobutton should be gridded. ''' sol_format_btn = Radiobutton(parent, text=btn_text, variable=self.solution_format_var, value=var_value) sol_format_btn.grid(row=2, column=column, sticky=W + N, padx=2)
def __init__(self, fr, widg, widg1=None): ''' Used to enable state change Creates radio buttons showing states Creates check button with "Enabled", useful for testing check and radio buttons Args: fr: frame reference in calling program widg: widget reference widg1: optional widget ''' self.fr = fr self.widg = widg self.widg1 = widg1 # Create radio buttons which will display widget states # except alternate and background states = [ 'active', 'disabled', 'focus', 'invalid', 'pressed', 'readonly', 'selected' ] self.rb = [] self.state_val = StringVar() for iy, state in enumerate(states): st_rb = Radiobutton(fr, value=state, text=state, variable=self.state_val, command=self.change_state) st_rb.grid(column=0, row=iy + 2, padx=5, pady=5, sticky='nw') self.rb.append(st_rb) st_rb.state(['disabled']) self.enabled = IntVar() self.cbOpt = Checkbutton(fr, text='Enabled', variable=self.enabled, command=self.change_state) self.cbOpt.grid(column=0, row=0) sep = Separator(orient='h') sep.grid(column=0, row=1, sticky='ew')
def __init__(self, master, layout): ''' Initializes a SelectorPanel object. master: a tkinter widget layout: a 2D list of tuples. The layout of the list defines the layout of the buttons. In each tuple, the first element is a string giving the button's text. The second is a string giving the value assigned to self.mode when the button is selected. return: a SelectorPanel object ''' Frame.__init__(self, master) self.mode = StringVar() for yindex, row in enumerate(layout): for xindex, (name, mode) in enumerate(row): button = Radiobutton(self, text=name, value=mode, variable=self.mode) button.grid(row=yindex, column=xindex) if (xindex, yindex) == (0, 0): button.invoke()
def _create_frame_with_radio_btns(self, parent, name, text, row_index, column_index, add_both=True): ''' Creates frame with one set of Radiobuttons. Args: parent (Tk object): parent of the frame. name (str): name of the parameter that will a key in options dictionary. text (list of str): list with two parameter values that should be displayed next to the first two Radiobuttons. row_index (int): index of the row where the frame should be placed using grid method. column_index (int): index of the column where the frame should be placed using grid method. add_both (bool, optional): True if the third Radiobutton with text "both" must be displayed, False otherwise, defaults to True. ''' assert len(text) == 2 v = IntVar() self.options[name] = v self.options[name].trace( 'w', (lambda *args: self.radio_btn_change(name))) frame_with_radio_btns = Frame(parent) first_option = Radiobutton(frame_with_radio_btns, text=text[0], variable=v, value=1) first_option.grid(row=0, column=0, sticky=W+N, padx=2) v.set(1) second_option = Radiobutton(frame_with_radio_btns, text=text[1], variable=v, value=2) second_option.grid(row=1, column=0, sticky=W+N, padx=2) if add_both: both = Radiobutton(frame_with_radio_btns, text='Both', variable=v, value=3) both.grid(row=3, column=0, sticky=W+N, padx=2) frame_with_radio_btns.grid(row=row_index, column=column_index, padx=1, pady=5, sticky=W+N)
def no_clicked(): """ If the category is not defined correctly """ choose = tk.Toplevel(window) program_message = tk.Label( choose, text='Вкажіть, до якої категорії належить звернення,' '\n та ми продовжимо навчання моделі') var = tk.IntVar() var.set(0) category0 = Radiobutton(choose, text='Позитивний відгук', variable=var, value=0) category1 = Radiobutton(choose, text='Негативний відгук', variable=var, value=1) category2 = Radiobutton(choose, text='Звернення на внутрішній департамент', variable=var, value=2) category3 = Radiobutton(choose, text='Хуліганське звернення', variable=var, value=3) category4 = Radiobutton( choose, text='Пропозиція щодо вдосконалення роботи', variable=var, value=4) category5 = Radiobutton( choose, text='Звернення стосовно сайту купівлі монет', variable=var, value=5) text = user_message.get('1.0', 'end-1c') def learn(): """ Continues model training on the entered message """ messagebox.showinfo(message='Дякуємо за звернення!') window.destroy() if var.get() == 0: category = 'Positive' elif var.get() == 1: category = 'Negative' elif var.get() == 2: category = 'Hotline' elif var.get() == 3: category = 'Hooligan' elif var.get() == 4: category = 'Offer' elif var.get() == 5: category = 'SiteAndCoins' model_class = ModelSingle( text=text, category=category, model='../model/save/model(nbu test data with answ).h5', way_study='../data/category_with_received_data.csv', batch_size=64, epochs=1, vocab_size=None) model_class.read() model_class.clean_and_prapare() model_class.data_to_vect() model_class.train() choose_button = tk.Button(choose, text='Підтвердити', command=learn) program_message.grid() category0.grid() category1.grid() category2.grid() category3.grid() category4.grid() category5.grid() choose_button.grid() choose.mainloop()
from tkinter import * from tkinter.ttk import Radiobutton #Program name window = Tk() window.title("Название файлов") window.geometry('400x250') # Label lbl = Label(window, text='Выберите категорию файла:') lbl.grid(column=0, row=0) #Radio Buttons rad1 = Radiobutton(window, text="название категории1", value=1) rad1.grid(column=0, row=3) rad2 = Radiobutton(window, text="название категории2", value=2) rad2.grid(column=0, row=4) rad3 = Radiobutton(window, text="название категории3", value=3) rad3.grid(column=0, row=5) rad4 = Radiobutton(window, text="название категории4", value=4) rad4.grid(column=0, row=6) window.mainloop()
def __make_radio(dialog, v): radio = Radiobutton(dialog, image=tk_image, variable=v, value=index) radio.grid(row=row, column=column) return radio
input_platform_3 = Checkbutton(checkbox_frame, text="Nintendo Switch", variable=v[3], onvalue="Nintendo Switch") input_platform_3.grid(row=0, column=3) # Radio button field lbl_mode = Label(form_frame, text="Mode").grid(row=4, column=0, sticky=W) selected_mode = StringVar(root) radio_frame = Frame(form_frame) radio_frame.grid(padx=10, pady=10, row=4, column=1, sticky=W) input_mode_0 = Radiobutton(radio_frame, text="Single-player", variable=selected_mode, value="Single-player") input_mode_0.grid(row=0, column=0) input_mode_1 = Radiobutton(radio_frame, text="Multi-player", variable=selected_mode, value="Multi-player") input_mode_1.grid(row=0, column=1) # Upload image field # Open file dialog and get the filename def upload_image(): global image_filename image_filename = filedialog.askopenfilename(title='Open')
def step_1(): def clicked(): lbl.configure(text=selected.get()) var= selected.get() step=1 counter_click(step,var) selected = IntVar() rad1 = Radiobutton(root,text='Легковой автомобиль', value=1, variable=selected) rad2 = Radiobutton(root,text='Грузовой автомобиль', value=2, variable=selected) rad3 = Radiobutton(root,text='Автобус', value=3, variable=selected) rad4 = Radiobutton(root,text='Микроавтобус', value=4, variable=selected) rad5 = Radiobutton(root,text='Мотоцикл', value=5, variable=selected) btn2 = Button(root, text="Далее", command=lambda: [clicked(),btn3.grid_remove(), btn1.grid_remove(), btn2.grid_remove(), rad1.grid_remove(), rad2.grid_remove(), rad3.grid_remove(), rad4.grid_remove(), rad5.grid_remove(),lbl1.grid_remove(), lbl4.grid_remove(),lbl2.grid_remove(),lbl3.grid_remove(),lbler.grid_remove(), lblT.grid_remove()]) btn1 = Button(root, text="Назад", command=lambda: [ start(), btn3.grid_remove(), btn1.grid_remove(), btn2.grid_remove(), rad1.grid_remove(), rad2.grid_remove(), rad3.grid_remove(), rad4.grid_remove(), rad5.grid_remove(),lbl1.grid_remove(),lbl4.grid_remove(),lbler.grid_remove(), lbl2.grid_remove(),lbl3.grid_remove(),lblT.grid_remove()]) btn3 = Button(root, text="Войти в систему", command=lambda: [ start(), btn3.grid_remove(), btn1.grid_remove(), btn2.grid_remove(), rad1.grid_remove(), rad2.grid_remove(), rad3.grid_remove(), rad4.grid_remove(), rad5.grid_remove(),lbl1.grid_remove(),lbl4.grid_remove(), lbl2.grid_remove(),lbl3.grid_remove(),lblT.grid_remove(), lbler.grid_remove()]) lbl = Label(root) x=1 y=1 rad1.grid(column=x+1, row=y+1, sticky="W") rad2.grid(column=x+1, row=y+2, sticky="W") rad3.grid(column=x+1, row=y+3, sticky="W") rad4.grid(column=x+1, row=y+4, sticky="W") rad5.grid(column=x+1, row=y+5, sticky="W") btn1.grid(column=x+0, row=y+7, sticky="W") btn2.grid(column=x+3, row=y+7, sticky="W") btn3.grid(column=0, row=0, sticky="N",pady=0,padx=0) lbl1 = tk.Label(root, text = '') lbl2 = tk.Label(root, text = 'ТЕСТ', font=("Arial Bold", 15)) lbl3 = tk.Label(root, text = '') lbl4 = tk.Label(root, text = '') lblT = tk.Label(root, text = 'Выберите авто', font=("Arial Bold", 14)) lbler = tk.Label(root, text = f'{text_error}', font=("Arial Bold", 5)) lbl1.grid(column=3, row=0, pady=0,padx=0) lbl2.grid(column=2, row=0, pady=10,padx=0) lbl3.grid(column=2, row=7, pady=0,padx=0) lbl4.grid(column=2, row=8, pady=0,padx=70) lblT.grid(column=2, row=1, pady=15,padx=0,columnspan=4) lbler.grid(column=8, row=1, pady=15,padx=0,columnspan=4) root.update()
class App(Tk): #the main class for the main window def __init__(self): Tk.__init__(self) # window properties self.title(string="Screen Recorder") self.iconbitmap("icon.ico") self.resizable(width=False, height=False) ffmpegAvailable = False for item in os.listdir(): if item == "ffmpeg.exe": ffmpegAvailable = True break if not ffmpegAvailable: self.withdraw() if messagebox.askyesno( "FFmpeg Not Found", "ffmpeg.exe could not be found in screen recorder's directory. Do you want to be redirected to the ffmpeg download website?" ): webbrowser.open_new_tab("https://ffmpeg.zeranoe.com/builds/") exit() self.cmdGen = cmdGen( ) # create a command generator object to store settings # file name label1 = Label(self, text="File Name:") label1.grid(row=0, column=0, sticky="") self.entry1 = Entry(self) self.entry1.grid(row=0, column=1, sticky="ew") # ensure the existance of the "ScreenCaptures" directory try: os.mkdir("ScreenCaptures") except FileExistsError: pass os.chdir("ScreenCaptures") # find a default file name that is currently available. defaultFile = "ScreenCapture.mp4" available = False fileNum = 0 while available == False: hasMatch = False for item in os.listdir(): if item == defaultFile: hasMatch = True break if not hasMatch: available = True else: fileNum += 1 defaultFile = "ScreenCapture" + str(fileNum) + ".mp4" os.chdir("..") self.entry1.insert(END, defaultFile) # radio buttons determine what to record self.what = StringVar() self.what.set("desktop") self.radio2 = Radiobutton(self, text="record the window with the title of: ", variable=self.what, value="title", command=self.enDis1) self.radio1 = Radiobutton(self, text="record the entire desktop", variable=self.what, value="desktop", command=self.enDis) self.radio1.grid(row=1, column=0, sticky="w") self.radio2.grid(row=2, column=0, sticky="w") self.entry2 = Entry(self, state=DISABLED) self.entry2.grid(row=2, column=1, sticky="ew") # initialize webcam self.webcamdevices = Webcam.listCam() self.webcamrecorder = Webcam.capturer("") # "record from webcam" checkbox self.rcchecked = IntVar() self.recordcam = Checkbutton(self, text="Record from webcam", command=self.checkboxChanged, variable=self.rcchecked) self.recordcam.grid(row=3, column=0) # a drop-down allowing you to select the webcam device from the available directshow capture devices self.devicename = StringVar(self) if self.webcamdevices: self.devicename.set(self.webcamdevices[0]) self.deviceselector = OptionMenu(self, self.devicename, *self.webcamdevices) self.deviceselector.config(state=DISABLED) self.deviceselector.grid(row=3, column=1) else: self.devicename.set("NO DEVICES AVAILABLE") self.recordcam.config(state=DISABLED) self.deviceselector = OptionMenu(self, self.devicename, "NO DEVICES AVAILABLE") self.deviceselector.config(state=DISABLED) self.deviceselector.grid(row=3, column=1) self.opButton = Button(self, text="⚙ Additional Options...", command=self.openSettings) self.opButton.grid(row=4, column=1, sticky='e') # the "start recording" button self.startButton = Button(self, text="⏺ Start Recording", command=self.startRecord) self.startButton.grid(row=5, column=0, columnspan=2) # some variables self.recording = False # are we recording? self.proc = None # the popen object for ffmpeg (during screenrecord) self.recorder = recordFile.recorder( ) # the "recorder" object for audio (see recordFile.py) self.mergeProcess = None # the popen object for ffmpeg (while merging video and audio files) # start the ffmpeg monitoring callback self.pollClosed() def openSettings(self): self.settings = settingsWin(self, self.cmdGen, self.recorder) def pollClosed(self): """callback that repeats itself every 100ms. Automatically determines if ffmpeg is still running.""" if self.recording: if self.proc.poll() != None: self.startRecord() messagebox.showerror( "ffmpeg error", "ffmpeg has stopped working. ERROR: \n" + str(self.proc.stderr.read()).replace('\\r\\n', '\n')) if self.recorder.error: self.startRecord() if self.mergeProcess and self.recording == False: if self.mergeProcess.poll() != None: self.startButton.config(text="⏺ Start Recording", state=NORMAL) self.title(string="Screen Recorder") self.after(100, self.pollClosed) def enDis(self): """Called when the "desktop" radio button is pressed""" self.entry2.config(state=DISABLED) # self.what.set("desktop") def enDis1(self): """Called when the "window title" radio button is pressed""" self.entry2.config(state=NORMAL) # self.what.set("title") def checkboxChanged(self): """Called when the "record webcam" checkbox is checked or unchecked.""" #self.rcchecked = not self.rcchecked if self.rcchecked.get(): self.deviceselector.config(state=NORMAL) else: self.deviceselector.config(state=DISABLED) def startRecord(self): """toggles recording. Will start conversion subprocess on recording completion""" if self.recording == False: # change the window self.title(string="Screen Recorder (Recording...)") self.startButton.config(text="⏹️ Stop Recording") self.filename = self.entry1.get() # disable interface self.entry1.config(state=DISABLED) self.radio1.config(state=DISABLED) self.radio2.config(state=DISABLED) self.deviceselector.config(state=DISABLED) self.opButton.config(state=DISABLED) if self.what.get() == "title": self.entry2.config(state=DISABLED) # ensure the existence of the "tmp" directory try: os.mkdir("tmp") except FileExistsError: pass # start screen recording process self.recording = True startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW startupinfo.wShowWindow = subprocess.SW_HIDE # self.cmdGen.setFps(60) # self.cmdGen.setEncode('nvenc_h264') # CPU: mpeg4 // NVIDIA: h264_nvenc // AMD: no. self.cmdGen.setSource(self.what.get() == "title", self.entry2.get()) command = self.cmdGen.getCmd("tmp/tmp.mkv") self.proc = subprocess.Popen(args=command, startupinfo=startupinfo, stderr=subprocess.PIPE) # start audio recording self.recorder.record("tmp/tmp.wav") # start webcam recording, if checked self.recordcam.config(state=DISABLED) if self.rcchecked.get() and self.webcamdevices: self.webcamrecorder.setDevice(str(self.devicename.get())) self.webcamrecorder.startCapture("tmp/webcamtmp.mkv") # minimize the window to get it out of the way of the recording self.iconify() elif self.recording == True: self.deiconify() defaultFile = self.filename # re-enable interface self.entry1.config(state=NORMAL) self.radio1.config(state=NORMAL) self.radio2.config(state=NORMAL) self.opButton.config(state=NORMAL) if self.webcamdevices: self.recordcam.config(state=NORMAL) if self.rcchecked.get(): self.deviceselector.config(state=NORMAL) if self.what.get() == "title": self.entry2.config(state=NORMAL) available = False fileNum = 0 # stop all recording processes self.recording = False self.proc.terminate() self.recorder.stop_recording() if self.rcchecked.get() and self.webcamdevices: self.webcamrecorder.stopCapture() try: os.mkdir("ScreenCaptures") except FileExistsError: pass # change the window title and button text to reflect the current process self.title(string="Screen Recorder (converting...)") self.startButton.config( text="converting your previous recording, please wait...", state=DISABLED) # start the video conversion process startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW startupinfo.wShowWindow = subprocess.SW_HIDE self.cmdGen.config(audList=self.recorder.devices) command = self.cmdGen.getCvtCmd("ScreenCaptures/" + self.filename) if not self.recorder.error: self.mergeProcess = subprocess.Popen(args=command, startupinfo=startupinfo) # if self.rcchecked.get(): # self.mergeProcess = subprocess.Popen(args= ["ffmpeg","-i",'tmp/tmp.mkv','-i','tmp/tmp.wav','-i','tmp/webcamtmp.mkv','-filter_complex','[2:v] scale=640:-1 [inner]; [0:0][inner] overlay=0:0 [out]',"-shortest",'-map','[out]','-y',"ScreenCaptures/"+self.filename]) # else: # self.mergeProcess = subprocess.Popen(args= ["ffmpeg","-i",'tmp/tmp.mkv','-i','tmp/tmp.wav',"-shortest",'-y',"ScreenCaptures/"+self.filename], startupinfo=startupinfo) # change the screen capture name to something that is not taken os.chdir("ScreenCaptures") while True: matches = 0 for item in os.listdir(): if item == defaultFile: matches += 1 if matches == 0: self.entry1.delete(0, END) self.entry1.insert(END, defaultFile) break else: fileNum += 1 file = self.filename.split(".") defaultFile = file[0].rstrip("1234567890") + str( fileNum) + "." + file[1] os.chdir("../")
class MediumTreeView(Frame): def __init__(self, parent, *args, **kwargs): Frame.__init__(self, parent) self.tree = Treeview(self) self.tree['selectmode'] = "browse" self.tree['columns'] = ('ID', 'Name', 'Gram', 'Include') self.tree['height'] = 30 self.tree['show'] = "headings" self.tree.heading('ID', text="ID") self.tree.heading('Name', text="Name") self.tree.heading('Gram', text="Quantity [mmol]") self.tree.heading('Include', text="Include") self.tree.column('ID', minwidth=0, width=20) self.tree.column('Name', minwidth=100, width=100) self.tree.column('Gram', minwidth=0, width=90) self.tree.column('Include', minwidth=50, width=50) self.tree.bind('<ButtonRelease-1>', self.select_item) self.tree.grid(row=0, column=0, columnspan=4) self.run_object = kwargs.pop('run_object', None) self.medium = None self.medium_volume = None self.uptake_quantities = {} self.species_names = [] self.pie_figure, self.piechart = plt.subplots() self.pie_figure.figsize = (4, 4) self.piechart.pie([0, 0]) self.canvas = FigureCanvasTkAgg(self.pie_figure, master=self) self.canvas.draw() self.canvas.get_tk_widget().grid(row=0, column=4, padx=10) Label(self, text="Quantity:").grid(row=1, column=0) self.edit_entry = FloatEntry(self, initial_value='') self.edit_entry.grid(row=1, column=1, sticky='w') Button(self, text="Save Changes", command=self.save_changes).grid(row=1, column=2, rowspan=2) self.rad_var = IntVar() self.rad_button_exclude = Radiobutton(self, text="No", variable=self.rad_var, value=0) self.rad_button_include = Radiobutton(self, text="Yes", variable=self.rad_var, value=1) self.rad_button_include.grid(row=2, column=1, sticky='w') self.rad_button_exclude.grid(row=2, column=1, sticky='e') Label(self, text="Include:").grid(row=2, column=0) Label(self, text="Medium Name:").grid(row=3, column=0) self.name_entry = StringEntry(self, initial_value="refined_medium") self.name_entry.grid(row=3, column=1, sticky='w') Button(self, text="Test Medium", command=parent.plot).grid(row=4, column=1) Button(self, text="Save Medium", command=lambda: self.save_medium(parent.save)).grid(row=3, column=2) def plot_medium(self, individual, sub_plot): #costruct medium from treeviev if self.medium is not None: components = {} children = self.tree.get_children('') for child in children: child = self.tree.item(child) ID = child['values'][0] quant = float(child['values'][2]) flag = bool(child['values'][3]) if flag: components[ID] = quant medium = Medium.from_dict(components, self.medium_volume) #simulate medium to get the nutrition uptake for each member of the bacterial community individual.plot(True, medium=medium, sub_plot=sub_plot) uptakes = individual.get_uptakes() #calculate the relative uptake quantities self.uptake_quantities = {} for child in children: child_elements = self.tree.item(child) ID = child_elements['values'][0] name = child_elements['values'][1] quant = float(child_elements['values'][2]) flag = child_elements['values'][3] uptake_per_species = [] self.species_names = [] for n, spec in enumerate(uptakes): self.species_names.append(spec) try: uptake = uptakes[spec][ID] except: uptake = 0 try: self.uptake_quantities[ID].append(uptake) except: self.uptake_quantities[ID] = [uptake] for ID in self.uptake_quantities: total = sum(self.uptake_quantities[ID]) if total == 0: self.uptake_quantities[ID] = [ 0 for i in self.species_names ] print(ID) continue relative_quantities = [] for i in self.uptake_quantities[ID]: relative_quantities.append(i / total) self.uptake_quantities[ID] = relative_quantities def add_medium(self, medium, medium_volume): if medium is not None: self.medium = medium self.medium_volume = medium_volume self.update_treeviev() def update_treeviev(self): if self.medium is not None: for i, comp in enumerate(self.medium.get_components()): try: name = SEEDIDs.SEED_to_Names[comp.split("_")[1]] except: name = comp self.tree.insert('', i, comp, values=[ comp, name, self.medium.get_components()[comp], 1, "" ]) def select_item(self, a): try: currItem = self.tree.focus() string_qu = self.tree.item(currItem)['values'][2] include = bool(self.tree.item(currItem)['values'][3]) self.edit_entry.set(string_qu) self.rad_var.set(0 if not include else 1) self.piechart.clear() self.piechart.pie( self.uptake_quantities[self.tree.item(currItem)['values'][0]], labels=self.species_names, labeldistance=None) self.piechart.axis('equal') self.piechart.legend() self.canvas.draw() except: pass def save_changes(self): currItem = self.tree.focus() ID = self.tree.item(currItem)['values'][0] name = self.tree.item(currItem)['values'][1] exclude = 1 if self.rad_var.get() == 1 else 0 uptake = self.tree.item(currItem)['values'][4] self.tree.item( currItem, values=[ID, name, self.edit_entry.get(), exclude, uptake]) def load_medium(self, file): medium = Medium.import_medium(file) self.add_medium(medium) #saves medium to file def save_medium(self, path): if self.medium is not None: file_path = "" for x in path.split("/")[:-1]: file_path = file_path + x + "/" components = {} children = self.tree.get_children('') for child in children: child = self.tree.item(child) ID = child['values'][0] name = child['values'][1] quant = float(child['values'][2]) flag = bool(child['values'][3]) if flag: if quant > 0: components[name] = quant medium = Medium.from_dict(components, self.medium_volume) Medium.export_medium( medium, file_path + "/" + self.name_entry.get() + ".csv")
fr.grid(column=0, row=0, sticky='nsew') states = [ 'active', 'alternate', 'background', 'disabled', 'focus', 'invalid', 'pressed', 'readonly', 'selected' ] # Create rasio buttons which will display widget states state_val = StringVar() for iy, state in enumerate(states): st_rb = Radiobutton(fr, value=state, text=state, variable=state_val, command=change_state) st_rb.grid(column=0, row=iy, padx=5, pady=5, sticky='nw') img1 = PhotoImage("separator", file='../images/piratz/separator.png') img2 = PhotoImage("separator-v", file='../images/piratz/separator-v.png') style = Style() # both theme_create and theme_settings worked style.theme_create( "yummy", parent="clam", settings={ #style.theme_settings('default', { # start of theme extract 'Separator.separator': { "element create": ( 'image',
def __init__(self, root): super().__init__(root) # url ============================ self.url = StringVar() self.url.set(url_use) entry = Entry(self, textvariable=self.url, bg='#666699', fg='#FFFFFF') entry.grid(row=0, column=0, columnspan=4, sticky=W+E) #================================== # 粘贴并打开 self.paste_do = Button(self, text='处理网址', command=self.doit, bg='#cc9933') self.paste_do.grid(row=1, column=0) # 状态 self.status = Label(self, text='待机', fg='blue') self.status.grid(row=1, column=1) # 检查更新 update_bt = Button(self, text='检测新版本', command=self.checkver) update_bt.grid(row=1, column=2) # 使用帮助 help = Button(self, text='使用帮助', command=self.help_bt) help.grid(row=1, column=3) #================================ # 辅助格式 l4 = Label(self, text='辅助格式:') l4.grid(row=2, column=0) self.assist = IntVar() self.assist.set(2) r1 = Radiobutton(self, text='无辅助', variable=self.assist, value=1) r1.grid(row=2, column=1) r2 = Radiobutton(self, text='页码模式', variable=self.assist, value=2) r2.grid(row=2, column=2) self.r3 = Radiobutton(self, text='楼层模式', variable=self.assist, value=3) self.r3.grid(row=2, column=3) # 末页 l2 = Label(self, text='下载页数(-1为到末页):') l2.grid(row=3, column=0, columnspan=2, sticky=E) self.till = StringVar() self.till.set('-1') entry = Entry(self, textvariable=self.till, width=7) entry.grid(row=3, column=2) # 删除文件 delfile = Button(self, text='删输出文件', command=self.delfile, fg='#990000') delfile.grid(row=3, column=3) #==================================== # 输出文件 l3 = Label(self, text='输出文件:') l3.grid(row=4, column=0) self.output = StringVar() self.output.set('auto.txt') self.e_out = Entry(self, textvariable=self.output, width=10) self.e_out.grid(row=4, column=1) # 重命名 self.rename = IntVar() self.rename.set(0) def callCheckbutton(): v = self.rename.get() if v: self.e_out.config(state='disabled') else: self.e_out.config(state='normal') cb = Checkbutton(self, variable=self.rename, text='自动重命名', command=callCheckbutton) cb.grid(row=4, column=2) # 覆盖 self.override = IntVar() self.override.set(0) cb = Checkbutton(self, variable=self.override, text = '覆盖已有文件') cb.grid(row=4, column=3) #==================================== # self self.pack() # fix radiobutton draw self.r3.focus_force() self.paste_do.focus_force()
class Gui(Frame): def __init__(self, root): super().__init__(root) # url ============================ self.url = StringVar() self.url.set(url_use) entry = Entry(self, textvariable=self.url, bg='#666699', fg='#FFFFFF') entry.grid(row=0, column=0, columnspan=4, sticky=W+E) #================================== # 粘贴并打开 self.paste_do = Button(self, text='处理网址', command=self.doit, bg='#cc9933') self.paste_do.grid(row=1, column=0) # 状态 self.status = Label(self, text='待机', fg='blue') self.status.grid(row=1, column=1) # 检查更新 update_bt = Button(self, text='检测新版本', command=self.checkver) update_bt.grid(row=1, column=2) # 使用帮助 help = Button(self, text='使用帮助', command=self.help_bt) help.grid(row=1, column=3) #================================ # 辅助格式 l4 = Label(self, text='辅助格式:') l4.grid(row=2, column=0) self.assist = IntVar() self.assist.set(2) r1 = Radiobutton(self, text='无辅助', variable=self.assist, value=1) r1.grid(row=2, column=1) r2 = Radiobutton(self, text='页码模式', variable=self.assist, value=2) r2.grid(row=2, column=2) self.r3 = Radiobutton(self, text='楼层模式', variable=self.assist, value=3) self.r3.grid(row=2, column=3) # 末页 l2 = Label(self, text='下载页数(-1为到末页):') l2.grid(row=3, column=0, columnspan=2, sticky=E) self.till = StringVar() self.till.set('-1') entry = Entry(self, textvariable=self.till, width=7) entry.grid(row=3, column=2) # 删除文件 delfile = Button(self, text='删输出文件', command=self.delfile, fg='#990000') delfile.grid(row=3, column=3) #==================================== # 输出文件 l3 = Label(self, text='输出文件:') l3.grid(row=4, column=0) self.output = StringVar() self.output.set('auto.txt') self.e_out = Entry(self, textvariable=self.output, width=10) self.e_out.grid(row=4, column=1) # 重命名 self.rename = IntVar() self.rename.set(0) def callCheckbutton(): v = self.rename.get() if v: self.e_out.config(state='disabled') else: self.e_out.config(state='normal') cb = Checkbutton(self, variable=self.rename, text='自动重命名', command=callCheckbutton) cb.grid(row=4, column=2) # 覆盖 self.override = IntVar() self.override.set(0) cb = Checkbutton(self, variable=self.override, text = '覆盖已有文件') cb.grid(row=4, column=3) #==================================== # self self.pack() # fix radiobutton draw self.r3.focus_force() self.paste_do.focus_force() def doit(self): # 获取、显示网址 try: u = self.master.clipboard_get().strip() except: bad = True u = '' else: bad = False if bad or not tz2txt.is_url(u): self.url.set('无效网址,网址须以http://或https://开头。') return self.url.set(u) # 辅助模式 assist = self.assist.get() if assist == 1: label = '' elif assist == 2: label = 'page' elif assist == 3: label = 'floor' # 末页 till = self.till.get().strip() try: till = int(till) except: till = -1 # 执行命令 self.status['fg'] = '#993300' self.status['text'] = '处理中' self.update() # except里return try: output, discard_output, title, info_list, chinese_ct = \ tz2txt.auto(u, till, '', '', label, from_gui=True) if title == None: raise Exception('无法完成全自动处理') except Exception as e: print('\n出现异常:', e) print('===================================\n') return else: # 显示标题 title = red.sub(r'[\U00010000-\U0010FFFF]', r'', title) title = title.strip() self.url.set(title) finally: self.status['fg'] = 'blue' self.status['text'] = '待机' # 输出文件名 if self.rename.get(): output_fn = title + '.txt' else: output_fn = self.output.get().strip() # 合法文件名 output_fn = red.sub(r'[\\/:*?"<>|]', r'', output_fn) if output_fn == '.txt': output_fn = '楼主.txt' # 输出内容 text = output.getvalue() output.close() # 覆盖判断:文件已存在 and 输出有内容 and (强制覆盖 or 选择覆盖) if os.path.isfile(output_fn) and \ text and \ (self.override.get() == 1 or \ messagebox.askyesno('输出文件已存在', '是否覆盖?\n%s' % output_fn) ): # 删除已有目标 try: os.remove(output_fn) except: pass # 写入output if not os.path.isfile(output_fn) and text: try: with open(output_fn, 'w', encoding='gb18030', errors='replace') as f: f.write(text) print('\n已保存为:', output_fn) except Exception as e: print('\n保存文件时出现异常', e) # 显示信息 size2 = os.path.getsize(output_fn) size2 = format(size2, ',') chinese_ct = format(chinese_ct, ',') print('输出文件 {0} 字节,约 {1} 个汉字。'.format( size2, chinese_ct) ) # 写入discard if discard_output != None: try: text = discard_output.getvalue() discard_output.close() if text: with open(discard_fn, 'w', encoding='gb18030', errors='replace') as f: f.write(text) except Exception as e: print('\n保存文件时出现异常', e) print() for line in info_list: if line.startswith('下载时间:'): break datamachine.save_print(line.rstrip('\n')) print('===================================\n') def delfile(self): try: output = self.output.get().strip() os.remove(output) except: pass else: print('已删除输出文件') try: os.remove(discard_fn) except: pass else: print('已删除丢弃文件') self.url.set(url_use) def checkver(self): self.status['fg'] = '#993300' self.status['text'] = '处理中' self.update() print('当前版本:', tz2txt.tz2txt_date) try: newver, download_url = checkver.check() except Exception as e: print('出现异常:', e) else: if newver > tz2txt.tz2txt_date: print('发现新版本:', newver) if messagebox.askyesno('发现新版本', '最新版本:%s\n是否用浏览器打开下载网址?' % newver): try: webbrowser.open_new_tab(download_url) except: print('无法用浏览器打开下载网址:', download_url) elif newver != tz2txt.tz2txt_date: print('当前版本比网盘版本(%s)新' % newver) else: print('检查完毕,没有发现新版本') print() self.status['fg'] = 'blue' self.status['text'] = '待机' def help_bt(self): url = 'http://www.cnblogs.com/animalize/p/4770397.html' try: webbrowser.open_new_tab(url) except: print('无法用浏览器打开使用帮助,网址:', url)
def __init__(self, master): super(HostFrame, self).__init__(master) self.root = master # get any previous data on last.json previous_data = read_write.read_last() # Three frames will hold the widgets label_frm = Frame(self) # this will hold the labels label_frm.grid(row=0, pady=10, padx=50) button_frm = Frame(self) # this will hold the buttons button_frm.grid(row=1, pady=5, padx=50) self.hosts_frm = Frame(self) # this will hold the previous hosts self.hosts_frm.grid(row=2, pady=5, padx=50) self.hosts_frm.grid_remove( ) # but we need to show it, only if user wants # Build the widgets for label_frm Label(label_frm, text="Host:").grid(column=2, row=0, pady=10, padx=5) Label(label_frm, text="Port:").grid(column=2, row=1, padx=5) self.host_entry = Entry(label_frm, width=30) self.host_entry.grid(column=3, row=0, pady=10) self.port_entry = Entry(label_frm, width=30) self.port_entry.grid(column=3, row=1) # Add data to entries if any data on last.json try: if previous_data["host"] is not "": self.host_entry.insert(0, previous_data["host"]) self.port_entry.insert(0, previous_data["port"]) except KeyError as e: message = "[ERROR] (frames.HostFrame): KeyError: " + str(e) read_write.log_message(message) # Build the widgets for button_frm self.next_btn = Button(button_frm, text="Next") self.next_btn.grid(column=2, row=0, pady=10, padx=4, ipadx=2, ipady=2) self.exit_btn = Button(button_frm, text="Exit", command=self.root.destroy) self.exit_btn.grid(column=4, row=0, pady=10, padx=4, ipadx=2, ipady=2) self.show_previous_btn = Button(button_frm, text="Show previous hosts", command=self.show_hosts) self.show_previous_btn.grid(column=2, row=1, columnspan=3, ipadx=2, ipady=2) # Build the widgets for hosts_frm def select_host(): selected_data = str(var.get()).split(":") self.host_entry.delete(0, "end") self.host_entry.insert(0, selected_data[0]) self.port_entry.delete(0, "end") self.port_entry.insert(0, selected_data[1]) # populate the hosts_frm with Radio-buttons that show previous connections data = read_write.read_mongo() var = StringVar() counter = 0 # this will show in which row each radio-button will be on the frame for json_object in data: if json_object["host"] is not "": option = json_object["host"] + ":" + str( json_object["port"]) # format host:port r = Radiobutton(self.hosts_frm, text=option, variable=var, value=option, command=select_host) r.grid(row=counter, column=2, pady=2) counter += 1
year = combo.get() combo.bind("<<ComboboxSelected>>", combo_fun) # Меню выбора Периода periods = {0: 'Год', 1: '1-ый квартал', 2: '2-ой квартал', 3: '3-ий квартал'} label_periods = Label(root) label_periods.config(text="Отчетные периоды: ", fg='black') label_periods.grid(column=1, row=label_periods_row, sticky=W) # выбора периода var = IntVar() var.set(1) # значение по умолчанию period = var.get() R1 = Radiobutton(root, text=periods[1], variable=var, value=1, command=sel) R1.grid(column=1, row=R1_row, sticky=W) R2 = Radiobutton(root, text=periods[2], variable=var, value=2, command=sel) R2.grid(column=1, row=R1_row + 1, sticky=W) R3 = Radiobutton(root, text=periods[3], variable=var, value=3, command=sel) R3.grid(column=1, row=R1_row + 2, sticky=W) R4 = Radiobutton(root, text=periods[0], variable=var, value=0, command=sel) R4.grid(column=1, row=R1_row + 3, sticky=W) # Метка выбора периода label0 = Label(root) label0.grid(column=1, row=label0_row, sticky=W) # Метка выбранного периода label1 = Label(root) label1.grid(column=2, row=label0_row, sticky=W) # Метка выбранного Года label_year_2 = Label(root)
class Page1(Frame): def __init__(self, master): Frame.__init__(self, master) self.style = Style() self.time_frame = LabelFrame(self, text='Time Setting') self.hour_label = Label(self.time_frame, text='Hours') self.hour_box = Spinbox(self.time_frame, from_=0, to=24) self.minute_label = Label(self.time_frame, text='Minutes') self.minute_box = Spinbox(self.time_frame, from_=0, to=60) self.second_label = Label(self.time_frame, text='Seconds') self.second_box = Spinbox(self.time_frame, from_=0, to=60) self.break_label = Label(self.time_frame, text='Time During Sessions') self.break_var = IntVar() self.break_var.set(4) self.break_radio_button_3 = Radiobutton(self.time_frame, text='3 min', variable=self.break_var, value=3) self.break_radio_button_4 = Radiobutton(self.time_frame, text='4 min', variable=self.break_var, value=4) self.break_radio_button_5 = Radiobutton(self.time_frame, text='5 min', variable=self.break_var, value=5) self.break_radio_button_6 = Radiobutton(self.time_frame, text='6 min', variable=self.break_var, value=6) self.break_radio_button_7 = Radiobutton(self.time_frame, text='7 min', variable=self.break_var, value=7) self.name_label = Label(self.time_frame, text='Task Name') self.name_entry = Entry(self.time_frame) self.reminder_label = Label(self.time_frame, text='Reminder') self.reminder_entry = Entry(self.time_frame) self.generate_button = Button(self, text='Generate Task', command=self.create_task) self.save_button = Button(self, text='Save Configuration', command=self.save_config) self.load_button = Button(self, text='Load Configuration', command=self.load_config) self.clear_button = Button(self, text='Clear', command=self.clear) # GRIDDING OPERATIONS self.hour_label.grid(row=1, column=0) self.hour_box.grid(row=1, column=1) self.minute_label.grid(row=1, column=2) self.minute_box.grid(row=1, column=3) self.second_label.grid(row=1, column=4) self.second_box.grid(row=1, column=5) self.break_label.grid(row=2, column=0) self.break_radio_button_3.grid(row=2, column=1) self.break_radio_button_4.grid(row=2, column=2) self.break_radio_button_5.grid(row=2, column=3) self.break_radio_button_6.grid(row=2, column=4) self.break_radio_button_7.grid(row=2, column=5) self.name_label.grid(row=3, column=0) self.name_entry.grid(row=3, column=1, columnspan=5, sticky='ew') self.reminder_label.grid(row=4, column=0) self.reminder_entry.grid(row=4, column=1, columnspan=5, sticky='ew') self.generate_button.grid(row=1, column=0, sticky='snew') self.save_button.grid(row=2, column=0, sticky='snew') self.load_button.grid(row=3, column=0, sticky='snew') self.clear_button.grid(row=4, column=0, sticky='snew') self.time_frame.grid(row=0, column=0) self.grid(row=0, column=0) def create_task(self): # Task signature: (task_name, task_duration, break_duration, task_reminder=None) hours = self.hour_box.get() minutes = self.minute_box.get() seconds = self.second_box.get() break_time = self.break_var.get() if hours and seconds and minutes: total_time = int(hours) * 3600 + int(minutes) * 60 + int(seconds) return Task(self.name_entry.get(), total_time, break_time) elif hours == 's': return Task('sample task', 5, 3 / 60) def save_config(self): with open('config.pickle', 'wb+') as config: pickle.dump(self.create_task(), config) def load_config(self): with open('config.pickle', 'rb') as config: unpickled_task = pickle.load(config) Task.tasks.append(unpickled_task) def clear(self): self.name_entry.delete(0, 'end') self.reminder_entry.delete(0, 'end') self.hour_box.set('') self.minute_box.set('') self.second_box.set('')
style = Style() # both theme_create and theme_settings worked style.theme_create( "yummy", parent="clam", settings={ #style.theme_settings('default', { # start of theme extract 'Radiobutton.indicator': { "element create": ('image', "radio-n", ('disabled', 'selected', "radio-ds"), ('disabled', "radio-d"), ('selected', "radio-s"), { 'width': 20, 'sticky': "w" }) } # end of theme extract - don't forget to add comma at end when inserting }) style.theme_use('yummy') # 'default' happy = ['Great', 'Good', 'OK', 'Poor', 'Awful'] happiness = StringVar() for ix, s in enumerate(happy): widg = Radiobutton(fr, text=s, value=s, variable=happiness) widg.grid(column=0, row=11 + ix, sticky='nw') run_state(fr, widg) root.mainloop()
class MarkovDemo(Frame): "MarkovDemo(master=None, **kw) -> MarkovDemo instance" TEXT = dict(height=2, width=46, wrap=WORD) # Text Options GRID = dict(padx=5, pady=5) # Grid Options # Initialize a MarkovDemo instance with a GUI for interaction. def __init__(self, master=None, **kw): "Initialize the MarkovDemo instance's widgets and settings." super().__init__(master, **kw) self.build_widgets() self.place_widgets() self.setup_widgets() self.grid_rowconfigure(2, weight=1) self.grid_rowconfigure(3, weight=1) self.grid_columnconfigure(0, weight=1) self.key = self.primer = None def build_widgets(self): "Build the various widgets that will be used in the program." # Create processing frame widgets. self.processing_frame = LabelFrame(self, text='Processing Mode:') self.mode_var = StringVar(self, 'encode') self.decode_button = Radiobutton(self.processing_frame, text='Decode Cipher-Text', command=self.handle_radiobuttons, value='decode', variable=self.mode_var) self.encode_button = Radiobutton(self.processing_frame, text='Encode Plain-Text', command=self.handle_radiobuttons, value='encode', variable=self.mode_var) self.freeze_var = BooleanVar(self, False) self.freeze_button = Checkbutton(self.processing_frame, text='Freeze Key & Primer', command=self.handle_checkbutton, offvalue=False, onvalue=True, variable=self.freeze_var) # Create encoding frame widgets. self.encoding_frame = LabelFrame(self, text='Encoding Options:') self.chain_size_label = Label(self.encoding_frame, text='Chain Size:') self.chain_size_entry = Entry(self.encoding_frame) self.plain_text_label = Label(self.encoding_frame, text='Plain-Text:') self.plain_text_entry = Entry(self.encoding_frame) # Create input frame widgets. self.input_frame = LabelFrame(self, text='Input Area:') self.input_text = ScrolledText(self.input_frame, **self.TEXT) # Create output frame widgets. self.output_frame = LabelFrame(self, text='Output Area:') self.output_text = ScrolledText(self.output_frame, **self.TEXT) def place_widgets(self): "Place the widgets where they belong in the MarkovDemo frame." # Locate processing frame widgets. self.processing_frame.grid(sticky=EW, **self.GRID) self.decode_button.grid(row=0, column=0, **self.GRID) self.encode_button.grid(row=0, column=1, **self.GRID) self.freeze_button.grid(row=0, column=2, **self.GRID) # Locate encoding frame widgets. self.encoding_frame.grid(sticky=EW, **self.GRID) self.chain_size_label.grid(row=0, column=0, sticky=W, **self.GRID) self.chain_size_entry.grid(row=0, column=1, sticky=EW, **self.GRID) self.plain_text_label.grid(row=1, column=0, sticky=W, **self.GRID) self.plain_text_entry.grid(row=1, column=1, sticky=EW, **self.GRID) self.encoding_frame.grid_columnconfigure(1, weight=1) # Locate input frame widgets. self.input_frame.grid(sticky=NSEW, **self.GRID) self.input_text.grid(sticky=NSEW, **self.GRID) self.input_frame.grid_rowconfigure(0, weight=1) self.input_frame.grid_columnconfigure(0, weight=1) # Locate output frame widgets. self.output_frame.grid(sticky=NSEW, **self.GRID) self.output_text.grid(sticky=NSEW, **self.GRID) self.output_frame.grid_rowconfigure(0, weight=1) self.output_frame.grid_columnconfigure(0, weight=1) def setup_widgets(self): "Setup each widget's configuration for the events they handle." self.input_text.bind('<Key>', self.handle_key_events) self.input_text.bind('<Control-Key-a>', self.handle_control_a) self.input_text.bind('<Control-Key-/>', lambda event: 'break') self.output_text['state'] = DISABLED self.output_text.bind('<Control-Key-a>', self.handle_control_a) self.output_text.bind('<Control-Key-/>', lambda event: 'break') ######################################################################## # Take care of any special event needing dedicated processing. def handle_radiobuttons(self): "Change the interface based on the encoding / decoding setting." if self.encrypting: self.freeze_button.grid() if not self.freeze_var.get(): self.encoding_frame.grid() else: self.freeze_button.grid_remove() if not self.freeze_var.get(): self.encoding_frame.grid_remove() self.handle_key_events(None) def handle_checkbutton(self): "Change the interface based on the key / primer freeze setting." if self.freeze_var.get(): self.encoding_frame.grid_remove() else: self.encoding_frame.grid() def handle_key_events(self, event): "Schedule refreshing the output area after an input area event." if event is None or event.char and event.state | 0o11 == 0o11: self.after_idle(self.refresh) @staticmethod def handle_control_a(event): "Select all text in the widget associated with the given event." event.widget.tag_add(SEL, 1.0, END + '-1c') return 'break' ######################################################################## # Handle interface's updates when either encoding or decoding. def refresh(self): "Refresh the output based on the value of the input." text = self.input_text.get(1.0, END + '-1c') if not text: self.output = text elif self.encrypting: self.encode(text) else: self.decode(text) def output(self, value): "Set the text in the output area to the string value." self.output_text['state'] = NORMAL self.output_text.delete(1.0, END) self.output_text.insert(END, value) if self.encrypting and self.freeze_var.get(): self.output_text.see(END) self.output_text['state'] = DISABLED output = property(fset=output, doc='Output area property.') @property def chain_size(self): "Chain size for the Markov chains used when encrypting." try: value = ast.literal_eval(self.chain_size_entry.get()) assert isinstance(value, int) and 2 <= value <= 256 return value except: self.chain_size_entry.delete(0, END) self.chain_size_entry.insert(0, '2') return 2 @property def plain_text(self): "Plain text or ignored characters in encryption process." try: value = self.repr_to_obj(self.plain_text_entry.get(), '') assert isinstance(value, str) return value except: self.plain_text_entry.delete(0, END) return '' ######################################################################## # Encrypt a string for display in the interface's output area. def encode(self, string): "Encode the string and show the cipher-text in the output." try: cipher = self.build_cipher(string) except ValueError: self.output = '' except: self.output = traceback.format_exc() else: self.output = self.build_header() + '\n\n' + cipher def build_cipher(self, string): "Build cipher-text based on plain-text and return answer." if self.key and self.freeze_var.get(): cipher, primer = me.encrypt_str(string, self.key, self.primer) else: args = string, self.chain_size, self.plain_text cipher, self.key, self.primer = me.auto_encrypt_str(*args) return cipher def build_header(self): "Build header from key and primer values in current use." header = '\n'.join(map(self.bytes_to_repr, self.key.data)) header += '\n' + self.bytes_to_repr(self.primer.data) return header ######################################################################## # Decrypt a string for display in the interface's output area. def decode(self, string): "Decode encrypted message and display plain-text in output." try: cipher = self.extract_keys(string) text = self.extract_text(cipher) except ValueError: self.output = '' except: self.output = traceback.format_exc() else: self.output = text def extract_keys(self, string): "Extract keys to decryption and return the cipher-text area." header, cipher = string.split('\n\n', 1) *key, primer = map(self.repr_to_obj, header.split('\n')) self.key, self.primer = me.Key(tuple(key)), me.Primer(primer) return cipher def extract_text(self, string): "Extract text message from string using built key and primer." text, primer = me.decrypt_str(string, self.key, self.primer) return text ######################################################################## # Provide some special methods to simplify the program's code. @property def encrypting(self): "Encrypting boolean stating current operations mode." return {'encode': True, 'decode': False}[self.mode_var.get()] @staticmethod def bytes_to_repr(obj): "Convert bytes object into suitable representation." if not isinstance(obj, bytes): raise TypeError('Object must be a bytes instance!') return repr(obj)[2:-1] @staticmethod def repr_to_obj(string, prefix='b'): "Convert representation into an equivalent object." for template in '{}"{}"', "{}'{}'": try: return ast.literal_eval(template.format(prefix, string)) except: pass raise ValueError('Cannot convert {!r} to object!'.format(string)) @classmethod def main(cls): "Create context for demo and run a test instance." NoDefaultRoot() root = Tk() root.minsize(420, 330) root.title('Markov Demo 2') test = cls(root) test.grid(sticky=NSEW) root.grid_rowconfigure(0, weight=1) root.grid_columnconfigure(0, weight=1) root.mainloop()
def __init__(self, kernel, master=None): Frame.__init__(self, master) self.kernel = kernel self.grid() self.master.title("YuMi experiment") self.client_tuple = None self.master.protocol("WM_DELETE_WINDOW", self.kernel.close_setup) #self.master.geometry("100x100+500+100") config = self.kernel.read_config() frame_session_type = Frame(self.master, relief=GROOVE, borderwidth=2) frame_participant = Frame(self.master, relief=GROOVE, borderwidth=2) frame_data_bases = Frame(self.master, relief=GROOVE, borderwidth=2) frame_server = Frame(self.master, relief=GROOVE, borderwidth=2) # Session type self.rbType = StringVar(self.master) lbl1 = Label(frame_session_type, text="Session type") rb1 = Radiobutton(frame_session_type, text="Hololens", variable=self.rbType, value="hololens", command=self.type) rb2 = Radiobutton(frame_session_type, text="Monitor", variable=self.rbType, value="monitor", command=self.type) rb3 = Radiobutton(frame_session_type, text="Dialogue", variable=self.rbType, value="dialogue", command=self.type) rb4 = Radiobutton(frame_session_type, text="Projector", variable=self.rbType, value="projector", command=self.type) self.rbType.set("hololens") rb1.select() rb2.deselect() rb3.deselect() rb4.deselect() lbl1.grid(row=0, column=0, sticky=W+N) rb1.grid(row=1, column=0, sticky=W+N) rb2.grid(row=2, column=0, sticky=W+N) rb3.grid(row=3, column=0, sticky=W+N) rb4.grid(row=4, column=0, sticky=W+N) # Data base self.data_base_path = config["data_base_path"] try: listdir(self.data_base_path) except FileNotFoundError: self.data_base_path = dirname(__file__) data_files = [f for f in listdir(self.data_base_path) if isfile(join(self.data_base_path, f))] data_files = [files for files in data_files if ".csv" in files] self.data_file = StringVar(master) if len(data_files) == 0: data_files.append("No data found") self.data_file.set(data_files[0]) lbl2 = Label(frame_data_bases, text="Data base") btn_browse = Button(frame_data_bases, text="Browse", command=self.kernel.browse_db) self.db_drop = OptionMenu(frame_data_bases, self.data_file, *data_files, command=self.kernel.set_db) self.data_base_file = join(self.data_base_path, self.data_file.get()) lbl_db1 = Label(frame_data_bases, text="Found in:") lbl_db2 = Label(frame_data_bases, text="Choose:") lbl_text = self.data_base_path if len(lbl_text) > 30: lbl_text = "..." + lbl_text[-30:] self.lbl_db3 = Label(frame_data_bases, text=lbl_text) lbl2.grid(row=0, column=0, columnspan=1, sticky=W+N) lbl_db2.grid(row=1, column=0, columnspan=1, sticky=W+N) self.db_drop.grid(row=1, column=1, columnspan=3, sticky=E+N) lbl_db1.grid(row=2, column=0, columnspan=1, sticky=W+N) self.lbl_db3.grid(row=2, column=1, columnspan=3, sticky=W+N) btn_browse.grid(row=3, column=3, sticky=E+N) # Participant self.write_to_path = config["write_to_path"] try: listdir(self.write_to_path) except FileNotFoundError: self.write_to_path = dirname(__file__) part_dirs = [f for f in listdir(self.write_to_path) if isdir(join(self.write_to_path, f))] part_dirs = [dirs for dirs in part_dirs if "participant" in dirs] parts = [" ".join(part.split("_")[0:2]) for part in part_dirs] self.participant = StringVar() self.participant.set("New participant") # default value parts = [self.participant.get()] + parts lbl_part = Label(frame_participant, text="Name:") self.part_entry = Entry(frame_participant, textvariable=self.participant) lbl3 = Label(frame_participant, text="Participant") lbl_text = self.write_to_path if len(lbl_text) > 10: lbl_text = "..." + lbl_text[-10:] self.lbl4 = Label(frame_participant, text=lbl_text) lbl5 = Label(frame_participant, text="Save to:") self.dropdown_participant = OptionMenu(frame_participant, self.participant, *parts) btn_browse2 = Button(frame_participant, text="Browse", command=self.kernel.browse_part) lbl_part.grid(row=1, column=0, sticky=W+N) self.part_entry.grid(row=1, column=1, sticky=W+N) lbl3.grid(row=0, column=0, sticky=W+N) self.dropdown_participant.grid(row=2, column=1, columnspan=2, sticky=W+N+E) lbl5.grid(row=3, column=0, columnspan=1, sticky=W+N) self.lbl4.grid(row=3, column=1, sticky=W+N) btn_browse2.grid(row=4, column=1, sticky=E+N) # Server self.addr = StringVar(master) self.addrs = config["server_adrs"].split(";") self.addr.set(self.addrs[0]) self.port = StringVar(master) self.ports = config["server_ports"].split(";") self.port.set(self.ports[0]) lbl6 = Label(frame_server, text="Connect to server") lbl7 = Label(frame_server, text="Server address:") lbl8 = Label(frame_server, text="Server port:") self.rbServer1 = StringVar(self.master) rb4 = Radiobutton(frame_server, text="", variable=self.rbServer1, value="entry", command=self.server1) rb5 = Radiobutton(frame_server, text="", variable=self.rbServer1, value="list", command=self.server1) self.rbServer1.set("entry") rb4.select() rb5.deselect() self.adr_entry = Entry(frame_server, textvariable=self.addr) self.adr_drop = OptionMenu(frame_server, self.addr, *self.addrs) self.adr_drop['state'] = 'disabled' self.rbServer2 = StringVar(self.master) rb6 = Radiobutton(frame_server, text="", variable=self.rbServer2, value="entry", command=self.server2) rb7 = Radiobutton(frame_server, text="", variable=self.rbServer2, value="list", command=self.server2) rb6.select() rb7.deselect() self.rbServer2.set("entry") self.port_entry = Entry(frame_server, textvariable=self.port) self.port_drop = OptionMenu(frame_server, self.port, *self.ports) self.port_drop['state'] = 'disabled' lbl8 = Label(frame_server, text="Status:") lbl_text = "Not connected" if self.kernel.client_tuple: lbl_text = "Connected to {}".format(self.kernel.client_tuple[0].host) self.lbl9 = Label(frame_server, text=lbl_text) btn_connect = Button(frame_server, text="Connect", command=self.kernel.connect) lbl6.grid(row=0, column=0, sticky=W+E+N+S) lbl7.grid(row=1, column=0, rowspan=2, sticky=W) rb4.grid(row=1, column=2, columnspan=1, rowspan=1, sticky=W) self.adr_entry.grid(row=1, column=3, columnspan=1, rowspan=1, sticky=W+E+N+S) rb5.grid(row=2, column=2, columnspan=1, rowspan=1, sticky=W) self.adr_drop.grid(row=2, column=3, columnspan=1, rowspan=1, sticky=W+E+N+S) lbl8.grid(row=3, column=0, rowspan=2, sticky=W) rb6.grid(row=3, column=2, columnspan=1, rowspan=1, sticky=W) self.port_entry.grid(row=3, column=3, columnspan=1, rowspan=1, sticky=W+E+N+S) rb7.grid(row=4, column=2, columnspan=1, rowspan=1, sticky=W) self.port_drop.grid(row=4, column=3, columnspan=1, rowspan=1, sticky=W+E+N+S) lbl8.grid(row=5, column=0, columnspan=1, rowspan=1, sticky=W) self.lbl9.grid(row=5, column=3, columnspan=1, rowspan=1, sticky=W) btn_connect.grid(row=6, column=3, columnspan=1, rowspan=1, sticky=W) # Layout btn_launch = Button(self.master, text="Launch", command=self.kernel.launch) frame_session_type.grid(row=0,column=0, columnspan=1, rowspan=1, sticky=W+E+N+S) frame_data_bases.grid(row=1, column=1, columnspan=1, rowspan=1, sticky=W+E+N+S) frame_participant.grid(row=1, column=0, columnspan=1, rowspan=1, sticky=W+E+N+S) frame_server.grid(row=0, column=1, columnspan=1, rowspan=1, sticky=W+E+N+S) btn_launch.grid(row=2, column=1, sticky=E)
def no_clicked(): """ If the category is not defined correctly """ choose = tk.Toplevel(window) program_message = tk.Label(choose, text='Вкажіть, до якої категорії належить звернення,' '\n та ми продовжимо навчання моделі') var = tk.IntVar() var.set(0) category0 = Radiobutton(choose, text='Позитивний відгук', variable=var, value=0) category1 = Radiobutton(choose, text='Негативний відгук', variable=var, value=1) category2 = Radiobutton(choose, text='Звернення на внутрішній департамент', variable=var, value=2) category3 = Radiobutton(choose, text='Хуліганське звернення', variable=var, value=3) category4 = Radiobutton(choose, text='Пропозиція щодо вдосконалення роботи', variable=var, value=4) category5 = Radiobutton(choose, text='Звернення стосовно сайту купівлі монет', variable=var, value=5) text = user_message.get('1.0', 'end-1c') def learn(): """ Continues model training on the entered message """ messagebox.showinfo(message='Дякуємо за звернення!') window.destroy() if var.get() == 0: category = 'Positive' elif var.get() == 1: category = 'Negative' elif var.get() == 2: category = 'Hotline' elif var.get() == 3: category = 'Hooligan' elif var.get() == 4: category = 'Offer' elif var.get() == 5: category = 'SiteAndCoins' text_list = list() for x in range(6): text_list.append(text) model = load_model('../model/save/model(our test data).h5') df = pd.DataFrame({'text': text_list}) X_train = df.text cat = '../data/category_with_received_data.csv' all = pd.read_csv(cat) cat = tc.CleanText.clean_category(all) descriptions = tc.CleanText.prepare_text(all).description maxSequenceLength, vocab_size, encoder, num_classes = tp.PrepareText.parameters(cat) tokenizer = Tokenizer(num_words=vocab_size) tokenizer.fit_on_texts(descriptions) X_train = tokenizer.texts_to_sequences(X_train) X_train = sequence.pad_sequences(X_train, maxlen=maxSequenceLength) cat = '../data/category_with_received_data.csv' with open(cat, 'a') as f: f.write('"{}",{}\n'.format(text, category)) # y_train = keras.utils.to_categorical(y_train, num_classes) dict_changes = { 'Positive': np.array([1., 0., 0., 0., 0., 0.]), 'Negative': np.array([0., 1., 0., 0., 0., 0.]), 'Hotline': np.array([0., 0., 1., 0., 0., 0.]), 'Hooligan': np.array([0., 0., 0., 1., 0., 0.]), 'Offer': np.array([0., 0., 0., 0., 1., 0.]), 'SiteAndCoins': np.array([0., 0., 0., 0., 0., 1.]), } y_train = [] for x in range(6): y_train.append(dict_changes[category]) model.fit(X_train, np.array(y_train), batch_size=1, epochs=1) choose_button = tk.Button(choose, text='Підтвердити', command=learn) program_message.grid() category0.grid() category1.grid() category2.grid() category3.grid() category4.grid() category5.grid() choose_button.grid() choose.mainloop()
from tkinter import * from tkinter.ttk import Radiobutton window = Tk() window.geometry('200x200') selected = IntVar() rad1 = Radiobutton(window,text='First', value=1, variable=selected) rad2 = Radiobutton(window,text='Second', value=2, variable=selected) rad3 = Radiobutton(window,text='Third', value=3, variable=selected) rad1.grid(column=0, row=0) rad2.grid(column=1, row=0) rad3.grid(column=2, row=0) button = Button(window, text="Click me!", command=lambda: print(selected.get())) button.grid(row=1, column=0) window.mainloop()
from tkinter import * from tkinter.ttk import Radiobutton def clicked(): lbl.configure(text=selected.get()) window = Tk() window.title("Example1") window.geometry("500x300") selected = IntVar() rd1 = Radiobutton(window, text="Первый", value=1, variable=selected) rd2 = Radiobutton(window, text="Второй", value=7, variable=selected) rd3 = Radiobutton(window, text="Третий", value=8, variable=selected) rd1.grid(column=0, row=0) rd2.grid(column=1, row=0) rd3.grid(column=2, row=0) btn = Button(window, text="OK", command=clicked) btn.grid(column=3, row=0) lbl = Label(window) lbl.grid(column=0, row=1) window.mainloop()
def step_2(): def clicked(): lbl.configure(text=selected.get()) var= selected.get() step=2 counter_click(step,var) selected = IntVar() rad1 = Radiobutton(root,text='Брест', value=1, variable=selected) rad2 = Radiobutton(root,text='Урбаны', value=2, variable=selected) rad3 = Radiobutton(root,text='Брузги', value=3, variable=selected) rad4 = Radiobutton(root,text='Котловка', value=4, variable=selected) rad5 = Radiobutton(root,text='Бригоровщина', value=5, variable=selected) btn2 = Button(root, text="Далее", command=lambda: [clicked(), btn1.grid_remove(), btn2.grid_remove(), btn3.grid_remove(), rad1.grid_remove(), rad2.grid_remove(),btn2.grid_remove(), rad3.grid_remove(), rad4.grid_remove(), rad5.grid_remove(),lbl1.grid_remove(), lbl4.grid_remove(),lbl2.grid_remove(),lbl3.grid_remove(),lblT.grid_remove()]) btn1 = Button(root, text="Назад", command=lambda: [step_1(), btn2.grid_remove(), btn1.grid_remove(),btn2.grid_remove(), rad1.grid_remove(), rad2.grid_remove(), rad3.grid_remove(), rad4.grid_remove(), rad5.grid_remove(),lbl1.grid_remove(),lbl4.grid_remove(), lbl2.grid_remove(),lbl3.grid_remove(),lblT.grid_remove()]) btn3 = Button(root, text="Войти в систему", command=lambda: [step_log(), btn2.grid_remove(), btn1.grid_remove(), btn3.grid_remove(), rad1.grid_remove(), rad2.grid_remove(), rad3.grid_remove(), rad4.grid_remove(), rad5.grid_remove(),lbl1.grid_remove(),lbl4.grid_remove(), lblT.grid_remove(), lbl2.grid_remove(),lbl3.grid_remove()]) lbl = Label(root) x=1 y=1 rad1.grid(column=x+1, row=y+1, sticky="W") rad2.grid(column=x+1, row=y+2, sticky="W") rad3.grid(column=x+1, row=y+3, sticky="W") rad4.grid(column=x+1, row=y+4, sticky="W") rad5.grid(column=x+1, row=y+5, sticky="W") btn1.grid(column=x+0, row=y+7, sticky="W") btn2.grid(column=x+3, row=y+7, sticky="W") btn3.grid(column=0, row=0, sticky="N") lbl1 = tk.Label(root, text = '') lbl2 = tk.Label(root, text = 'ТЕСТ', font=("Arial Bold", 15)) lbl3 = tk.Label(root, text = '') lbl4 = tk.Label(root, text = '') lblT = tk.Label(root, text = 'Выберите точку возврата ', font=("Arial Bold", 14)) lbl1.grid(column=5, row=0, pady=0,padx=70) lbl2.grid(column=2, row=0, pady=10,padx=0) lbl3.grid(column=2, row=7, pady=0,padx=0) lbl4.grid(column=2, row=8, pady=0,padx=70) lblT.grid(column=2, row=1, pady=15,padx=0,columnspan=4) root.update()
def clicked_stocks(): messagebox.showinfo('Акции', 'Вы выбрали акции') def clicked_founds(): messagebox.showinfo('Фонды', 'Вы выбрали фонды') window = Tk() window.title("Мой инвестиционный портфель 1.0 (release 01.12.2020)") window.geometry('270x30') menu = Menu(window) new_item = Menu(menu, tearoff=0) new_item.add_command(label='Новый') new_item.add_separator() new_item.add_command(label='Параметры констант', command=par) menu.add_cascade(label='Файл', menu=new_item) window.config(menu=menu) Bonds = Radiobutton(window, text='Облигация', value=1, command=clicked_bonds) Stocks = Radiobutton(window, text='Акция', value=2, command=clicked_stocks) Founds = Radiobutton(window, text='ETF/ПИФ (Фонды)', value=3, command=clicked_founds) Bonds.grid(column=0, row=0) Stocks.grid(column=2, row=0) Founds.grid(column=4, row=0) window.mainloop()
class settingsWin(Toplevel): def __init__(self, parent, sourceCmdGen, audioRec): Toplevel.__init__(self, parent) #self.transient(parent) self.cmdGen = sourceCmdGen self.audioRec = audioRec self.title(string="Screen Recorder - Settings") self.iconbitmap("icon.ico") self.resizable(width=False, height=False) self.minsize(400, 450) self.columnconfigure(0, weight=1) self.rowconfigure(0, weight=1) self.notebook = Notebook(self) self.notebook.grid(row=0, column=0, columnspan=4, sticky="nesw", padx=5, pady=5) ########################################### VIDEO OPTIONS ############################################## self.videoOptions = Frame(self) self.videoOptions.columnconfigure(1, weight=1) Label(self.videoOptions, text="Suggested FPS (Not guaranteed): ").grid(row=0, column=0) self.FPSVar = StringVar() self.FPSspin = Spinbox(self.videoOptions, from_=1, to=120, textvariable=self.FPSVar) self.FPSspin.grid(row=0, column=1, sticky="ew", pady=5) self.FPSVar.set(self.cmdGen.fps) self.hwaccVar = StringVar() Label( self.videoOptions, text= "Encoding (GPU encoding may improve perfomance, but also may result in corrupted files):" ).grid(row=1, column=0, columnspan=2, sticky="w") self.buttonCPU = Radiobutton(self.videoOptions, text="CPU-only encoder", variable=self.hwaccVar, value="CPU") self.buttonCPU.grid(row=2, column=0, columnspan=2, sticky="w") self.buttonNVENC = Radiobutton( self.videoOptions, text="Nvidia NVENC GPU encoder (experimental)", variable=self.hwaccVar, value="NVENC") self.buttonNVENC.grid(row=3, column=0, columnspan=2, sticky="w") if self.cmdGen.encoder == "mpeg4": self.hwaccVar.set("CPU") elif self.cmdGen.encoder == "h264_nvenc": self.hwaccVar.set("NVENC") self.drawMouseVar = IntVar() self.drawMouseVar.set(self.cmdGen.drawMouse) self.drawMouseCheck = Checkbutton(self.videoOptions, text="Draw mouse", variable=self.drawMouseVar) self.drawMouseCheck.grid(row=5, column=0, columnspan=2, sticky='w', pady=10) self.notebook.add(self.videoOptions, text="Video Options") ###################################################################################################################### ############################################### AUDIO OPTIONS ##################################################### self.audioOptions = Frame(self) self.audioOptions.columnconfigure(0, weight=1) self.audioOptions.rowconfigure(2, weight=1) self.audInputVar = StringVar() self.defaultCheck = Radiobutton( self.audioOptions, text="Record from the default device only", value="default", variable=self.audInputVar) self.defaultCheck.grid(row=0, column=0, sticky="w") self.selectedCheck = Radiobutton(self.audioOptions, text="Record from these devices:", value="selected", variable=self.audInputVar) self.selectedCheck.grid(row=1, column=0, sticky="w") self.audioDevices = Listbox(self.audioOptions, selectmode="multiple") self.audioDevices.grid(row=2, column=0, sticky='news') self.deviceIDList = [] for i in range(self.audioRec.getDeviceCount()): if self.audioRec.isInputDevice(i): self.deviceIDList.append(i) self.audioDevices.insert( "end", self.audioRec.getAPIName(i) + " || " + self.audioRec.getDeviceName(i)) if i in self.audioRec.devices: self.audioDevices.selection_set('end') self.audInputVar.trace("w", self.audButtonChange) if self.audioRec.devices == [None]: self.audInputVar.set("default") else: self.audInputVar.set("selected") self.notebook.add(self.audioOptions, text="Audio Options") #################################################################################################################### self.okButton = Button(self, text="OK", width=9, command=self.applyQuit) self.okButton.grid(row=1, column=1, padx=4, pady=4) self.cancelButton = Button(self, text="Cancel", width=9, command=self.destroy) self.cancelButton.grid(row=1, column=2, padx=4, pady=4) self.applyButton = Button(self, text="Apply", width=9, command=self.apply) self.applyButton.grid(row=1, column=3, padx=4, pady=4) self.grab_set() self.focus() def audButtonChange(self, *args): if self.audInputVar.get() == "default": self.audioDevices.config(state=DISABLED) else: self.audioDevices.config(state=NORMAL) def apply(self): self.cmdGen.config(fps=int(self.FPSVar.get())) if self.hwaccVar.get() == "CPU": self.cmdGen.config(encoder='mpeg4', hwaccel=None) elif self.hwaccVar.get() == "NVENC": self.cmdGen.config(encoder='h264_nvenc', hwaccel=None) if self.audInputVar == "default": self.audioRec.setToDefault() elif len(self.audioDevices.curselection()) > 0: deviceList = [] for i in range(len(self.deviceIDList)): if self.audioDevices.selection_includes(i): deviceList.append(self.deviceIDList[i]) print("AUD DEV LIST: " + str(deviceList)) self.audioRec.setToDevices(deviceList) def applyQuit(self): self.apply() self.destroy()
def __init__(self, parent: Tk or Toplevel, param_ids: List[int]): Frame.__init__(self, parent) self.parent = parent self.param_ids = param_ids self.paragraph_params = [ param_id for param_id in param_ids if not PARAMS[param_id].is_run ] self.run_params = [ param_id for param_id in param_ids if PARAMS[param_id].is_run ] self.pack(fill=BOTH, expand=1) self.centerWindow() self.parent.title('Введите параметры для анализа') self.user_input = { param_id: StringVar() for param_id in self.param_ids } container1 = Frame(self) group = LabelFrame(container1, text='Шрифт') group.pack(side=TOP, fill=BOTH, expand=True) group2 = LabelFrame(container1, text='Абзац') group2.pack(side=TOP, fill=BOTH, expand=True) indent = 0 i = 0 for param_id in self.param_ids: param = PARAMS[param_id] if i < 4: current_group = group else: current_group = group2 lbl = Label(current_group, text=param.name) lbl.grid(row=i, sticky=W, padx=(5, 25)) if param.is_boolean: radio_btn = Radiobutton(current_group, variable=self.user_input[param_id], value="Нет") radio_btn.grid(row=i, column=1, sticky=W, padx=(5, 25)) i += 1 # # lbl_yes = Label(self, text="Нет") # lbl_yes.grid(row=i, sticky=W, padx=(5, 25)) # # # radio_btn = Radiobutton(self, variable=self.user_input[param_id], value="Да") # # radio_btn.place(x=scnd_row_x + 50, y=10 + indent) # # # # lbl_yes = Label(self, text="Да") # # # # lbl_yes.place(x=scnd_row_x + 70, y=10 + indent) # # self.user_input[param_id].set("Нет") # # else: # text_field = Combobox(self, textvariable=self.user_input[param_id]) # text_field['values'] = param.default_vals # text_field.current(param.start_val) # text_field.grid(row=i, sticky=W, padx=(5, 25)) # # indent += 23 container1.pack(side=LEFT, fill=BOTH) self.addButton = Button(self, text="Начать анализ", command=self.new_test) self.addButton.pack(padx=15, side=LEFT)
width=22, text='Добавить в друзья', value=6, variable=selected) rad7 = Radiobutton(app, width=22, text='Убрать из друзей', value=7, variable=selected) rad8 = Radiobutton(app, width=22, text='Отправить сообщение', value=8, variable=selected) rad1.grid(column=0, row=11) rad2.grid(column=0, row=12) rad3.grid(column=0, row=13) rad4.grid(column=0, row=14) rad5.grid(column=0, row=15) rad6.grid(column=0, row=16) rad7.grid(column=0, row=17) rad8.grid(column=0, row=18) button = Button(text="Выполнить", command=clicked) button.grid(row=4, column=1) button = Button(text="Как пользоваться?", command=howto) button.grid(row=4, column=0) app.mainloop()
lbl = Label(window, text="Текст Label: ") #добавить текст lbl.grid(column=0, row=0) #позиция текста txt = Entry( window, width=10) #форма ввода. Для выключения формы ввода , state='disabled txt.grid(column=1, row=0) #позиция ввода btn = Button(window, text="▲ Кнопка", command=clicked) #добавить кнопку btn.grid(column=2, row=0) #позиция кнопки combo = Combobox(window) #создаём окно combo['values'] = ("Виджет Combobox →", 1, 2, 3, 4, 5) #вводим значение combo.current(0) #какую строку выводит? combo.grid(column=0, row=1) #размеры окна chk_state = BooleanVar() #логический тип данных chk_state.set( 0) # задайте проверку состояния чекбокса 0 False(Ложь), 1 True(Истина) chk = Checkbutton(window, text='← Виджет Checkbutton', var=chk_state) # chk.grid(column=0, row=2) #позиция кнопки rad1 = Radiobutton(window, text='Первый', value=1) #Кнопка чекбокс с названием rad2 = Radiobutton(window, text='Второй', value=2) rad3 = Radiobutton(window, text='Третий', value=3) rad1.grid(column=0, row=3) #позиция rad2.grid(column=1, row=3) #позиция rad3.grid(column=2, row=3) #позиция window.mainloop() #функция бесконечного окна
class ModelFrame(LabelFrame): topPadding = 12 def __init__(self,parent): LabelFrame.__init__(self,parent,text="Model",borderwidth=5) self.selection = tkinter.IntVar() self.exponential = Radiobutton(self,text="Exponential model",variable=self.selection,value=Model.EXP.value,command=self.changeSelection) self.powerlaw = Radiobutton(self,text="Power law model",variable=self.selection,value=Model.POW.value,command=self.changeSelection) self.weibull = Radiobutton(self,text="Weibull model",variable=self.selection,value=Model.WEI.value,command=self.changeSelection) self.exponential.grid(row=0,column=0,sticky="W",padx=10,pady=(self.topPadding,5)) self.powerlaw.grid(row=1,column=0,sticky="W",padx=10,pady=5) self.weibull.grid(row=2,column=0,sticky="W",padx=10,pady=(5,0)) seperator = Separator(self, orient=tkinter.VERTICAL) seperator.grid(row=0, column=1, rowspan=3, sticky="NS", padx=(20,10), pady=(self.topPadding,0)) ## Exponential setup self.expNumberOfSegments_L = Label(self,text="Number of segments: ") self.expNumberOfSegments_E = Entry(self,width=5, justify="right") self.expNumberOfSegments_E.insert(0, settings.EXP_DEFAULT_NUMBER_OF_SEGMENTS) self.expWidgets = [self.expNumberOfSegments_L,self.expNumberOfSegments_E] ## Power law setup self.powProximalLimit_L = Label(self,text="Proximal limit of integration: ") self.powProximalLimit_E = Entry(self,width=5, justify="right") self.powDistalLimit_L = Label(self,text="Distal limit of integration: ") self.powDistalLimit_E = Entry(self,width=5, justify="right") self.powProximalLimit_E.insert(0, settings.POW_DEFAULT_PROXIMAL_LIMIT) self.powDistalLimit_E.insert(0, settings.POW_DEFAULT_DISTAL_LIMIT) self.powWidgets = [self.powProximalLimit_L,self.powProximalLimit_E, self.powDistalLimit_L,self.powDistalLimit_E] ## Weibull setup self.weiNumberOfRuns_L = Label(self,text="Number of runs: ") self.weiNumberOfRuns_E = Entry(self,width=5, justify="right") self.weiIterationsPerRun_L = Label(self,text="Iterations per run: ") self.weiIterationsPerRun_E = Entry(self,width=5, justify="right") self.weiEstimatedTime_L = Label(self,text="Estimated time (s): ") self.weiEstimatedTime_E = CustomEntry(self,width=5, justify="right") self.weiEstimatedTime_E.setUserEditable(False) self.weiLambdaLowerBoundL = Label(self,text="\u03BB lower bound:") self.weiLambdaUpperBoundL = Label(self,text="\u03BB upper bound:") self.weiLambdaLowerBoundE = Entry(self,width=5, justify="right") self.weiLambdaUpperBoundE = Entry(self,width=5, justify="right") self.weiKLowerBoundL = Label(self,text="k lower bound:") self.weiKUpperBoundL = Label(self,text="k upper bound:") self.weiKLowerBoundE = Entry(self,width=5, justify="right") self.weiKUpperBoundE = Entry(self,width=5, justify="right") self.weiNumberOfRuns_E.insert(0, settings.WEI_DEFAULT_NUMBER_OF_RUNS) self.weiIterationsPerRun_E.insert(0, settings.WEI_DEFAULT_ITERATIONS_PER_RUN) self.weiLambdaLowerBoundE.insert(0, settings.WEI_DEFAULT_LAMBDA_LOWER_BOUND) self.weiLambdaUpperBoundE.insert(0, settings.WEI_DEFAULT_LAMBDA_UPPER_BOUND) self.weiKLowerBoundE.insert(0, settings.WEI_DEFAULT_K_LOWER_BOUND) self.weiKUpperBoundE.insert(0, settings.WEI_DEFAULT_K_UPPER_BOUND) self.weiWidgets = [self.weiNumberOfRuns_L,self.weiNumberOfRuns_E, self.weiIterationsPerRun_L,self.weiIterationsPerRun_E, self.weiEstimatedTime_L,self.weiEstimatedTime_E, self.weiLambdaLowerBoundL,self.weiLambdaUpperBoundL,self.weiLambdaLowerBoundE,self.weiLambdaUpperBoundE, self.weiKLowerBoundL,self.weiKUpperBoundL,self.weiKLowerBoundE,self.weiKUpperBoundE] ## General self.currentWidgets = [] self.selection.set(Model.EXP.value) self.changeSelection() def changeSelection(self): for widget in self.currentWidgets: widget.grid_remove() modelType = Model(self.selection.get()) sX = 10 bX = 20 if modelType == Model.EXP: self.expNumberOfSegments_L.grid(row=0,column=2,padx=(bX,sX),pady=(self.topPadding,5),sticky="W") self.expNumberOfSegments_E.grid(row=0,column=3,padx=(sX,bX),pady=(self.topPadding,5),sticky="W") self.currentWidgets = self.expWidgets elif modelType == Model.POW: self.powProximalLimit_L.grid(row=0,column=2,padx=(bX,sX),pady=(self.topPadding,5),sticky="W") self.powProximalLimit_E.grid(row=0,column=3,padx=(sX,bX),pady=(self.topPadding,5),sticky="W") self.powDistalLimit_L.grid(row=1,column=2,padx=(bX,sX),pady=5,sticky="W") self.powDistalLimit_E.grid(row=1,column=3,padx=(sX,bX),pady=5,sticky="W") self.currentWidgets = self.powWidgets elif modelType == Model.WEI: self.weiNumberOfRuns_L.grid(row=0,column=2,padx=(bX,sX),pady=(self.topPadding,5),sticky="W") self.weiNumberOfRuns_E.grid(row=0,column=3,padx=(sX,bX),pady=(self.topPadding,5),sticky="W") self.weiIterationsPerRun_L.grid(row=1,column=2,padx=(bX,sX),pady=5,sticky="W") self.weiIterationsPerRun_E.grid(row=1,column=3,padx=(sX,bX),pady=5,sticky="W") self.weiEstimatedTime_L.grid(row=2,column=2,padx=(bX,sX),pady=5,sticky="W") self.weiEstimatedTime_E.grid(row=2,column=3,padx=(sX,bX),pady=5,sticky="W") self.weiLambdaLowerBoundL.grid(row=0,column=4,padx=(bX,sX),pady=(self.topPadding,5),sticky="W") self.weiLambdaLowerBoundE.grid(row=0,column=5,padx=(sX,bX),pady=(self.topPadding,5)) self.weiLambdaUpperBoundL.grid(row=1,column=4,padx=(bX,sX),pady=5,sticky="W") self.weiLambdaUpperBoundE.grid(row=1,column=5,padx=(sX,bX),pady=5) self.weiKLowerBoundL.grid(row=0,column=6,padx=(bX,sX),pady=(self.topPadding,5),sticky="W") self.weiKLowerBoundE.grid(row=0,column=7,padx=(sX,sX),pady=(self.topPadding,5)) self.weiKUpperBoundL.grid(row=1,column=6,padx=(bX,sX),pady=5,sticky="W") self.weiKUpperBoundE.grid(row=1,column=7,padx=(sX,sX),pady=5) self.currentWidgets = self.weiWidgets def getModelDetails(self): modelType = Model(self.selection.get()) values = [modelType] if modelType == Model.EXP: numberOfSegments = helper_functions.validateValue( self.expNumberOfSegments_E.get(), "The number of exponential segments must be 1 \u2264 n \u2264 " + str(settings.EXP_MAX_NUMBER_OF_SEGMENTS), "int", lowerBound=1, upperBound=settings.EXP_MAX_NUMBER_OF_SEGMENTS) values.append(numberOfSegments) elif modelType == Model.POW: proximalLimitKM = helper_functions.validateValue( self.powProximalLimit_E.get(), "The proximal limit of integration must be 0 \u2264 x \u2264 \u221E", "float", strictLowerBound=0, strictUpperBound=float('inf')) proximalLimitKM /= SQRT_PI distalLimitKM = helper_functions.validateValue( self.powDistalLimit_E.get(), "The distal limit of integration must be prox \u2264 x \u2264 \u221E", "float", strictLowerBound=proximalLimitKM, strictUpperBound=float('inf')) distalLimitKM /= SQRT_PI values.extend([proximalLimitKM,distalLimitKM]) elif modelType == Model.WEI: numberOfRuns = helper_functions.validateValue( self.weiNumberOfRuns_E.get(), "The number of runs must be greater than 0", "int", strictLowerBound=0) iterationsPerRun = helper_functions.validateValue( self.weiIterationsPerRun_E.get(), "The number of iterations must be greater than 0", "int", strictLowerBound=0) lambdaLowerBound = helper_functions.validateValue( self.weiLambdaLowerBoundE.get(), "The lower bound for \u03BB must be a decimal", "float") lambdaUpperBound = helper_functions.validateValue( self.weiLambdaUpperBoundE.get(), "The upper bound for \u03BB must be greater than the lower bound", "float", strictLowerBound=lambdaLowerBound) kLowerBound = helper_functions.validateValue( self.weiKLowerBoundE.get(), "The lower bound for k must be numeric and less than 2", "float", strictUpperBound=2) kUpperBound = helper_functions.validateValue( self.weiKUpperBoundE.get(), "The upper bound for k must be greater than the lower bound and less than or equal to 2", "float", strictLowerBound=kLowerBound, upperBound=2) values.extend([numberOfRuns,iterationsPerRun,[[lambdaLowerBound,lambdaUpperBound],[kLowerBound,kUpperBound]]]) return values