class GUI: """For reciprocal space maps""" def __init__(self, master): self.file_path = None self.RSM = None #Defaul scale for RSM and Linescan is logarithmic self.rsm_scale = StringVar() self.rsm_scale.set("log") self.line_scale = StringVar() self.line_scale.set("log") #Default parameters for RSM self.rsm_parallel_lower = -0.01 self.rsm_parallel_upper = 0 self.rsm_normal_lower = 0.5 self.rsm_normal_upper = 0.52 #Default parameters for linescan self.origin_parallel = -0.0007 self.origin_normal = 0.51192 self.linescan_angle = 0.0 self.linescan_width = 0.000015 self.window_frame = Frame(master, bd=2, relief=GROOVE) self.fileselect_button = Button(self.window_frame, text="Select XRDML file", command=self.select_file) self.busy_label = Label(self.window_frame, text="") self.savebutton1 = Button(self.window_frame, text="Save RSM", command=lambda: self.savefigure(self.rsm_plot_figure)) self.savebutton2 = Button(self.window_frame, text="Save Linescan", command=lambda: self.savefigure(self.linescan_plot_figure)) self.rsm_frame = Frame(self.window_frame, bd=2, relief=GROOVE) self.rsm_label = Label(self.rsm_frame, text="Amerigo - RSM Viewer Space Map") self.rsm_parallel_lower_label = Label(self.rsm_frame, text="Lower q-parallel bound") self.rsm_parallel_lower_entry = Entry(self.rsm_frame) self.rsm_parallel_upper_label = Label(self.rsm_frame, text="Upper q-parallel bound") self.rsm_parallel_upper_entry = Entry(self.rsm_frame) self.rsm_normal_lower_label = Label(self.rsm_frame, text="Lower q-normal bound") self.rsm_normal_lower_entry = Entry(self.rsm_frame) self.rsm_normal_upper_label = Label(self.rsm_frame, text="Upper q-normal bound") self.rsm_normal_upper_entry = Entry(self.rsm_frame) self.rsm_sclae_linear = Radiobutton(self.rsm_frame, text="Linear", variable=self.rsm_scale, value="linear") self.rsm_sclae_log = Radiobutton(self.rsm_frame, text="Logarithmic", variable=self.rsm_scale, value="log") self.create_rsm_button = Button(self.rsm_frame, text="Create RSM", command=self.create_rsm) self.linescan_frame = Frame(self.window_frame, bd=2, relief=GROOVE) self.linescan_label = Label(self.linescan_frame, text="Line Scan") self.origin_parallel_label = Label(self.linescan_frame, text="Point of origin parallel coordinate") self.origin_normal_label = Label(self.linescan_frame, text="Point of origin normal coordinate") self.linescan_angle_label = Label(self.linescan_frame, text="Angle to parallel axis in degrees") self.linescan_width_label = Label(self.linescan_frame, text="Linescan thickness intervall") self.origin_parallel_entry = Entry(self.linescan_frame) self.origin_normal_entry = Entry(self.linescan_frame) self.linescan_angle_entry = Entry(self.linescan_frame) self.linescan_width_entry = Entry(self.linescan_frame) self.create_linescan_button = Button(self.linescan_frame, text="Create linescan", command=self.create_line_scan) self.line_scale_log = Radiobutton(self.linescan_frame, text="Logarithmic", variable=self.line_scale, value="log") self.line_scale_linear = Radiobutton(self.linescan_frame, text="Linear", variable=self.line_scale, value="linear") self.rsm_plot_frame = Frame(master, relief=GROOVE, bd=2) self.rsm_plot_figure = Figure() self.rsm_canvas = FigureCanvasTkAgg(self.rsm_plot_figure, master=self.rsm_plot_frame) self.rsm_toolbar = NavigationToolbar2TkAgg(self.rsm_canvas, self.rsm_plot_frame) self.rsm_toolbar.update() self.rsm_canvas.show() self.linescan_plot_frame = Frame(master, relief=GROOVE, bd=2) self.linescan_plot_figure = Figure() self.linescan_canvas = FigureCanvasTkAgg(self.linescan_plot_figure, master=self.linescan_plot_frame) self.linescan_toolbar = NavigationToolbar2TkAgg(self.linescan_canvas, self.linescan_plot_frame) self.linescan_toolbar.update() self.linescan_canvas.show() self.place_widgets() def place_widgets(self): self.window_frame.place(x=10, y=10, width=425, height=520) self.fileselect_button.place(x=5, y=5, width=415, height=25) self.savebutton1.place(x=5, y=485, height=25, width=205) self.savebutton2.place(x=215, y=485, height=25, width=200) self.rsm_frame.place(x=5, y=35, height=220, width=415) self.rsm_label.place(x=5, y=5, height=25, width=405) self.rsm_parallel_lower_label.place(x=5, y=35, height=25, width=200) self.rsm_normal_lower_label.place(x=5, y=65, height=25, width=200) self.rsm_parallel_upper_label.place(x=5, y=95, height=25, width=200) self.rsm_normal_upper_label.place(x=5, y=125, height=25, width=200) self.rsm_parallel_lower_entry.place(x=210, y=35, height=25, width=200) self.rsm_parallel_upper_entry.place(x=210, y=65, height=25, width=200) self.rsm_normal_lower_entry.place(x=210, y=95, height=25, width=200) self.rsm_normal_upper_entry.place(x=210, y=125, height=25, width=200) self.rsm_sclae_linear.place(x=5, y=155, height=25, width=200) self.rsm_sclae_log.place(x=210, y=155, height=25, width=200) self.create_rsm_button.place(x=5, y=185, height=25, width=405) self.linescan_frame.place(x=5, y=260, width=415, height=220) self.linescan_label.place(x=5, y=5, width=405, height=25) self.origin_parallel_label.place(x=5, y=35, width=200, height=25) self.origin_normal_label.place(x=5, y=65, width=200, height=25) self.linescan_angle_label.place(x=5, y=95, width=200, height=25) self.linescan_width_label.place(x=5, y=125, width=200, height=25) self.origin_parallel_entry.place(x=210, y=35, width=200, height=25) self.origin_normal_entry.place(x=210, y=65, width=200, height=25) self.linescan_angle_entry.place(x=210, y=95, width=200, height=25) self.linescan_width_entry.place(x=210, y=125, width=200, height=25) self.line_scale_linear.place(x=5, y=155, width=200, height=25) self.line_scale_log.place(x=210, y=155, width=200, height=25) self.create_linescan_button.place(x=5, y=185, width=405, height=25) self.rsm_plot_frame.place(x=440, y=10, width=480, height=520) self.rsm_canvas.get_tk_widget().place(x=5, y=5, height=470, width=470) self.linescan_plot_frame.place(x=925, y=10, width=480, height=520) self.linescan_canvas.get_tk_widget().place(x=5, y=5, height=470, width=470) def select_file(self): self.file_path = askopenfilename() self.busy_label.configure(text="Be patient, I have a lot of data to read") self.RSM = Reciprocal(self.file_path) self.RSM.readfile() self.RSM.refine_data() self.busy_label.configure(text="") def create_rsm(self): if self.RSM is not None: self.busy_label.configure(text="Busy! Plotting %s data points." % len(self.RSM.intensity)) if self.rsm_parallel_lower_entry.get() != "": self.rsm_parallel_lower = float(self.rsm_parallel_lower_entry.get()) if self.rsm_parallel_upper_entry.get() != "": self.rsm_parallel_upper = float(self.rsm_parallel_upper_entry.get()) if self.rsm_normal_lower_entry.get() != "": self.rsm_normal_lower = float(self.rsm_normal_lower_entry.get()) if self.rsm_normal_upper_entry.get() != "": self.rsm_normal_upper = float(self.rsm_normal_upper_entry.get()) x = self.RSM.q_parallel y = self.RSM.q_normal if self.rsm_scale == "linear": z = self.RSM.intensity else: z = self.RSM.log_intensity ax = self.rsm_plot_figure.gca() ax.clear() ax.tricontourf(x, y, z, 1000, cmap="gist_rainbow") ax.tricontour(x, y, z, 8, colors="black") ax.set_ylabel(r"$q_{\perp} [\AA^{-1}]$") ax.set_xlabel(r"$q_{\parallel} [\AA^{-1}]$") ax.set_xlim(self.rsm_parallel_lower, self.rsm_parallel_upper) ax.set_ylim(self.rsm_normal_lower, self.rsm_normal_upper) ax.axis("equal") self.rsm_plot_figure.subplots_adjust(left=0.2) self.rsm_canvas.draw() self.busy_label.configure(text="") else: self.busy_label.configure(text="Select XRDML file first!") def create_line_scan(self): if self.RSM is not None: self.busy_label.configure(text="Busy! Processing %s data points." % len(self.RSM.intensity)) if self.origin_parallel_entry.get() != "": self.origin_parallel = float(self.origin_parallel_entry.get()) if self.origin_normal_entry.get() != "": self.origin_normal = float(self.origin_normal_entry.get()) if self.linescan_angle_entry.get() != "": self.linescan_angle = float(self.linescan_angle_entry.get()) if self.linescan_width_entry.get() != "": self.linescan_width = float(self.linescan_width_entry.get()) line = self.RSM.create_line_scan(self.origin_parallel, self.origin_normal, self.linescan_angle, self.linescan_width) bx = self.linescan_plot_figure.gca() bx.clear() bx.plot(line[0], line[1], '-o') bx.set_xlim(-0.005, 0.005) bx.set_yscale(self.line_scale.get()) bx.set_ylabel("Counts") bx.set_xlabel(r"Distance from origin $[\AA]^{-1}$") self.linescan_canvas.draw() self.busy_label.configure(text="") else: self.busy_label.configure(text="Select XRDML file first!") def savefigure(self, figure): if figure: figure.savefig(self.file_path+"_picture.png")
def __init__(self, **kwargs): super().__init__(**kwargs) self._isReady = False Grid.rowconfigure(self, 0, weight = 1) Grid.columnconfigure(self, 0, weight = 1) # Create a list of all available parsers and their class objects self._pList = [(name, parser()) for name, parser in inspect.getmembers(parsers, inspect.isclass) if issubclass(parser, parsers.Parser) and name != 'Parser'] plugins = _utils.findPlugins('Parser') self._pList.extend(((name, parser()) for name, parser in plugins)) # value = 1 prevents PositionParser's config window from opening v = IntVar(value = 1) parent = self.master for index, (text, _) in enumerate(self._pList): b = Radiobutton( self, text=text, variable = v, value=index, command = lambda: self._configureParser(v, parent)) b.grid(row = index, column = 0, sticky = W) # Intialize the parser contained by the LabelFrame self._configureParser(v, parent) self._isReady = True
def make_Radiobutton_2(self, frame): """ Radiobutton: False : at RadioGroup_1(3,1)""" self.Radiobutton_2 = Radiobutton(frame, value="2", text="False", width="15", anchor="w") self.Radiobutton_2.grid(row=3, column=1) # >>>>>>insert any user code below this comment for section "make_Radiobutton_2" self.Radiobutton_2.configure(variable=self.RadioGroup_1_StringVar)
def create_radio_buttons(self): # Scale related entries = ['DIATONIC', 'HARMONIC', 'MELODIC', 'PENTATONIC', 'PENTA_MINOR', 'GREEK_CHROMATIC', 'GREEK_ENHARMONIC'] self.scale = StringVar() self.scale.set('DIATONIC') self.rb_frame = Frame(self) for e in entries: rb = Radiobutton(self.rb_frame, value=e, text=e, anchor=W, command=self.send_scale, variable=self.scale) rb.grid(row=len(self.rb_frame.winfo_children()), sticky=W) self.rb_frame.grid(column=1, row=len(self.grid_slaves(column=1)), rowspan=3)
def make_Radiobutton_4(self, frame): """ Radiobutton: TkDefaultFont : at RadioGroup_1(4,0)""" self.Radiobutton_4 = Radiobutton(frame, text="TkDefaultFont", value="4", width="15", anchor="w") self.Radiobutton_4.grid(row=4, column=0) # >>>>>>insert any user code below this comment for section "make_Radiobutton_4" self.Radiobutton_4.configure(variable=self.RadioGroup_1_StringVar)
def make_Radiobutton_1(self, frame): """ Radiobutton: True : at RadioGroup_1(2,1)""" self.Radiobutton_1 = Radiobutton(frame, value="1", text="True", width="15", anchor="w") self.Radiobutton_1.grid(row=2, column=1) # >>>>>>insert any user code below this comment for section "make_Radiobutton_1" self.Radiobutton_1.configure(variable=self.RadioGroup_1_StringVar)
def make_Radiobutton_3(self, frame): """ Radiobutton: Times : at RadioGroup_1(3,0)""" self.Radiobutton_3 = Radiobutton(frame, text="Times", value="3", width="15", anchor="w") self.Radiobutton_3.grid(row=3, column=0) # >>>>>>insert any user code below this comment for section "make_Radiobutton_3" self.Radiobutton_3.configure(variable=self.RadioGroup_1_StringVar)
def add_radio_button_group(self, buttons, command, selected=1): variable = IntVar() variable.set(selected) for value, text in buttons.items(): radio_button = Radiobutton(self, text=text, value=value, variable=variable, command=lambda: command(variable.get()), indicatoron=False) radio_button.pack(side=LEFT, fill=X)
def make_Radiobutton_6(self, frame): """ Radiobutton: Symbol : at RadioGroup_1(5,0)""" self.Radiobutton_6 = Radiobutton(frame, text="Symbol", value="5", width="15", anchor="w") self.Radiobutton_6.grid(row=5, column=0) # >>>>>>insert any user code below this comment for section "make_Radiobutton_6" self.Radiobutton_6.configure(variable=self.RadioGroup_1_StringVar)
def init_reformat_display(self): orientation_var = IntVar(0) orientation_var.trace_add("write", self.__reformat_callback) count = 0 for text, _value in self._ORIENTATIONS: b = Radiobutton(self, text=text, variable=orientation_var, value=count) b.pack(side=tk.TOP, anchor="w") count += 1 self._orientation = orientation_var
def drawChoice(self) : frame = LabelFrame(self,text="Mode") frame.grid(row=1,column=0,sticky="we",padx=5,pady=5); Radiobutton(frame,text="solve",variable=self.mode , value=True).grid(row=0,column=1,pady=(0,8)) Radiobutton(frame,text="check",variable=self.mode , value=False).grid(row=0,column=3,pady=(0,8)) frame2 = LabelFrame(self,text="Console") frame2.grid(row=2,column=0,sticky="we",padx=5,pady=5); self.debug = Label(frame2,text="\n\n") self.debug.grid(row=0,column=0,ipadx=5,pady=(8,0)) rstLbl = Label(self,text="reset ?",fg="blue",cursor="hand2") rstLbl.grid(row=3,column=0,sticky="w",padx=5,pady=0); rstLbl.bind("<Button-1>",self._resetPuzzle);
def create_radiobuttons(self, texts, grid_row, callback): var = IntVar() for idx, buttontext in enumerate(texts): chk = Radiobutton(self.frame, text=buttontext, variable=var, value=idx, command=lambda val=buttontext: callback(val)) chk.grid(row=grid_row + idx, column=0)
def make_Radiobutton_5(self, frame): """ Radiobutton: Platform Specific : at RadioGroup_1(6,0)""" self.Radiobutton_5 = Radiobutton(frame, text="Platform Specific", value="6", width="15", anchor="e") self.Radiobutton_5.grid(row=6, column=0) # >>>>>>insert any user code below this comment for section "make_Radiobutton_5" self.Radiobutton_5.configure(variable=self.RadioGroup_1_StringVar)
def make_Radiobutton_2(self, frame): """ Radiobutton: Helvetica : at RadioGroup_1(2,0)""" self.Radiobutton_2 = Radiobutton(frame, text="Helvetica", value="2", width="15", anchor="w") self.Radiobutton_2.grid(row=2, column=0) # >>>>>>insert any user code below this comment for section "make_Radiobutton_2" self.Radiobutton_2.configure(variable=self.RadioGroup_1_StringVar)
def __init__(self, x, y, board): self.boardA = board self.boardB = copy(board) self.root = Toplevel() self.root.title("Piece Placement Editing Window") f1 = Frame(self.root) #frame containing the save and cancel buttons f1.pack(side=TOP) f2 = Frame(self.root) #frame containing piece selection f2.pack(side=LEFT) b1 = Button(f1, text="SAVE", command=self.save) b2 = Button(f1, text="CANCEL", command=self.root.destroy) b1.pack(side=LEFT) b2.pack(side=RIGHT) l1 = Label(f2, text="Type") l2 = Label(f2, text="Colour") self.c1 = ttk.Combobox( f2, values=__piece_types__) #menu for piece type selection self.c1.current(0) l1.pack() self.c1.pack() l2.pack() self.v1 = StringVar() #radiobuttons for piece colour selection self.v1.set("red") for c in __player_colours__: b = Radiobutton(f2, text=c, variable=self.v1, value=c) b.pack() self.v2 = BooleanVar() c = Checkbutton(f2, text="Centrally Symmetrical Opponent", variable=self.v2) self.v2.set(False) c.pack() self.canvas = Canvas(self.root, width=320, height=320) self.boardB.canvas = self.canvas self.canvas.bind("<Button-1>", self.callback1) self.canvas.bind("<Button-3>", self.callback2) self.canvas.pack(side=BOTTOM) self.redraw(0) self.align(x, y) self.root.mainloop()
def make_Radiobutton_2(self, frame): """ Radiobutton: AA CR=3:1 large text : at RadioGroup_1(2,1)""" self.Radiobutton_2 = Radiobutton(frame, text="AA CR=3:1 large text", value="2", width="16", anchor="w", justify="left") self.Radiobutton_2.grid(row=2, column=1, sticky="w") # >>>>>>insert any user code below this comment for section "make_Radiobutton_2" self.Radiobutton_2.configure(variable=self.RadioGroup_1_StringVar)
def create_other_buttons(self): "Fill frame with buttons tied to other options." frame = self.make_frame("Direction")[0] var = self.engine.backvar others = [(1, 'Up'), (0, 'Down')] for val, label in others: btn = Radiobutton(frame, anchor="w", variable=var, value=val, text=label) btn.pack(side="left", fill="both") #print(var.get(), val, label) if var.get() == val: btn.select() return frame, others # for test
def make_Radiobutton_4(self, frame): """ Radiobutton: AAA CR=4.5:1 for large text : at RadioGroup_1(4,1)""" self.Radiobutton_4 = Radiobutton(frame, text="AAA CR=4.5:1 for large text", value="4", width="20", anchor="w", justify="left") self.Radiobutton_4.grid(row=4, column=1, sticky="w") # >>>>>>insert any user code below this comment for section "make_Radiobutton_4" self.Radiobutton_4.configure(variable=self.RadioGroup_1_StringVar)
def make_Radiobutton_3(self, frame): """ Radiobutton: AAA CR=7:1 for normal text : at RadioGroup_1(3,1)""" self.Radiobutton_3 = Radiobutton(frame, text="AAA CR=7:1 for normal text", value="3", width="20", anchor="w", justify="left") self.Radiobutton_3.grid(row=3, column=1, sticky="w") # >>>>>>insert any user code below this comment for section "make_Radiobutton_3" self.Radiobutton_3.configure(variable=self.RadioGroup_1_StringVar)
def pack_preference_radio_button(frame, preference): Radiobutton(frame, text="Mixdown to mono", variable=preference, value=audiofile.ImportPreferences.mono.value).pack(side=LEFT) Radiobutton(frame, text="Use left channel", variable=preference, value=audiofile.ImportPreferences.left.value).pack(side=LEFT) Radiobutton(frame, text="Use right channel", variable=preference, value=audiofile.ImportPreferences.right.value).pack(side=LEFT)
def UI(): # 软件窗口大小 sWidth = 400 sHeight = 180 # 初始化窗口 root = tk.Tk() root.title('财务造假识别 V1.001') # 窗口居中 screen_w = root.winfo_screenwidth() screen_h = root.winfo_screenheight() alignstr = '%dx%d+%d+%d' % (sWidth, sHeight, (screen_w - sWidth) / 2, (screen_h - sHeight) / 2) root.geometry(alignstr) # 第一行布局 Label(root, text="文件路径", font=(6)).grid(row=0) entry1 = Entry(root, width=30, xscrollcommand=True) entry1.grid(row=0, column=1) # 设置载入按钮 load_button = tk.Button(root, text='浏览', command=lambda: load_file(entry1), font=(6)) load_button.grid(row=0, column=2, padx=3, pady=3) # 第二行布局 v = IntVar() select_model = [('支持向量机', 0), ('随机森林', 1), ('融合模型', 2)] for model_type, num in select_model: model_radio_button = Radiobutton(root, text=model_type, value=num, command=lambda: choose_model(v), variable=v, font=(6)) model_radio_button.grid(row=1, column=num) # 第三行布局 Label(root, text="结果", font=(6)).grid(row=2) entry2 = Entry(root, width=30, xscrollcommand=True) entry2.grid(row=2, column=1) # 设置预测按钮 load_button = tk.Button(root, text='开始', command=lambda: test(root, entry2), font=(6)) load_button.grid(row=2, column=2, padx=3, pady=3) root.mainloop()
class RadioButton(ScheduleMixin, DestroyMixin, EnableMixin, FocusMixin, DisplayMixin, ReprMixin): def __init__(self, master, text, value, variable, command=None, grid=None, align=None): self.description = "[RadioButton] object with option=\"" + str( text) + "\" value=\"" + str(value) + "\"" self._text = text self._value = value # `variable` is the externally passed StringVar keeping track of which # option was selected. This class should not be instantiated by a user # unless they know what they are doing. self.tk = Radiobutton(master.tk, text=self._text, value=self._value, variable=variable) # PROPERTIES # ----------------------------------- # The value of this button @property def value(self): return (self._value) @value.setter def value(self, value): self._value = str(value) self.tk.config(value=str(value)) self.description = "[RadioButton] object with option=\"" + self._text + "\" value=\"" + str( value) + "\"" # The text from this button @property def text(self): return (self._text) @text.setter def text(self, text): self._text = str(text) self.tk.config(text=self._text) self.description = "[RadioButton] object with option=\"" + str( text) + "\" value=\"" + self._value + "\""
def set_new_time_or_continue_after_manual_check(top_settings): global reset_time_after_manually_check_intvar reset_time_after_manually_check_intvar = IntVar() reset_time_after_manually_check_intvar.set( reset_time_after_manually_check_int) label_reset_time_after_manually_check_ = Label( top_settings, text="After checking manually:") label_reset_time_after_manually_check_.grid(column=0, row=4, rowspan=2, sticky=W) radiobutton_reset_time_after_manually_check_on = Radiobutton( top_settings, text="New time (reset time)", variable=reset_time_after_manually_check_intvar, value=1) radiobutton_reset_time_after_manually_check_off = Radiobutton( top_settings, text="Continue time", variable=reset_time_after_manually_check_intvar, value=0) radiobutton_reset_time_after_manually_check_on.grid(column=1, row=4, sticky=W) radiobutton_reset_time_after_manually_check_off.grid(column=1, row=5, sticky=W)
class Select_Py_Version(_Dialog): """ Select_Py_Version is a tkinter pop-up dialog used to select a python interpreter for use with Tk_Nosy. """ def body(self, master): dialogframe = Frame(master, width=300, height=300) dialogframe.pack() self.Label_1 = Label(dialogframe, text="Select Python Version") self.Label_1.pack() if self.dialogOptions: rbL = self.dialogOptions.get('rbL', ['No Options','No Options']) else: rbL = ['No Options', 'No Options'] self.RadioGroup1_StringVar = StringVar() self.RadioGroup1_StringVar.set(rbL[0]) self.RadioGroup1_StringVar_traceName = \ self.RadioGroup1_StringVar.trace_variable("w", self.RadioGroup1_StringVar_Callback) for rb in rbL: self.Radiobutton_1 = Radiobutton(dialogframe, text=rb, value=rb) self.Radiobutton_1.pack(anchor=W) self.Radiobutton_1.configure( variable=self.RadioGroup1_StringVar ) self.resizable(0, 0) # Linux may not respect this def RadioGroup1_StringVar_Callback(self, varName, index, mode): """When radio group selection changes, print message to CLI.""" print( "RadioGroup1_StringVar_Callback varName, index, mode", varName, index, mode ) print( " new StringVar value =", self.RadioGroup1_StringVar.get() ) def validate(self): """Validates and packages dialog selections prior to return to calling routine. set values in "self.result" dictionary for return """ self.result = {} # return a dictionary of results self.result["selection"] = self.RadioGroup1_StringVar.get() return 1 def apply(self): print( 'apply called')
def open_render_view(self): try: path = filedialog.askopenfilename(initialdir=".", filetypes=(("DOT graph", "*.gv *.dot"), ("all files", "*.*")), title="Choose a file.") path_splitted = os.path.split(path) ext = path_splitted[1].split('.') # Check in case user enter an unknown file # or closes without choosing a file. if ext[1] != 'dot' and ext[1] != 'gv': self.popupmsg("Wrong extension file inserted!\n" "Please insert a DOT file") else: # define the frame and its geometry r_window = tk.Toplevel(padx=20, pady=20, bg=self.COLOR_frames) r_window.wm_title("Render") r_window.resizable(False, False) self.__set_window_dimension__(r_window) label_format = tk.Label(r_window, text="Choose a file format for render:", fg=self.COLOR_foreground, bg=self.COLOR_frames, wraplength=500) label_format.grid(row=0, column=0) # Initialize file format variable for radiobutton option = tk.StringVar() # Radiobutton rb1 = Radiobutton(r_window, text='png', value="png", var=option, bg=self.COLOR_frames) rb2 = Radiobutton(r_window, text='pdf', value="pdf", var=option, bg=self.COLOR_frames) rb1.grid(row=1, column=0) rb2.grid(row=1, column=1) # TODO try except for wrong dot files b = Button(r_window, text='Render', bg=self.COLOR_buttons, command=lambda: (self.log(["[RENDER] " + self.controller.render(path, option.get())]), r_window.destroy())) b.grid(row=2, column=1) except: pass
def init_info_labels(self): """ Initialize the labels providing info about input fields """ Radiobutton(self.frame, variable=self.radio_angle_var, value=False, text="Degrees").grid(row=1, column=0) Radiobutton(self.frame, variable=self.radio_angle_var, value=True, text="Radians").grid(row=1, column=1) Label(self.frame, text="Angle").grid(row=2, column=0, sticky=W) Label(self.frame, text="Length").grid(row=2, column=1, sticky=W)
def __setup__(self): frame_timezone = LabelFrame(self._root, text='Timezone') frame_timezone.pack() label1 = Label(frame_timezone, text='UTC+') label1.grid(row=0, column=0, padx=(5, 0), pady=5) self.entry1 = Entry(frame_timezone) self.entry1.grid(row=0, column=1, padx=(0, 5), pady=5) self.entry1.delete(0, 'end') self.entry1.insert(0, str(self._main.time_offset)) frame_orientation = LabelFrame(self._root, text='Orientation') frame_orientation.pack() self.switch_variable = IntVar(value=self._main.gps_sign) east_button = Radiobutton(frame_orientation, text='East', variable=self.switch_variable, value=True, width=8) west_button = Radiobutton(frame_orientation, text='West', variable=self.switch_variable, value=False, width=8) east_button.grid(row=0, column=0) west_button.grid(row=0, column=1) save_button = Button(self._root, text='Save', command=self.save_gps) save_button.pack()
def onOpen(self): ftypes = [('Excel files', '*.xls, *.xlsx'), ('All files', '*')] dlg = filedialog.Open(self, filetypes=ftypes) file = dlg.show() if file != '': self.filelabel.set("Current file: " + file) self.filename = file self.readExcel(self.filename) self.columns = BooleanVar() self.columns.set(1) if self.filelabel.get() != "File not chosen": rboneColumn = Radiobutton(self, text="Arrange in 1 column", variable=self.columns, value=1, command=self.onClick) rboneColumn.grid(sticky=W, row=2, column=1, padx=5, pady=5) rb2Columns = Radiobutton(self, text="Arrange in 2 columns", variable=self.columns, value=0, command=self.onClick) rb2Columns.grid(sticky=W, row=3, column=1, padx=5, pady=5)
def init_widgets(self): self._promopt_label = Label(self._input_frame, text="请选择:", font=self._my_font) self._promopt_label.place(x=10, y=7, anchor='nw') self.choice_A = Radiobutton(self._input_frame, variable=self.choosen, value='A', fg='blue', font=self._my_bold_font, text='A') self.choice_A.place(x=160, y=7, anchor='nw') self.choice_B = Radiobutton(self._input_frame, variable=self.choosen, font=self._my_bold_font, value='B', fg='blue', text='B') self.choice_B.place(x=240, y=7, anchor='nw') self.choice_C = Radiobutton(self._input_frame, variable=self.choosen, font=self._my_bold_font, value='C', fg='blue', text='C') self.choice_C.place(x=320, y=7, anchor='nw') self.choice_D = Radiobutton(self._input_frame, variable=self.choosen, font=self._my_bold_font, value='D', fg='blue', text='D') self.choice_D.place(x=400, y=7, anchor='nw') self.choosen.set('A')
def load_r(self, name, num1=65, num2=70, judge=True): for i in range(num1, num2 + 1): attr_name = name + chr(i) if num1 == 71: self.__class__.F = True stt = self.__class__.dicts_main.get(chr(i)) setattr( self, attr_name, Radiobutton(self.window, text=chr(i) + ' ' + stt, variable=self.__class__.var, value=chr(i), command=self.print_ser1)) self.pk_forget('r1', self.__class__.num_b, self.__class__.num_b, True) self.__class__.num_b = self.__class__.num_b + 1 else: if judge: stt = self.__class__.dicts_main.get(chr(i)) if chr(i) != 'F': setattr( self, attr_name, Radiobutton(self.window, text=chr(i) + ' ' + stt, variable=self.__class__.var, value=chr(i), command=self.print_selection)) else: setattr( self, attr_name, Radiobutton(self.window, text=chr(i) + ' ' + stt, variable=self.__class__.var, value=chr(i), command=self.select_h)) self.pk_forget('r', self.__class__.num_a, self.__class__.num_a, True) self.__class__.num_a = self.__class__.num_a + 1 else: stt = self.__class__.dicts_middle.get(chr(i)) setattr( self, attr_name, Radiobutton(self.window, text=chr(i) + ' ' + stt, variable=self.__class__.var, value=str(i), command=self.print_ser0)) self.pk_forget('r0', self.__class__.num_c, self.__class__.num_c, True) self.__class__.num_c = self.__class__.num_c + 1
def pass_info(*args): frame_head =Frame(root, bg='light yellow' ,bd=0) frame_head.place(relx=0.5, rely=0.01, relwidth=0.99, relheight=0.11, anchor='n') """ t="" for x in args: t+=" "+x t=t.strip() """ t=args[0] label_mesg = Label(frame_head,text=t) label_mesg.grid(row=0,column=0,columnspan=2) if len(args)>1: if args[1]=="NEW": rb1=Radiobutton(frame_head, text="Option 1", variable=r, value=1, anchor='n' ) rb1.grid(row=1,column=0,columnspan=1) rb2=Radiobutton(frame_head, text="Option 2", variable=r, value=0, anchor='n' ) rb2.grid(row=1,column=1,columnspan=1) opt_select = Button(frame_head,text="Confirm \n Option" ,command= lambda: clicked_rb(r.get(),frame_head,label_mesg ,rb1,rb2,opt_select,frame_pad,frame_status)) opt_select.grid(row=0,column=2,rowspan=2 , padx=0,pady=0) frame_pad =Frame(root, bg='light green' ,bd=0) frame_pad.place(relx=0.5, rely=0.13, relwidth=0.99, relheight=0.75 , anchor='n') frame_status =Frame(root, bg='light yellow' ,bd=0) frame_status.place(relx=0.5, rely=0.88, relwidth=0.99, relheight=0.12, anchor='n')
def bulbPopulate(bulbs): if len(devices.children) > 0: for widgets in devices.winfo_children(): widgets.destroy() i = 0 for name, v in bulbs.items(): ip = (list(v.values())[0]) bulb = Bulb(ip) dev_op = Radiobutton(devices, text=name, bg=bg_color, selectcolor=bg_color, width=24, offrelief="flat", overrelief="ridge", indicatoron=0, variable=bulbsOp, value=name, padx=1, command=lambda name=name, bulb=bulb: activateBulb(name, bulb)) dev_op.grid(column=0, row=i, pady=1) i += 1
def __init__(self): # create the window window = Tk() window.title("Widget Demo") # create the first frame frame1 = Frame(window) frame1.pack() # create variables for buttons and create the buttons self.v1 = IntVar() cbtBold = Checkbutton(frame1, text="Bold", variable=self.v1, command=self.processCheckbutton) self.v2 = IntVar() rbRed = Radiobutton(frame1, text="Red", bg="red", variable=self.v2, value=1, command=self.processRadiobutton) rbYellow = Radiobutton(frame1, text="Yellow", bg="yellow", variable=self.v2, value=2, command=self.processRadiobutton) # set the buttons in the frame cbtBold.grid(row=1, column=1) rbRed.grid(row=1, column=2) rbYellow.grid(row=1, column=3) # create the second frame frame2 = Frame(window) frame2.pack() # create labels and entry and button and message label = Label(frame2, text="Enter Your Name: ") self.name = StringVar() entryName = Entry(frame2, textvariable=self.name) btGetName = Button(frame2, text="Get Name", command=self.processButton) message = Message(frame2, text="This is the Message Widget") # position what we just made label.grid(row=1, column=1) entryName.grid(row=1, column=2) btGetName.grid(row=1, column=3) message.grid(row=1, column=4) # create a text window and add text to it text = Text(window) text.pack() text.insert(END, "Tip\nThe Best way to learn tkinter is to read ") text.insert(END, "these carefully designed examples and use them ") text.insert(END, "to create your application") window.mainloop()
def __init__(self, master): self.master = master self.offset = 0 with open('videos1.txt', 'r') as v_file: self.videos = json.load(v_file) with open('result.txt', 'r') as r_file: self.result = json.load(r_file) self.current = self.videos[0] self.title_label = Label(self.master, text=emoji_pattern.sub( "", self.current['title']), font=Font(size=15, weight='bold'), wraplength=580, justify=LEFT) self.title_label.place(anchor=NW, x=10, y=10) self._get_poster() self.poster_label = Label(self.master, image=tk_image) self.poster_label.place(anchor=NW, x=10, y=100) tags = ', '.join(self.current['tag']) self.tag_label = Label(self.master, text=emoji_pattern.sub("", tags), wraplength=580, justify=LEFT) self.tag_label.place(anchor=NW, x=10, y=350) self.sexy_value = IntVar() self.sexy_value.set(self.result.get(self.current['id'], -1)) sexy_radio = Radiobutton(master, text="sexy", variable=self.sexy_value, value=1, command=self.set_sexy) not_sexy_radio = Radiobutton(master, text="not sexy", variable=self.sexy_value, value=0, command=self.set_not_sexy) sexy_radio.place(anchor=NW, x=200, y=600) not_sexy_radio.place(anchor=NW, x=300, y=600) self.save_button = Button(self.master, text="save", command=self.handle_save) self.save_button.place(anchor=NW, x=400, y=600) self.previous_button = Button(self.master, text="previous", command=self.handle_previous) self.previous_button.place(anchor=NW, x=10, y=650) self.page_label = Label(self.master, text=str(self.offset)) self.page_label.place(anchor=NW, x=290, y=650) self.next_button = Button(self.master, text="next", command=self.handle_next) self.next_button.place(anchor=NW, x=550, y=650)
def __init__(self, parent, db, *args, **kwargs): Toplevel.__init__(self, *args, **kwargs) self.parent = parent self.db = db self.title('Register new competitor...') self.hr1 = Frame(self, height=1, width=500, bg="gray") # creates a gray line under the registration self.fnameLabel = Label(self, text='First:') self.lnameLabel = Label(self, text='Last:') self.levelLabel = Label(self, text='Level:') self.sexLabel = Label(self, text='Sex:') self.ageLabel = Label(self, text='Age:') self.sexValue = StringVar() self.sexValue.set('M') self.levelValues = ('Beginner', 'Intermediate', 'Advanced', 'Open') self.fnameEntry = EntryWithPlaceholder(self, placeholder='John', width=30) self.lnameEntry = EntryWithPlaceholder(self, placeholder='Doe', width=30) self.levelEntry = Spinbox(self, values=self.levelValues) self.sexEntryM = Radiobutton(self, text='M', variable=self.sexValue, value='M') self.sexEntryF = Radiobutton(self, text='F', variable=self.sexValue, value='F') self.ageEntry = Spinbox(self, from_=1, to=100, width=6) self.registerButton = Button(self, text='Register', command=self.register_competitor) self.ageEntry.delete('0', 'end') self.ageEntry.insert(0, 20) self.fnameEntry.bind('<Return>', self.register_competitor) # these bind all the entries to <return> self.lnameEntry.bind('<Return>', self.register_competitor) # meaning that hitting enter while within any of self.levelEntry.bind('<Return>', self.register_competitor) # of them will submit the form to the self.sexEntryF.bind('<Return>', self.register_competitor) # register_competitor function self.sexEntryM.bind('<Return>', self.register_competitor) self.ageEntry.bind('<Return>', self.register_competitor) self.registerButton.bind('<Return>', self.register_competitor) self.fnameLabel.grid(row=1, column=0) self.fnameEntry.grid(row=1, column=1, columnspan=4) self.lnameLabel.grid(row=1, column=5) self.lnameEntry.grid(row=1, column=6, columnspan=4) self.levelLabel.grid(row=2, column=0) self.levelEntry.grid(row=2, column=1, columnspan=2) self.sexLabel.grid(row=2, column=3) self.sexEntryM.grid(row=2, column=4) self.sexEntryF.grid(row=2, column=5) self.ageLabel.grid(row=2, column=6) self.ageEntry.grid(row=2, column=7) self.registerButton.grid(row=2, column=8)
def __init__(self, master): """initialize GUI""" self.root = master self.on = True self.connection = None Tk().withdraw() self.basicframe = Frame(self.root) self.basicframe.grid() self.basicframe.configure(bg=bgcolor) self.fr = Frame(self.basicframe) self.fr.grid(row=0, column=0, sticky='new') # , sticky='W') self.fr.configure(bg=bgcolor) Grid.columnconfigure(self.root, 0, weight=1) self.port = None self.baud = None # self.inputTypes = ['ascii', 'bin', 'hex', 'mix'] self.inputType = StringVar() self.inputType.set('ascii') self.input = 'ascii' self.labelPort = Label(self.fr, width=10, text='PORT', justify='left', anchor='w', bg=bgcolor, fg=fgcolor, font=("Calibri", 12)) self.entryPort = Entry(self.fr, width=20, bd=3, justify='left', bg=inputbox, fg=fgcolor) self.labelBaud = Label(self.fr, text='BAUD', justify='left', anchor='w', bg=bgcolor, fg=fgcolor, font=("Calibri", 12)) self.entryBaud = Entry(self.fr, width=20, bd=3, justify='right', bg=inputbox, fg=fgcolor) self.labelType = Label(self.fr, text='TYPE', justify='left', anchor='w', bg=bgcolor, fg=fgcolor, font=("Calibri", 12)) self.radioType1 = Radiobutton(self.fr, text='ascii', variable=self.inputType, value='ascii', indicatoron=0) self.radioType2 = Radiobutton(self.fr, text='bin', variable=self.inputType, value='bin', width=20, indicatoron=0) self.radioType3 = Radiobutton(self.fr, text='hex', variable=self.inputType, value='hex', indicatoron=0) self.radioType4 = Radiobutton(self.fr, text='mix', variable=self.inputType, value='mix', width=20, indicatoron=0) self.labelInput = Label(self.fr, text='INPUT', justify='left', anchor='w', bg=bgcolor, fg=fgcolor, font=("Calibri", 12)) self.entryInput = Entry(self.fr, width=20, bd=3, justify='left', bg=inputbox, fg=fgcolor) self.buttonSend = Button(self.fr, text='SEND', justify='center', bg=buttoncolor, command=self.send) self.buttonRead = Button(self.fr, text='READ', justify='center', bg=buttoncolor, command=self.read) self.buttonExit = Button(self.fr, text='EXIT', justify='center', bg='red', fg='white', command=self.exit) self.response = StringVar() self.response.set('') self.responseBar = Label(self.fr, textvariable=self.response, justify='left', anchor='w', bg=bgcolor, fg=fgcolor, font=("Calibri", 12)) self.status = StringVar() self.statusBar = Label(self.fr, textvariable=self.status, justify='left', anchor='nw', bg=bgcolor, fg=fgcolor, font=("Calibri", 10)) self.status.set('Initialized')
def create_other_buttons(self): """Return (frame, others) for testing. Others is a list of value, label pairs. A gridded frame from make_frame is filled with radio buttons. """ frame = self.make_frame("Direction")[0] var = self.engine.backvar others = [(1, "Up"), (0, "Down")] for val, label in others: btn = Radiobutton(frame, anchor="w", variable=var, value=val, text=label) btn.pack(side="left", fill="both") if var.get() == val: btn.select() return frame, others
def create_other_buttons(self): "Fill frame with buttons tied to other options." f = self.make_frame("Direction") btn = Radiobutton(f, anchor="w", variable=self.engine.backvar, value=1, text="Up") btn.pack(side="left", fill="both") if self.engine.isback(): btn.select() btn = Radiobutton(f, anchor="w", variable=self.engine.backvar, value=0, text="Down") btn.pack(side="left", fill="both") if not self.engine.isback(): btn.select()
def createCategoryButtons(self): """Create the buttons used to choose category. Return them.""" result = [] icons = self.readIcons() categories = self.predictor.categories() for i in categories: if i in icons: icon = icons[i] else: icon = icons["= default ="] category_button = Radiobutton(self, image=icon, variable=self.active_category, value=i, indicatoron=False, width=icon_size, height=icon_size, command=self.update) category_button.image_data = icon result.append(category_button) self.active_category.set(categories[0]) return result
def __init__(self): Tk.__init__(self) self.title("Nim") self.kamen = PhotoImage(file = './kamen.ppm') self.nacin = BooleanVar() #0 is ai, 1 is human self.nacin = 0 self.zahtevnost = DoubleVar() #0, 1, 2 are (easy, medium hard) self.vnos_nacina = Entry(self, textvariable = "način") ni = Button(self, text="Nova igra", command=self.nova_igra) ni.grid(column = 2, row = 0) self.platno = Canvas(self, width=700, height = 500, bg='white') self.platno.grid(row= 3, column = 0, columnspan=4) self.vrhovi = [] self.z1 = Radiobutton(self, text = "Skoraj Nepremagljivo!", variable = self.zahtevnost, value=1) self.z2 = Radiobutton(self, text = "Srednje zahtevno ", variable = self.zahtevnost, value=2) self.z3 = Radiobutton(self, text = "Za majhne punčke ", variable = self.zahtevnost, value=3) self.z1.grid(column = 0, row = 0) self.z2.grid(column = 0, row = 1) self.z3.grid(column = 0, row = 2) self.z1.select() self.konec = Label() self.mainloop()
def __init__(self, master): self.master = master master.title("ICP WaveForm Control") master.geometry("480x320") self.modelone = Radiobutton(master, text = "Normal", bg = 'seashell3', indicatoron = 0, value =1, variable = 1, command = self.modelone) ## self.modelone.pack(fill = X, expand = 1) self.modelone.grid(row = 1, column = 0, sticky ='WNS', padx = 0, pady = 10) self.modeltwo = Radiobutton(master, text = "Leveled",indicatoron = 0, value = 2, variable = 1, bg = 'seashell3',command = self.modeltwo) ## self.modeltwo.pack(fill = X, expand = 1) self.modeltwo.grid(row=2, column=0,sticky = 'WNS', padx =0, pady = 10) ## mi = PhotoImage(" ## self.modeltwo.config( self.modelthree = Radiobutton(master, text = "Abnormal", indicatoron = 0, value = 3, variable = 1, bg = 'seashell3', command = self.modelthree) ## self.modelthree.pack(fill = X, expand = 1) self.modelthree.grid(row=3, column=0, sticky ='WNS', padx = 0, pady = 10) self.donebutton = Radiobutton(master, text = "Zero", indicatoron = 0, variable = 1, value = 4, bg = 'seashell3', command = self.done) ## self.donebutton.pack(fill = X, expand = 1) self.donebutton.grid(row=4, column=0, sticky ='WNS', padx = 0, pady = 10) self.quitbutton = Radiobutton(master, text = "Quit", indicatoron = 0, value = 5, variable = 1, bg = 'seashell3', command = self.quit) ## self.quitbutton.pack(fill = X, expand = 1) self.quitbutton.grid(row=5, column=0, sticky ='EWNS', padx = 0, pady = 10) Label(master, text = "", width = 5, height = 5).grid(row = 2, column = 4, sticky = "WNS") self.DisplayButton = Button(master, text = self.rate1) self.DisplayButton.grid(column = 1, row = 2, sticky = "WNS") self.Plus1Button = Button(master, text = "+1", command=self.plus1, bg="green") self.Plus1Button.grid(column = 1, row = 1, sticky = "WNS") self.Neg1Button = Button(master, text = "-1", command=self.neg1, bg="green") self.Neg1Button.grid(column = 1, row = 3, sticky = "WNS") self.pid = -1
def __init__(self, master, parentWindow): frame = Frame(master) frame.pack() self.frame = frame # for destroy purpose self.master = master self.parentWindow = parentWindow # database with images self.imgDB = tm.cdb.imgDB # for database.get(item) self.item = 1 self.labelImgPlace = Label(frame, text="Image from database \n (click next)") self.labelImgPlace.grid(row=0, column=1) # buttons for going trought imgDB self.buttonNext = Button(frame, text="Next", command=self.next) self.buttonNext.grid(row=2, column=0) self.buttonBack = Button(frame, text="Back", command=self.back) self.buttonBack.grid(row=3, column=0) # label for name of class self.varForLabel = StringVar() self.labelClassName = Label(frame, textvariable=self.varForLabel) self.labelClassName.grid(row=4, column=0) self.button = Button(frame, text="load image", command=self.load_image) # self.button.grid(row=0, column=0) self.label = 0 # self.label=Label(frame,image=imgP) # self.label.pack(side=RIGHT) self.things = self.parentWindow.childResultList # ["cup","banana","pencil"] for i in range(len(self.things)): b = Radiobutton(self.frame, text=self.things[i], value=i) # write i-ths element from list to database as label b.config(command=lambda iter=i: self.choice_class(iter)) b.deselect() b.grid(row=i+1, column=2)
def radio_buttons(root, elements): """Creates and positions radio buttons for task selection.""" button_var = IntVar() path_button = Radiobutton(root, variable = button_var, value = PATH, background = 'gray') textbox_button = Radiobutton(root, variable = button_var, value = TEXT, background = 'gray') path_button.grid(row = 0, sticky = W) textbox_button.grid(row = 2, sticky = W) path_button.select() elements["path_button"] = path_button elements["textbox_button"] = textbox_button elements["button_var"] = button_var return elements
def body(self, master): dialogframe = Frame(master, width=300, height=300) dialogframe.pack() self.Label_1 = Label(dialogframe, text="Select Python Version") self.Label_1.pack() if self.dialogOptions: rbL = self.dialogOptions.get('rbL', ['No Options','No Options']) else: rbL = ['No Options', 'No Options'] self.RadioGroup1_StringVar = StringVar() self.RadioGroup1_StringVar.set(rbL[0]) self.RadioGroup1_StringVar_traceName = \ self.RadioGroup1_StringVar.trace_variable("w", self.RadioGroup1_StringVar_Callback) for rb in rbL: self.Radiobutton_1 = Radiobutton(dialogframe, text=rb, value=rb) self.Radiobutton_1.pack(anchor=W) self.Radiobutton_1.configure( variable=self.RadioGroup1_StringVar ) self.resizable(0, 0) # Linux may not respect this
labelSrcPath = Label(root, text="待整理目录:") labelSrcPath.grid(row=0, column=0, sticky=W) entrySrcPath = Entry(root, textvariable=srcPath, width=60) entrySrcPath.grid(row=0, column=1, columnspan=2, sticky=E) buttonSrcPath = Button(root, text="目录选择", width=10, command=selectSrcPath) buttonSrcPath.grid(row=0, column=3, sticky=E) labelDesPath = Label(root, text="输出目录:") labelDesPath.grid(row=1, column=0, sticky=W) entryDesPath = Entry(root, textvariable=desPath, width=60) entryDesPath.grid(row=1, column=1, columnspan=2, sticky=E) buttonDesPath = Button(root, text="目录选择", width=10, command=selectDesPath) buttonDesPath.grid(row=1, column=3, sticky=E) RadioYM = Radiobutton( root, text="按月分类", variable=radioVar, value=1) RadioYM.grid(row=2, column=1, sticky=W) RadioYM.select() RadioYMD = Radiobutton( root, text="按天分类", variable=radioVar, value=2) RadioYMD.grid(row=2, column=2, sticky=W) buttonSort = Button(root, text="开始", width=10, command=sort) buttonSort.grid(row=2, column=3, sticky=E) logText = ScrolledText(root) logText.grid(row=3, columnspan=4, sticky=W) logText.insert(END, '\n\n') logText.insert( END, ' ================说明====================\n\n\n\n')
class Nim(Tk): def __init__(self): Tk.__init__(self) self.title("Nim") self.kamen = PhotoImage(file = './kamen.ppm') self.nacin = BooleanVar() #0 is ai, 1 is human self.nacin = 0 self.zahtevnost = DoubleVar() #0, 1, 2 are (easy, medium hard) self.vnos_nacina = Entry(self, textvariable = "način") ni = Button(self, text="Nova igra", command=self.nova_igra) ni.grid(column = 2, row = 0) self.platno = Canvas(self, width=700, height = 500, bg='white') self.platno.grid(row= 3, column = 0, columnspan=4) self.vrhovi = [] self.z1 = Radiobutton(self, text = "Skoraj Nepremagljivo!", variable = self.zahtevnost, value=1) self.z2 = Radiobutton(self, text = "Srednje zahtevno ", variable = self.zahtevnost, value=2) self.z3 = Radiobutton(self, text = "Za majhne punčke ", variable = self.zahtevnost, value=3) self.z1.grid(column = 0, row = 0) self.z2.grid(column = 0, row = 1) self.z3.grid(column = 0, row = 2) self.z1.select() self.konec = Label() self.mainloop() def nova_igra(self): # print(self.zahtevnost.get()) if self.vrhovi != []: self.unici_kamne() self.k1.destroy() self.k2.destroy() self.k3.destroy() self.ligralec.destroy() # print(self.vrhovi) self.vrhovi = [randint(1, 5), randint(1, 5), randint(1, 5)] self.kamni = [[],[],[]] self.narisi_kamne(1) self.ligralec = Label(self, text='Na vrsti ste vi!', bg='white', font=("Calibri",21)) self.lracunalnik = Label(self, text='Na vrsti je računalnik', bg='white', font=("Calibri",21)) self.k1 = Label(self, text="Prvi kupček", bg='white') self.k1.place(x = 10, y=220) self.k2 = Label(self, text="Drugi kupček", bg='white') self.k2.place(x = 10, y=330) self.k3 = Label(self, text="Tretji kupček", bg='white') self.k3.place(x = 10, y=440) self.ligralec.place(x=300, y=130) self.konec.destroy() def preveri_zmagovalca(self, igralec): if max(self.vrhovi)<1: self.ligralec.destroy() self.lracunalnik.destroy() if igralec == 0: self.konec = Label(text='Čestitamo, zmagali ste!', bg = 'white', font=("Calibri", 24)) else: self.konec = Label(text = 'Več sreče prihodnjič!', bg = 'white', font=("Calibri",24)) self.konec.place(x=150, y=250) self.k1.destroy() self.k2.destroy() self.k3.destroy() def sestevek(self): s = 0 for i in range(len(self.vrhovi)): s = s^self.vrhovi[i] return s def sestevki(self): return [a^self.X < a for a in self.vrhovi] def naredi_potezo_AI(self): #Ta del kode sem dobil tako, da sem priredil kodo iz wikipedije #vir: http://en.wikipedia.org/wiki/Nim self.X = self.sestevek() S = self.sestevki() odstranjenih = 0 if self.X == 0: if max(self.vrhovi) >1: print("Can't win") for i, vrh in enumerate(self.vrhovi): if vrh>0: izbrani, odstranjenih = i, vrh else: izbrani = S.index(True) odstranjenih = self.vrhovi[izbrani] - (self.vrhovi[izbrani]^self.X) dva_alivec = 0 for i, vrh in enumerate(self.vrhovi): if i == izbrani: if vrh-odstranjenih > 1: dva_alivec += 1 else: if vrh > 1: dva_alivec += 1 if dva_alivec == 0: izbrani = self.vrhovi.index(max(self.vrhovi)) vrhov_z1 = sum(v == 1 for v in self.vrhovi) if vrhov_z1%2 == 1: odstranjenih = self.vrhovi[izbrani]-1 else: odstranjenih = self.vrhovi[izbrani] if odstranjenih == 0: odstranjenih = 1 izbrani = self.vrhovi.index(True) x = 10*(1-(1/self.zahtevnost.get())) v = randint(1, 10) if v < x: neprazni = [] for i, vr in enumerate(self.vrhovi): if vr>0: neprazni.append(i) izbrani = choice(neprazni) odstranjenih = randint(1, self.vrhovi[izbrani]) self.vrhovi[izbrani] -= odstranjenih self.unici_kamne() self.narisi_kamne(b=1) self.lracunalnik.place_forget() self.ligralec.place(x=300, y=130) self.preveri_zmagovalca(1) # print("Odstranil sem " + str(odstranjenih+1) + " kamenčkov iz " + str(izbrani+1) + " vrha.") def narisi_kamne(self, b=0): # print("narisi kamne") self.kamni = [[],[],[]] for i, j in enumerate(self.vrhovi): for k in range(j): self.kamni[i].append(Label(self, image=self.kamen, bd=0)) self.kamni[i][k].place(x=(100+110*k), y=(200+110*i)) par = (k+1, i+1) if b == 1: self.kamni[i][k].bind('<Button-1>', partial(self.izberi_kamen, par)) def unici_kamne(self): for vrh in self.kamni: for kamen in vrh: kamen.destroy() def naredi_potezo_clovek_text(self): izbrani = int(input("Izberi vrh: ")) odstranjenih = int(input("Stevilo kamenckov: ")) self.vrhovi[izbrani] -= odstranjenih # print(self.vrhovi) def izberi_kamen(self, par, j): # print("izbrali ste kamen ", par[0], " iz ", par[1], " vrha.") self.vrhovi[par[1]-1] = par[0]-1 # print(self.vrhovi) self.unici_kamne() self.narisi_kamne(0) self.ligralec.place_forget() self.lracunalnik.place(x=300, y=130) self.preveri_zmagovalca(0) self.after(1000, self.naredi_potezo_AI)
def __init__(self): super().__init__() # Initialisation des pions à la valeur initiale. self.pion1 = "X" self.pion2 = "O" # Titre de la fenêtre self.title("Ultimate TIC-TAC-TOE") # Pour changer taille minimum de fenêtre et taille centrer, # changer variable self.width_fen, self.height_fen. self.width_fen, self.height_fen = 430, 500 # Taille minimum de la fenêtre self.minsize(self.width_fen, self.height_fen) # Centrer la fenêtre. centreFen(self, self.width_fen, self.height_fen) # Création d'un canvas avec l'image "logo.gif" canvas = Canvas(self, width=280, height=100) self.img = PhotoImage(file="logo.gif") canvas.create_image(280, 100, anchor=SE, image=self.img) canvas.grid(row=0, columnspan=5, pady=10) # Libellé - Nouvelle Partie Label(self, text="Nouvelle partie", font=("Arial", 16), fg="#0080FF", justify=CENTER).grid( row=1, columnspan=5, padx = 20, pady = 5) separateur(20).grid(row=10,columnspan=5) # Sélection du type de partie avec bouton radio self.choixJoueur = IntVar() r1 = Radiobutton(self, text="Jouer avec l'ordinateur", variable = self.choixJoueur, value = 1, command=self.define_choix) r1.select() r1.grid(row=20, column=0) r2 = Radiobutton(self, text="Jouer avec un autre joueur", variable = self.choixJoueur, value = 2, command=self.define_choix) r2.grid(row=20, column=1) # Saisie du nom du joueur 1. f_j1 = Frame(self, borderwidth=1, padx=5, pady=5, relief=SUNKEN) f_j1.grid(row=30, columnspan=5, padx=5, pady=5) Label(f_j1, text="Nom joueur 1:").grid(row=1, column=0, sticky=E, padx = 5, pady = 5) self.nom_joueur1 = Entry(f_j1) self.nom_joueur1.grid(row=1,column=1) # Sélection du pion joueur 1. Le pion restant est automatiquement attribué au joueur 2. Label(f_j1, text="Choix de pion:").grid(row=1, column=2, padx=5) self.sel_pion=IntVar() p1 = Radiobutton(f_j1, indicatoron=0, width=5, text="X", variable=self.sel_pion, value=1, command=self.choix_pion) p1.grid(row=1, column=3, padx=2) p1.select() Radiobutton(f_j1, indicatoron=0, width=5, text="O", variable=self.sel_pion, value=2, command=self.choix_pion).grid(row=1, column=4, padx=2) # Saisie du nom du joueur 2. Apparaît seulement si on sélection 2 joueurs. Voir define_choix self.f_j2 = Frame(self, width=420, borderwidth=1, padx=5, pady=5, relief=SUNKEN) Label(self.f_j2, text="Nom joueur 2").grid(row=1, column=0, sticky=E, padx = 5, pady = 5) self.nom_joueur2 = Entry(self.f_j2, state="disabled") self.nom_joueur2.grid(row=1, column=1) self.label_pion2 = Label(self.f_j2, text="Pion Joueur 2 = O") self.label_pion2.grid(row=1, column=2, padx=5) # Information sur l'ordinateur. Disparaît si on choisi 2 joueurs. self.f_ordi = Frame(self, width=420, borderwidth=1, padx=5, pady=5, relief=SUNKEN) self.f_ordi.grid(row=40, columnspan=5, padx=5, pady=5) Label(self.f_ordi, text="Ordinateur = Colosse", font=("Arial", 12), fg="#0080FF")\ .grid(row=1, column=0, sticky=E, padx = 5, pady = 5) self.pion_ordi = Label(self.f_ordi, text="| Pion de l'ordinateur = O", font=("Arial", 12), fg="#0080FF") self.pion_ordi.grid(row=1, column=2) separateur(20).grid(row=50,columnspan=5) # Sélection de la force de l'ordinateur self.choixForce = IntVar() self.f1 = Radiobutton(self, indicatoron=0, width = 20, padx = 20, text="Facile", variable=self.choixForce, value=1, command=self.define_choix) self.f1.select() self.f1.grid(row=60, columnspan=5) self.f2 = Radiobutton(self, indicatoron=0, width = 20, padx = 20, text="Moyen", variable=self.choixForce, value=2, command=self.define_choix) self.f2.grid(row=61, columnspan=5) self.f3 = Radiobutton(self, indicatoron=0, width = 20, padx = 20, text="Difficile", variable=self.choixForce, value=3, command=self.define_choix) self.f3.grid(row=62, columnspan=5) separateur(40).grid(row=70, column=0) #Button pour démarrer la partie self.bt_start = Button(text="Démarrer", font=("Arial", 12), fg="green", command=self.demarrer_jeu) self.bt_start.grid(row=80, columnspan=5)
def mainDialog(self): self.basicframe = Frame(self.root) self.basicframe.grid() self.basicframe.configure(bg=bgcolor) self.fr = Frame(self.basicframe) self.fr.grid(row=0, column=0, sticky='new') # , sticky='W') self.fr.configure(bg=bgcolor) # Grid.rowconfigure(root, 0, weight=1) Grid.columnconfigure(root, 0, weight=1) self.emptyRow(0) Label(self.fr, textvariable=self.labelTop, justify='center', bg=bgcolor, font=("Calibri", 24) ).grid(row=1, column=0, columnspan=3, sticky='we') self.emptyRow(2) Label(self.fr, text='STATUS:', justify='left', anchor='w', bg=bgcolor, fg=statuscolor, font=("Calibri", 12) ).grid(row=3, column=0, sticky='we', padx=(5, 0)) self.statusLine = Label(self.fr, textvariable=self.statusString, justify='left', anchor='w', bg=bgcolor, fg=statuscolor, font=("Calibri", 14, "bold") ).grid(row=3, column=1, columnspan=2, sticky='we') self.emptyRow(4) self.butStartStop = Button(self.fr, textvariable=self.label10, command=self.startStop, bg=startstopbg[self.active], fg=startstopfg[self.active], font=("Calibri", 16, "bold"), width=10) self.butStartStop.grid(row=5, column=1, sticky='nsew') # AUTO / MANUAL self.my_var.set(1) self.butManual = Radiobutton(self.fr, text="MANUAL", variable=self.auto, value=0, width=15, justify='center', # bg=buttoncolor2, bg="moccasin", indicatoron=0) # self.exit_root) self.butManual.grid(row=5, column=0, sticky='ew', padx=(0, 10)) # self.butManual.configure(state='selected') self.butAuto = Radiobutton(self.fr, text="AUTO", variable=self.auto, value=1, width=15, justify='center', # bg=buttoncolor2, bg="moccasin", indicatoron=0) # self.exit_root) self.butAuto.grid(row=5, column=2, sticky='ew', padx=(10, 0)) self.emptyRow(6) self.emptyRow(7) # put Labels here Label(self.fr, textvariable=self.label31, justify='center', bg=bgcolor, fg=statuscolor, font=("Calibri", 10) ).grid(row=8, column=0, sticky='we') Label(self.fr, textvariable=self.label32, justify='center', bg=bgcolor, fg=statuscolor, font=("Calibri", 10) ).grid(row=8, column=1, sticky='we') Label(self.fr, textvariable=self.label33, justify='center', bg=bgcolor, fg=statuscolor, font=("Calibri", 10) ).grid(row=8, column=2, sticky='we') # input boxes: step start stop (mm) self.lowEntry = Entry(self.fr, width=20, bd=3, justify='right', bg=inputbox, fg=statuscolor) self.lowEntry.grid(row=9, column=0, sticky='we') # , columnspan=2) # SET DEFAULT LOW # self.lowEntry.delete(0,END) # self.lowEntry.insert(0, MINPOS) self.hiEntry = Entry(self.fr, width=20, bd=3, justify='right', bg=inputbox, fg=statuscolor) self.hiEntry.grid(row=9, column=1, sticky='we') # , columnspan=2) # SET DEFAULT HIGH # self.hiEntry.delete(0,END) # self.hiEntry.insert(0, MAXPOS) self.stepEntry = Entry(self.fr, width=20, bd=3, justify='right', bg=inputbox, fg=statuscolor) self.stepEntry.grid(row=9, column=2, sticky='we') # , columnspan=2) # put buttons for GOTO and MOVE self.butGotoLow = Button(self.fr, text="Go To Low", justify='center', bg=buttoncolor, command=self.gotoLow) self.butGotoLow.grid(row=10, column=0, sticky='we') self.butGotoHi = Button(self.fr, text="Go To High", justify='center', bg=buttoncolor, command=self.gotoHi) self.butGotoHi.grid(row=10, column=1, sticky='we') self.butMoveStep = Button(self.fr, text="Move a Step", justify='center', bg=buttoncolor, command=self.moveStep) self.butMoveStep.grid(row=10, column=2, sticky='we') self.emptyRow(11) Label(self.fr, text='EXTERNAL SENSORS', justify='left', anchor='w', bg=bgcolor, fg=statuscolor, font=("Calibri", 12) ).grid(row=12, column=0, columnspan=3, sticky='we', padx=(5, 0)) # function buttons # RIadok 12: Externals butIFM = Button(self.fr, text="Read IFM", width=15, justify='center', bg=buttoncolor, command=self.getIfm) # self.exit_root) butIFM.grid(row=13, column=0, sticky='we') self.labIfmStatus = Label(self.fr, textvariable=self.ifmStatus, justify='left', anchor='w', bg=bgcolor, fg=statuscolor, font=("Calibri", 12)) self.labIfmStatus.grid(row=13, column=1, columnspan=2, sticky='we', padx=(15, 0)) self.labIfmStatus.bind('<Button-1>', self.resetIfmStatus) butLVL = Button(self.fr, text="Read level", width=15, justify='center', bg=buttoncolor, command=self.getLevel) # self.exit_root) butLVL.grid(row=14, column=0, sticky='we') self.labLvlStatus = Label(self.fr, textvariable=self.lvlStatus, justify='left', anchor='w', bg=bgcolor, fg=statuscolor, font=("Calibri", 12)) self.labLvlStatus.grid(row=14, column=1, columnspan=2, sticky='we', padx=(15, 0)) self.labLvlStatus.bind('<Button-1>', self.resetLvlStatus) self.emptyRow(15) Label(self.fr, text='OBSERVER:', anchor='w', justify='left', bg=bgcolor, fg=statuscolor, font=("Calibri", 12) ).grid(row=16, column=0, sticky='we', padx=(5, 0)) self.entryObserver = Entry(self.fr, textvariable=self.observer, bg=inputbox, fg=statuscolor, font=("Calibri", 12), justify='left') self.entryObserver.grid(row=16, column=1, columnspan=2, sticky='we') # row 18> empty (or test connection) self.emptyRow(18) self.timeLabel = Label(self.fr, textvariable=self.timestring, anchor='w', bg=bgcolor, fg=statuscolor, font=("Calibri", 9)) self.timeLabel.grid(row=19, column=0) self.connLabel = Label(self.fr, textvariable=self.connstring, anchor='w', bg=bgcolor, fg=statuscolor, font=("Calibri", 9)) self.connLabel.grid(row=19, column=1) butexit = Button(self.fr, text="EXIT", width=15, justify='center', bg="black", fg="yellow", command=self.close, font=("Calibri", 14, "bold")) butexit.grid(row=19, column=2)
def init_gui(self): """init helper""" # setting up frames top_frame = Frame(self.root) mid_frame = Frame(self.root) radio_frame = Frame(self.root) res_frame = Frame(self.root) msg_frame = Frame(self.root) check_frame = Frame(self.root) history_frame = Frame(self.root) btn_frame = Frame(self.root) rating_frame = Frame(self.root) top_frame.pack(side=TOP, fill=X) mid_frame.pack(side=TOP, fill=X) history_frame.pack(side=TOP, fill=BOTH, expand=True) radio_frame.pack(side=TOP, fill=BOTH, expand=True) rating_frame.pack(side=TOP, fill=BOTH, expand=True) res_frame.pack(side=TOP, fill=BOTH, expand=True) check_frame.pack(side=TOP, fill=BOTH, expand=True) msg_frame.pack(side=TOP, fill=BOTH, expand=True) btn_frame.pack(side=TOP, fill=X) # Message ListBox rightscrollbar = Scrollbar(msg_frame) rightscrollbar.pack(side=RIGHT, fill=Y) bottomscrollbar = Scrollbar(msg_frame, orient=HORIZONTAL) bottomscrollbar.pack(side=BOTTOM, fill=X) self.lbMessages = Listbox( msg_frame, yscrollcommand=rightscrollbar.set, xscrollcommand=bottomscrollbar.set, bg="white" ) self.lbMessages.pack(expand=True, fill=BOTH) rightscrollbar.config(command=self.lbMessages.yview) bottomscrollbar.config(command=self.lbMessages.xview) # History ListBoxes rightscrollbar2 = Scrollbar(history_frame) rightscrollbar2.pack(side=RIGHT, fill=Y) bottomscrollbar2 = Scrollbar(history_frame, orient=HORIZONTAL) bottomscrollbar2.pack(side=BOTTOM, fill=X) self.showhistory = Listbox( history_frame, yscrollcommand=rightscrollbar2.set, xscrollcommand=bottomscrollbar2.set, bg="white" ) self.showhistory.pack(expand=True, fill=BOTH) rightscrollbar2.config(command=self.showhistory.yview) bottomscrollbar2.config(command=self.showhistory.xview) self.showhistory.bind("<Double-Button-1>", self.select_recent_file) self.set_history_window() # status bar self.status = Label(self.root, text="", bd=1, relief=SUNKEN, anchor=W) self.status.pack(side=BOTTOM, fill=X) # labels self.lblRatingLabel = Label(rating_frame, text="Rating:") self.lblRatingLabel.pack(side=LEFT) self.lblRating = Label(rating_frame, textvariable=self.rating) self.lblRating.pack(side=LEFT) Label(mid_frame, text="Recently Used:").pack(side=LEFT) Label(top_frame, text="Module or package").pack(side=LEFT) # file textbox self.txtModule = Entry(top_frame, background="white") self.txtModule.bind("<Return>", self.run_lint) self.txtModule.pack(side=LEFT, expand=True, fill=X) # results box rightscrollbar = Scrollbar(res_frame) rightscrollbar.pack(side=RIGHT, fill=Y) bottomscrollbar = Scrollbar(res_frame, orient=HORIZONTAL) bottomscrollbar.pack(side=BOTTOM, fill=X) self.results = Listbox( res_frame, yscrollcommand=rightscrollbar.set, xscrollcommand=bottomscrollbar.set, bg="white", font="Courier" ) self.results.pack(expand=True, fill=BOTH, side=BOTTOM) rightscrollbar.config(command=self.results.yview) bottomscrollbar.config(command=self.results.xview) # buttons Button(top_frame, text="Open", command=self.file_open).pack(side=LEFT) Button(top_frame, text="Open Package", command=(lambda: self.file_open(package=True))).pack(side=LEFT) self.btnRun = Button(top_frame, text="Run", command=self.run_lint) self.btnRun.pack(side=LEFT) Button(btn_frame, text="Quit", command=self.quit).pack(side=BOTTOM) # radio buttons self.information_box = IntVar() self.convention_box = IntVar() self.refactor_box = IntVar() self.warning_box = IntVar() self.error_box = IntVar() self.fatal_box = IntVar() i = Checkbutton( check_frame, text="Information", fg=COLORS["(I)"], variable=self.information_box, command=self.refresh_msg_window, ) c = Checkbutton( check_frame, text="Convention", fg=COLORS["(C)"], variable=self.convention_box, command=self.refresh_msg_window, ) r = Checkbutton( check_frame, text="Refactor", fg=COLORS["(R)"], variable=self.refactor_box, command=self.refresh_msg_window ) w = Checkbutton( check_frame, text="Warning", fg=COLORS["(W)"], variable=self.warning_box, command=self.refresh_msg_window ) e = Checkbutton( check_frame, text="Error", fg=COLORS["(E)"], variable=self.error_box, command=self.refresh_msg_window ) f = Checkbutton( check_frame, text="Fatal", fg=COLORS["(F)"], variable=self.fatal_box, command=self.refresh_msg_window ) i.select() c.select() r.select() w.select() e.select() f.select() i.pack(side=LEFT) c.pack(side=LEFT) r.pack(side=LEFT) w.pack(side=LEFT) e.pack(side=LEFT) f.pack(side=LEFT) # check boxes self.box = StringVar() # XXX should be generated report = Radiobutton( radio_frame, text="Report", variable=self.box, value="Report", command=self.refresh_results_window ) rawMet = Radiobutton( radio_frame, text="Raw metrics", variable=self.box, value="Raw metrics", command=self.refresh_results_window ) dup = Radiobutton( radio_frame, text="Duplication", variable=self.box, value="Duplication", command=self.refresh_results_window ) ext = Radiobutton( radio_frame, text="External dependencies", variable=self.box, value="External dependencies", command=self.refresh_results_window, ) stat = Radiobutton( radio_frame, text="Statistics by type", variable=self.box, value="Statistics by type", command=self.refresh_results_window, ) msgCat = Radiobutton( radio_frame, text="Messages by category", variable=self.box, value="Messages by category", command=self.refresh_results_window, ) msg = Radiobutton( radio_frame, text="Messages", variable=self.box, value="Messages", command=self.refresh_results_window ) report.select() report.grid(column=0, row=0, sticky=W) rawMet.grid(column=1, row=0, sticky=W) dup.grid(column=2, row=0, sticky=W) msg.grid(column=3, row=0, sticky=E) stat.grid(column=0, row=1, sticky=W) msgCat.grid(column=1, row=1, sticky=W) ext.grid(column=2, row=1, columnspan=2, sticky=W) # dictionary for check boxes and associated error term self.msg_type_dict = { "I": lambda: self.information_box.get() == 1, "C": lambda: self.convention_box.get() == 1, "R": lambda: self.refactor_box.get() == 1, "E": lambda: self.error_box.get() == 1, "W": lambda: self.warning_box.get() == 1, "F": lambda: self.fatal_box.get() == 1, } self.txtModule.focus_set()
def __init__(self, master): self.file_path = None self.RSM = None #Defaul scale for RSM and Linescan is logarithmic self.rsm_scale = StringVar() self.rsm_scale.set("log") self.line_scale = StringVar() self.line_scale.set("log") #Default parameters for RSM self.rsm_parallel_lower = -0.01 self.rsm_parallel_upper = 0 self.rsm_normal_lower = 0.5 self.rsm_normal_upper = 0.52 #Default parameters for linescan self.origin_parallel = -0.0007 self.origin_normal = 0.51192 self.linescan_angle = 0.0 self.linescan_width = 0.000015 self.window_frame = Frame(master, bd=2, relief=GROOVE) self.fileselect_button = Button(self.window_frame, text="Select XRDML file", command=self.select_file) self.busy_label = Label(self.window_frame, text="") self.savebutton1 = Button(self.window_frame, text="Save RSM", command=lambda: self.savefigure(self.rsm_plot_figure)) self.savebutton2 = Button(self.window_frame, text="Save Linescan", command=lambda: self.savefigure(self.linescan_plot_figure)) self.rsm_frame = Frame(self.window_frame, bd=2, relief=GROOVE) self.rsm_label = Label(self.rsm_frame, text="Amerigo - RSM Viewer Space Map") self.rsm_parallel_lower_label = Label(self.rsm_frame, text="Lower q-parallel bound") self.rsm_parallel_lower_entry = Entry(self.rsm_frame) self.rsm_parallel_upper_label = Label(self.rsm_frame, text="Upper q-parallel bound") self.rsm_parallel_upper_entry = Entry(self.rsm_frame) self.rsm_normal_lower_label = Label(self.rsm_frame, text="Lower q-normal bound") self.rsm_normal_lower_entry = Entry(self.rsm_frame) self.rsm_normal_upper_label = Label(self.rsm_frame, text="Upper q-normal bound") self.rsm_normal_upper_entry = Entry(self.rsm_frame) self.rsm_sclae_linear = Radiobutton(self.rsm_frame, text="Linear", variable=self.rsm_scale, value="linear") self.rsm_sclae_log = Radiobutton(self.rsm_frame, text="Logarithmic", variable=self.rsm_scale, value="log") self.create_rsm_button = Button(self.rsm_frame, text="Create RSM", command=self.create_rsm) self.linescan_frame = Frame(self.window_frame, bd=2, relief=GROOVE) self.linescan_label = Label(self.linescan_frame, text="Line Scan") self.origin_parallel_label = Label(self.linescan_frame, text="Point of origin parallel coordinate") self.origin_normal_label = Label(self.linescan_frame, text="Point of origin normal coordinate") self.linescan_angle_label = Label(self.linescan_frame, text="Angle to parallel axis in degrees") self.linescan_width_label = Label(self.linescan_frame, text="Linescan thickness intervall") self.origin_parallel_entry = Entry(self.linescan_frame) self.origin_normal_entry = Entry(self.linescan_frame) self.linescan_angle_entry = Entry(self.linescan_frame) self.linescan_width_entry = Entry(self.linescan_frame) self.create_linescan_button = Button(self.linescan_frame, text="Create linescan", command=self.create_line_scan) self.line_scale_log = Radiobutton(self.linescan_frame, text="Logarithmic", variable=self.line_scale, value="log") self.line_scale_linear = Radiobutton(self.linescan_frame, text="Linear", variable=self.line_scale, value="linear") self.rsm_plot_frame = Frame(master, relief=GROOVE, bd=2) self.rsm_plot_figure = Figure() self.rsm_canvas = FigureCanvasTkAgg(self.rsm_plot_figure, master=self.rsm_plot_frame) self.rsm_toolbar = NavigationToolbar2TkAgg(self.rsm_canvas, self.rsm_plot_frame) self.rsm_toolbar.update() self.rsm_canvas.show() self.linescan_plot_frame = Frame(master, relief=GROOVE, bd=2) self.linescan_plot_figure = Figure() self.linescan_canvas = FigureCanvasTkAgg(self.linescan_plot_figure, master=self.linescan_plot_frame) self.linescan_toolbar = NavigationToolbar2TkAgg(self.linescan_canvas, self.linescan_plot_frame) self.linescan_toolbar.update() self.linescan_canvas.show() self.place_widgets()
class MyGUI: rate1 = 60 def __init__(self, master): self.master = master master.title("ICP WaveForm Control") master.geometry("480x320") self.modelone = Radiobutton(master, text = "Normal", bg = 'seashell3', indicatoron = 0, value =1, variable = 1, command = self.modelone) ## self.modelone.pack(fill = X, expand = 1) self.modelone.grid(row = 1, column = 0, sticky ='WNS', padx = 0, pady = 10) self.modeltwo = Radiobutton(master, text = "Leveled",indicatoron = 0, value = 2, variable = 1, bg = 'seashell3',command = self.modeltwo) ## self.modeltwo.pack(fill = X, expand = 1) self.modeltwo.grid(row=2, column=0,sticky = 'WNS', padx =0, pady = 10) ## mi = PhotoImage(" ## self.modeltwo.config( self.modelthree = Radiobutton(master, text = "Abnormal", indicatoron = 0, value = 3, variable = 1, bg = 'seashell3', command = self.modelthree) ## self.modelthree.pack(fill = X, expand = 1) self.modelthree.grid(row=3, column=0, sticky ='WNS', padx = 0, pady = 10) self.donebutton = Radiobutton(master, text = "Zero", indicatoron = 0, variable = 1, value = 4, bg = 'seashell3', command = self.done) ## self.donebutton.pack(fill = X, expand = 1) self.donebutton.grid(row=4, column=0, sticky ='WNS', padx = 0, pady = 10) self.quitbutton = Radiobutton(master, text = "Quit", indicatoron = 0, value = 5, variable = 1, bg = 'seashell3', command = self.quit) ## self.quitbutton.pack(fill = X, expand = 1) self.quitbutton.grid(row=5, column=0, sticky ='EWNS', padx = 0, pady = 10) Label(master, text = "", width = 5, height = 5).grid(row = 2, column = 4, sticky = "WNS") self.DisplayButton = Button(master, text = self.rate1) self.DisplayButton.grid(column = 1, row = 2, sticky = "WNS") self.Plus1Button = Button(master, text = "+1", command=self.plus1, bg="green") self.Plus1Button.grid(column = 1, row = 1, sticky = "WNS") self.Neg1Button = Button(master, text = "-1", command=self.neg1, bg="green") self.Neg1Button.grid(column = 1, row = 3, sticky = "WNS") self.pid = -1 def plus1(self): self.done() self.rate1 += 5 self.DisplayButton["text"]=str(self.rate1) def neg1(self): self.done() self.rate1 -= 5 self.DisplayButton["text"]=str(self.rate1) def modelone(self): self.done() self.process = subprocess.Popen('python modelone.py {}'.format(self.rate1), shell=True, preexec_fn=os.setsid) self.pid = self.process.pid def modeltwo(self): self.done() self.process = subprocess.Popen('python modeltwo.py {}'.format(self.rate1), shell=True, preexec_fn=os.setsid) self.pid = self.process.pid def modelthree(self): self.done() self.process = subprocess.Popen('python modelthree.py {}'.format(self.rate1), shell=True, preexec_fn=os.setsid) self.pid = self.process.pid def done(self): if self.pid > 0: os.killpg(os.getpgid(self.pid), signal.SIGTERM) self.pid = -1 def quit(self): self.done() self.master.quit()
def mainDialog(self): self.basicframe = Frame(self.root) self.basicframe.grid() self.basicframe.configure(bg=bgcolor) self.fr = Frame(self.basicframe) self.fr.grid(row=0, column=0, sticky='new') # , sticky='W') self.fr.configure(bg=bgcolor) # Grid.rowconfigure(root, 0, weight=1) Grid.columnconfigure(root, 0, weight=1) self.emptyRow(0) Label(self.fr, textvariable=self.labelTop, justify='center', bg=bgcolor, font=("Calibri", 24) ).grid(row=1, column=0, columnspan=3, sticky='we') self.emptyRow(2) Label(self.fr, text='STATUS:', justify='left', anchor='w', bg=bgcolor, fg=statuscolor, font=("Calibri", 12) ).grid(row=3, column=0, sticky='we', padx=(5, 0)) self.statusLine = Label(self.fr, textvariable=self.statusString, justify='left', anchor='w', bg=bgcolor, fg=statuscolor, font=("Calibri", 14, "bold") ).grid(row=3, column=1, columnspan=2, sticky='we') self.emptyRow(4) # AUTO / MANUAL self.my_var.set(1) self.buttonManual = Radiobutton(self.fr, text="MANUAL", variable=self.auto, value=0, width=15, justify='center', # bg=buttoncolor2, bg="moccasin", indicatoron=0) # self.exit_root) self.buttonManual.grid(row=5, column=0, sticky='ew', padx=(0, 10)) # self.buttonManual.configure(state='selected') self.buttonAuto = Radiobutton(self.fr, text="AUTO", variable=self.auto, value=1, width=15, justify='center', # bg=buttoncolor2, bg="moccasin", indicatoron=0) # self.exit_root) self.buttonAuto.grid(row=5, column=2, sticky='ew', padx=(10, 0)) self.emptyRow(6) #should be disabled if initialized already self.buttonInitialize = Button(self.fr, text='Initialize', justify='center', bg=buttoncolor, command=self.initialize) self.buttonInitialize.grid(row=7, column=0, sticky='nsew') self.buttonStartStop = Button(self.fr, textvariable=self.label11, command=self.startStop, bg=startstopbg[self.active], fg=startstopfg[self.active], font=("Calibri", 16, "bold"), width=10) self.buttonStartStop.grid(row=7, column=1, sticky='nsew') self.buttonPause = Button(self.fr, textvariable=self.label12, justify='center', bg=buttoncolor, state={0: 'disabled', 1: 'enabled'}[self.auto], command=self.pause) self.buttonPause.grid(row=7, column=2, sticky='nsew') self.emptyRow(8) # put Labels here Label(self.fr, textvariable=self.label31, justify='center', bg=bgcolor, fg=statuscolor, font=("Calibri", 10) ).grid(row=8, column=0, sticky='we') Label(self.fr, textvariable=self.label32, justify='center', bg=bgcolor, fg=statuscolor, font=("Calibri", 10) ).grid(row=8, column=1, sticky='we') Label(self.fr, textvariable=self.label33, justify='center', bg=bgcolor, fg=statuscolor, font=("Calibri", 10) ).grid(row=8, column=2, sticky='we') # input boxes: step start stop (mm) self.lowEntry = Entry(self.fr, width=20, bd=3, justify='right', bg=inputbox, fg=statuscolor) self.lowEntry.grid(row=9, column=0, sticky='we') # , columnspan=2) # SET DEFAULT LOW # self.lowEntry.delete(0,END) # self.lowEntry.insert(0, MINPOS) self.hiEntry = Entry(self.fr, width=20, bd=3, justify='right', bg=inputbox, fg=statuscolor) self.hiEntry.grid(row=9, column=1, sticky='we') # , columnspan=2) # SET DEFAULT HIGH # self.hiEntry.delete(0,END) # self.hiEntry.insert(0, MAXPOS) self.stepEntry = Entry(self.fr, width=20, bd=3, justify='right', bg=inputbox, fg=statuscolor) self.stepEntry.grid(row=9, column=2, sticky='we') # , columnspan=2) # put buttons for GOTO and MOVE self.butGotoLow = Button(self.fr, text="Go To Low", justify='center', bg=buttoncolor, command=self.gotoLow) self.butGotoLow.grid(row=10, column=0, sticky='we') self.butGotoHi = Button(self.fr, text="Go To High", justify='center', bg=buttoncolor, command=self.gotoHi) self.butGotoHi.grid(row=10, column=1, sticky='we') self.butMoveStep = Button(self.fr, text="Move a Step", justify='center', bg=buttoncolor, command=self.moveStep) self.butMoveStep.grid(row=10, column=2, sticky='we') self.emptyRow(11) Label(self.fr, text='EXTERNAL SENSORS', justify='left', anchor='w', bg=bgcolor, fg=statuscolor, font=("Calibri", 12) ).grid(row=12, column=0, columnspan=3, sticky='we', padx=(5, 0)) # function buttons # RIadok 13-16: Externals # Interferometer buttonIfm = Button(self.fr, text="Read IFM", width=15, justify='center', bg=buttoncolor, command=self.getIfm) # self.exit_root) buttonIfm.grid(row=13, column=0, sticky='we') self.labelIfmStatus = Label(self.fr, textvariable=self.ifmStatus, justify='left', anchor='w', bg=bgcolor, fg=statuscolor, font=("Calibri", 12)) self.labelIfmStatus.grid(row=13, column=1, columnspan=2, sticky='we', padx=(15, 0)) self.labelIfmStatus.bind('<Button-1>', self.resetIfmStatus) # Digital level (Leica /Trimble) buttonLevel = Button(self.fr, text="Read Level", width=15, justify='center', bg=buttoncolor, command=self.getLevel) # self.exit_root) buttonLevel.grid(row=14, column=0, sticky='we') self.labelLevelStatus = Label(self.fr, textvariable=self.levelStatus, justify='left', anchor='w', bg=bgcolor, fg=statuscolor, font=("Calibri", 12)) self.labelLevelStatus.grid(row=14, column=1, columnspan=2, sticky='we', padx=(15, 0)) self.labelLevelStatus.bind('<Button-1>', self.resetLevelStatus) # Nivel - inclinometer buttonNivel = Button(self.fr, text="Read Nivel", width=15, justify='center', bg=buttoncolor, command=self.getNivel) # self.exit_root) buttonNivel.grid(row=15, column=0, sticky='we') self.labelNivelStatus = Label(self.fr, textvariable=self.nivelStatus, justify='left', anchor='w', bg=bgcolor, fg=statuscolor, font=("Calibri", 12)) self.labelNivelStatus.grid(row=15, column=1, columnspan=2, sticky='we', padx=(15, 0)) self.labelNivelStatus.bind('<Button-1>', self.resetNivelStatus) # Thermometer line buttonThermo = Button(self.fr, text="Read Thermo", width=15, justify='center', bg=buttoncolor, command=self.getThermo) # self.exit_root) buttonThermo.grid(row=16, column=0, sticky='we') self.labelThermoStatus = Label(self.fr, textvariable=self.thermoStatus, justify='left', anchor='w', bg=bgcolor, fg=statuscolor, font=("Calibri", 12)) self.labelThermoStatus.grid(row=16, column=1, columnspan=2, sticky='we', padx=(15, 0)) self.labelThermoStatus.bind('<Button-1>', self.resetThermoStatus) self.emptyRow(17) Label(self.fr, text='OBSERVER:', anchor='w', justify='left', bg=bgcolor, fg=statuscolor, font=("Calibri", 12) ).grid(row=19, column=0, sticky='we', padx=(5, 0)) self.entryObserver = Entry(self.fr, textvariable=self.observer, bg=inputbox, fg=statuscolor, font=("Calibri", 12), justify='left') self.entryObserver.grid(row=19, column=1, columnspan=2, sticky='we') # row 18> empty (or test connection) self.emptyRow(20) if ADMIN_MODE: # port, message, checksum_type?, resulting checksum?, submit, response self.portEntry = Entry(self.fr, width=20, bd=3, justify='left', bg=inputbox, fg=statuscolor) self.portEntry.grid(row=21, column=0, sticky='we') Label(self.fr, text='PORT', anchor='w', justify='left', bg=bgcolor, fg=statuscolor, font=("Calibri", 12) ).grid(row=22, column=0, sticky='we', padx=(5, 0)) self.messageEntry = Entry(self.fr, width=20, bd=3, justify='left', bg=inputbox, fg=statuscolor) self.messageEntry.grid(row=21, column=1, sticky='we') Label(self.fr, text='MESSAGE', anchor='w', justify='left', bg=bgcolor, fg=statuscolor, font=("Calibri", 12) ).grid(row=22, column=1, sticky='we', padx=(5, 0)) self.portChecksumType = Entry(self.fr, width=20, bd=3, justify='left', bg=inputbox, fg=statuscolor) self.portChecksumType.grid(row=21, column=2, sticky = 'we') Label(self.fr, text='CHKSUM TYPE', anchor='w', justify='left', bg=bgcolor, fg=statuscolor, font=("Calibri", 12) ).grid(row=22, column=2, sticky='we', padx=(5, 0)) self.chksumLabel = Label(self.fr, textvariable=self.chksumText, anchor='w', bg=bgcolor, fg=statuscolor, font=("Calibri", 9)) self.chksumLabel.grid(row=23, column=2) buttonSubmit = Button(self.fr, text="SUBMIT", width=15, justify='center', bg="black", fg="yellow", command=self.submit, font=("Calibri", 14, "bold")) buttonSubmit.grid(row=23, column=0) self.responseLabel = Label(self.fr, textvariable=self.responseText, anchor='w', bg=bgcolor, fg=statuscolor, font=("Calibri", 9)) self.responseLabel.grid(row=23, column=1) self.emptyRow(24) lastLine = 21 if not ADMIN_MODE else 25 self.timeLabel = Label(self.fr, textvariable=self.timestring, anchor='w', bg=bgcolor, fg=statuscolor, font=("Calibri", 9)) self.timeLabel.grid(row=lastLine, column=0) self.connLabel = Label(self.fr, textvariable=self.connstring, anchor='w', bg=bgcolor, fg=statuscolor, font=("Calibri", 9)) self.connLabel.grid(row=lastLine, column=1) butexit = Button(self.fr, text="EXIT", width=15, justify='center', bg="black", fg="yellow", command=self.close, font=("Calibri", 14, "bold")) butexit.grid(row=lastLine, column=2)
class Main: def __init__(self, master): # we will define everything in the UI below logger.info("Program start") self.master = master self.master.wm_title("Lautaloader v.1.03") # title of window self.master.resizable(width=FALSE, height=FALSE) # window is not resizable self.master.geometry('420x240') # resolution of the window in pixels self.master.grid_propagate(False) # window will not resize in any case self.r_selection = IntVar() # these are radiobuttons and checkbuttons self.c1_selection = IntVar() self.c2_selection = IntVar() self.c1_selection.set(0) # checkbuttons will be off at launch self.c2_selection.set(0) self.r_selection.set(1) # we need one radiobutton selected at start self.status_text = StringVar() # status text is visible at the bottom of GUI self.status_text.set('Ready to work') # we can (and will) set the status text like this self.save_folder = '' # we will save into this folder self.filenames = [] # this is our folder filenames list self.url_text = StringVar() self.num_pics = 0 self.num_mp4 = 0 self.num_mp3 = 0 self.image_url = '' self.name_of_file = '' self.res = '' self.imagefile = '' self.filesize = '' self.imagewritten = False self.read_timeout = 1.0 self.headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) ' 'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36', 'Upgrade-Insecure-Requests': '1', 'Referer': '', 'DNT': '1', 'Accept-Language': 'fi-FI,fi;q=0.8,en-US;q=0.6,en;q=0.4', 'Accept-Encoding': 'gzip, deflate, sdch', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8' } # need to send some headers or server refuses connection self.lf = LabelFrame(master, text=' Get ') self.lf.grid(row=1, column=1, rowspan=4) self.lf2 = LabelFrame(master, text=' Options ') self.lf2.grid(row=1, column=2) self.R1 = Radiobutton(self.lf, text="All", variable=self.r_selection, value=1) self.R1.grid(row=1, column=1, sticky=W) self.R2 = Radiobutton(self.lf, text="only img", variable=self.r_selection, value=2) self.R2.grid(row=2, column=1, sticky=W) self.R3 = Radiobutton(self.lf, text="only mp4", variable=self.r_selection, value=3) self.R3.grid(row=3, column=1, sticky=W) self.R4 = Radiobutton(self.lf, text="only mp3", variable=self.r_selection, value=4) self.R4.grid(row=4, column=1, sticky=W) self.C1 = Checkbutton(self.lf2, text="Create new filenames", variable=self.c1_selection, state=NORMAL, onvalue=1, offvalue=0) self.C1.grid(row=1, column=2, sticky=W) self.C2 = Checkbutton(self.lf2, text="Overwrite if found", variable=self.c2_selection, state=NORMAL, onvalue=1, offvalue=0) self.C2.grid(row=2, column=2, sticky=W) self.folder_label = Label(master, text="Folder: ") self.folder_label.grid(row=5, sticky=E) self.url_label = Label(root, text="URL: ") self.url_label.grid(row=6, sticky=E) self.folder_entry = Entry(master, textvariable=self.save_folder, state="readonly", width=50) self.folder_entry.grid(row=5, column=1, columnspan=2) self.url_entry = Entry(master, textvariable=self.url_text, width=50) self.url_entry.grid(row=6, column=1, columnspan=2) self.selectbutton = Button(master, text="Select..", state=NORMAL, command=self.get_folder) self.selectbutton.grid(row=5, column=3, sticky=W) self.openfolderbutton = Button(master, text="Open folder", state=DISABLED, command=self.openfolder) self.openfolderbutton.grid(row=3, column=2, sticky=W, padx=22) self.urlbutton = Button(master, text="Download", state=DISABLED, command=self.logic) self.urlbutton.grid(row=6, column=3, sticky=W) self.status = Label(master, textvariable=self.status_text, wraplength=300) self.status.grid(row=9, columnspan=4, sticky=W) self.progressbar = Progressbar(master, orient="horizontal", length=100, mode="determinate") self.progressbar.grid(row=8, sticky='we', columnspan=3, pady=3) self.manage_config() # process through config file self.url_1 = config.get('basic_config', 'url_1') logging.debug("url_1 set to %s" % self.url_1) self.url_2 = config.get('basic_config', 'url_2') logging.debug("url_2 set to %s" % self.url_2) if self.save_folder != '': # if save folder is not empty, we probably have a valid folder self.urlbutton['state'] = 'normal' # so we can enable urlbutton already self.openfolderbutton['state'] = 'normal' # and we can also enable open folder button def manage_config(self): if not os.path.isfile(os.path.expanduser("~\\documents\\lloader_cfg.ini")): with open((os.path.expanduser("~\\documents\\lloader_cfg.ini")), 'w') as cfgfile: config.add_section('basic_config') # cfg file not exists so we make it config.set('basic_config', 'save_folder', self.save_folder) config.set('basic_config', 'html_tag1', ".filecontainer figcaption a") config.set('basic_config', 'html_tag2', ".filecontainer .file a") config.set('basic_config', 'url_1', "ylilauta.org") config.set('basic_config', 'url_2', "www.ylilauta.org") # .filecontainer .file a = ALL images (np included) but not mp4 # .filecontainer figcaption a = not np images, but all uploaded images & mp4 config.write(cfgfile) logger.debug("Created a config file") else: try: config.read(os.path.expanduser('~\\documents\\lloader_cfg.ini')) self.folder_entry['state'] = 'normal' # make the folder field writable self.folder_entry.delete(0, END) self.save_folder = config.get('basic_config', 'save_folder') # get save folder from file self.folder_entry.insert(0, self.save_folder) # write to folder field self.folder_entry['state'] = 'readonly' # make it read-only again logger.debug("Read from config") except (IOError, OSError): logger.exception("Config error") except (configparser.MissingSectionHeaderError, configparser.NoSectionError): # correct section not found from file os.remove(os.path.expanduser("~\\documents\\lloader_cfg.ini")) self.manage_config() # delete file and try to create it from start def get_folder(self): dir_opt = options = {} # define options for get folder function options['initialdir'] = self.save_folder options['mustexist'] = False options['parent'] = self.master options['title'] = 'Choose a directory' self.save_folder = filedialog.askdirectory(**dir_opt) # actual function to get the folder name with open((os.path.expanduser("~\\documents\\lloader_cfg.ini")), 'w') as cfgfile: config.set('basic_config', 'save_folder', self.save_folder) config.write(cfgfile) # write new save folder to config file self.folder_entry['state'] = 'normal' # make the folder field writable self.folder_entry.delete(0, END) self.folder_entry.insert(0, self.save_folder) # update folder field self.folder_entry['state'] = 'readonly' # make it read-only again self.clear_savefolder_list() self.openfolderbutton['state'] = 'normal' # we can now press the open folder and url buttons self.urlbutton['state'] = 'normal' # because we have defined a save folder def openfolder(self): os.startfile(self.save_folder) # opens the save folder def clear_savefolder_list(self): del self.filenames[:] # clears the list of files in a folder self.filenames.append(next(os.walk(self.save_folder))[2]) # adds every file in folder to list def check_for_url(self): parse = urlparse(self.url_texti.lower()) # checks if url is ylilauta logging.debug("url started with %s" % parse.netloc) if (parse.netloc.startswith(self.url_1) or parse.netloc.startswith(self.url_2)): return True else: return False def is_image(self): if (self.image_url.lower().endswith(".jpg") or self.image_url.lower().endswith(".jpeg") or self.image_url.lower().endswith(".png")): # link seems to be image return True else: return False def is_mp4(self): if self.image_url.lower().endswith(".mp4"): # link ends in mp4 so its mp4 return True else: return False def is_mp3(self): if self.image_url.lower().endswith(".mp3"): # link ends in mp3 so its mp3 return True else: return False def we_want_it_anyway(self): if self.c2_selection.get() == 1: # checkbutton2 is selected so we want all files return True else: return False def getting_both(self): if self.r_selection.get() == 1: # first radio button is selected so dl both return True else: return False def getting_img(self): if self.r_selection.get() == 2: # second radio button is selected so dl images only return True else: return False def getting_mp4(self): if self.r_selection.get() == 3: # third radio button is selected so dl mp4 only return True else: return False def getting_mp3(self): if self.r_selection.get() == 4: # fourth radio button is selected so we get mp3 only return True else: return False def rename_file(self): get_filetype = os.path.splitext(os.path.basename(self.image_url))[1] # get filetype new_file_name_start = '' for i in range(0, 15): new_file_name_start += str(random.randint(0, 9)) # create random string of numbers self.name_of_file = (new_file_name_start + get_filetype) # create the whole new name def write_file(self): self.status_text.set('Downloading %s' % self.name_of_file) logger.info('Downloading %s' % self.name_of_file) self.master.update() self.res = requests.get(self.image_url) self.res.raise_for_status() try: with open(os.path.join(self.save_folder, self.name_of_file), 'wb') as self.imagefile: for chunk in self.res.iter_content(100000): self.imagefile.write(chunk) self.imagewritten = True except IOError: logger.exception("Exception with file write") self.status_text.set('File error') self.master.update() def file_get_logic(self): self.clear_savefolder_list() # need to update this list between files self.imagewritten = False # need to change this here because if same thread has same pictures if self.c1_selection.get() == 1: # if want new random name self.rename_file() else: self.name_of_file = os.path.basename(self.image_url) # using default filename if self.name_of_file in self.filenames[0]: # file exists if self.c2_selection.get() == 1: # we want to overwrite self.write_file() else: pass elif self.name_of_file not in self.filenames[0]: # file does not exist in folder self.write_file() # so we take it in self.master.update() def connect_logic(self): try: self.res = requests.get(self.url_texti, headers=self.headers, timeout=(10.0, self.read_timeout)) self.res.raise_for_status() except (requests.exceptions.ReadTimeout, requests.exceptions.HTTPError): logger.exception("Connection exception") self.status_text.set("Network error %s" % self.res.status_code) self.master.update() def logic(self): self.clear_savefolder_list() self.num_pics = 0 # make these 0 because we just called the function self.num_mp4 = 0 self.num_mp3 = 0 self.imagewritten = False self.url_texti = '' self.progressbar["value"] = 0 done = False if self.url_text != '': self.url_texti = (self.url_text.get()) # if url text is not empty we will set it to variable if not self.url_text or self.check_for_url() is False: # if url is wrong or empty self.status_text.set('URL not supported') logger.debug("URL is false: %s" % self.url_texti) while not done and self.check_for_url() is True: self.urlbutton['state'] = 'disabled' # disable buttons so they cant be pressed while run self.selectbutton['state'] = 'disabled' # we will enable them again in the end self.R1['state'] = 'disabled' self.R2['state'] = 'disabled' self.R3['state'] = 'disabled' self.R4['state'] = 'disabled' self.C1['state'] = 'disabled' self.C2['state'] = 'disabled' self.url_entry['state'] = 'readonly' self.status_text.set(("Getting from %s" % self.url_texti)) self.progressbar['value'] = 0 self.master.update() self.connect_logic() soup = bs4.BeautifulSoup(self.res.text, 'html.parser') # create soup total_stuff = 0 html_tag1 = config.get('basic_config', 'html_tag1') # we will fetch from these tags html_tag2 = config.get('basic_config', 'html_tag2') list_of_links = [] for imglink in soup.select(html_tag1): # grab items from tags and put them to list if imglink.get('href') not in list_of_links: list_of_links.append(str(imglink.get('href'))) for imglink in soup.select(html_tag2): if imglink.get('href') not in list_of_links: list_of_links.append(str(imglink.get('href'))) try: list_of_links = [x for x in list_of_links if x != "None"] # clear "none"s from list except ValueError: # there is no "none" in list pass total_stuff = len(list_of_links) # variable helps with progressbar logger.debug("total stuff is: %s" % total_stuff) for link in list_of_links: # iterate through list of links link = 'http:' + link # make item a valid link self.image_url = link # file get logic still uses global variable lol if (link.lower().endswith('.jpg') or link.lower().endswith('png') or link.lower().endswith('jpeg')): # we have an image if self.getting_both() or self.getting_img(): # we want an image self.file_get_logic() # we get an image if self.imagewritten: # logic is complete and image is written self.num_pics += 1 if link.lower().endswith('.mp4'): # same as above but with mp4 if self.getting_both() or self.getting_mp4(): self.file_get_logic() if self.imagewritten: self.num_mp4 += 1 if link.lower().endswith('.mp3'): if self.getting_both() or self.getting_mp3(): self.file_get_logic() if self.imagewritten: self.num_mp3 += 1 self.progressbar['value'] += 100 / total_stuff # progressbar fills self.status_text.set('Downloaded %s images, %s mp4, %s mp3.' % (self.num_pics, self.num_mp4, self.num_mp3)) self.urlbutton['state'] = 'normal' self.url_entry['state'] = 'normal' self.selectbutton['state'] = 'normal' self.R1['state'] = 'normal' self.R2['state'] = 'normal' self.R3['state'] = 'normal' self.R4['state'] = 'normal' self.C1['state'] = 'normal' self.C2['state'] = 'normal' # we have enabled all buttons to be used again logger.info("Done.") break logging.shutdown()
def create_voices(self): voice_ids = ['1', '2', '3', '4'] SCALES = OrderedDict([ ('pan_pos', {'min': -1, 'max': 1, 'start': 0.5, 'res': 0.001}), ('volume', {'min': 0, 'max': 1, 'start': 0.666, 'res': 0.001}), ('slide_duration_msecs', {'min': 0, 'max': 2000, 'start': 60, 'res': 1}), ('slide_duration_prop', {'min': 0, 'max': 2, 'start': 0.666, 'res': 0.001}), ('binaural_diff', {'min': 0, 'max': 66, 'start': 0.2, 'res': 0.01}) ]) for vid in voice_ids: counter = 0 for sca in SCALES: name = 'voice_' + vid + '_' + sca setattr(self, 'min_' + name, SCALES[sca]['min']) setattr(self, 'max_' + name, SCALES[sca]['max']) this_sca = Scale(self, label=sca, orient=HORIZONTAL, from_=getattr(self, 'min_' + name), to=getattr(self, 'max_' + name), resolution=SCALES[sca]['res']) this_sca.enable = ('enable' in list(SCALES[sca].keys()) and SCALES[sca]['enable'] or None) this_sca.disable = ('disable' in list(SCALES[sca].keys()) and SCALES[sca]['disable'] or None) this_sca.grid(column=int(2 + int(vid)), row=counter, sticky=E + W) this_sca.bind("<ButtonRelease>", self.scale_handler) this_sca.ref = name counter += 1 CHECK_BUTTONS = OrderedDict( [('mute', False), ('automate_binaural_diffs', True), ('automate_note_duration_prop', True), ('use_proportional_slide_duration', {'val': True, 'label': 'proportional slide'}), ('automate_pan', True), ('automate_wavetables', True)]) for vid in voice_ids: counter = 0 cb_frame = LabelFrame(self, text="Voice {0} - Automation".format(vid)) setattr(self, 'voice_' + vid + '_cb_frame', cb_frame) for cb in CHECK_BUTTONS: options = CHECK_BUTTONS[cb] name = 'voice_' + vid + '_' + cb if isinstance(options, dict) and 'label' in list(options.keys()): label = options['label'] else: label = cb[9:] if cb[:9] == 'automate_' else cb setattr(self, name, IntVar( value=type(options) == dict and options['val'] or options)) self.this_cb = Checkbutton(cb_frame, text=label, variable=getattr(self, name)) self.this_cb.bind('<Button-1>', self.check_boxes_handler) self.this_cb.disable = None self.this_cb.grid(sticky=W, column=0, row=counter) self.this_cb.ref = name counter += 1 # add trigger wavetable-button trigWavetableButton = Button(cb_frame, text='Next Wavetable') trigWavetableButton.bind('<Button-1>', self.trigger_waveform_handler) trigWavetableButton.ref = 'voice_' + vid + "_trigger_wavetable" trigWavetableButton.grid(row=counter) cb_frame.grid(column=int(vid) + 2, row=5, sticky=E + W + N, rowspan=8) for vid in voice_ids: generation_types = ["random", "random_harmonic", "harmonic"] partial_pools = ["even", "odd", "all"] prefix = 'voice_' + vid + '_' types_name = prefix + 'wavetable_generation_type' pools_name = prefix + 'partial_pool' setattr(self, types_name, StringVar()) getattr(self, types_name).set("random") setattr(self, pools_name, StringVar()) getattr(self, pools_name).set("all") target_frame = getattr(self, 'voice_' + vid + '_cb_frame') gen_typ_frame = LabelFrame(target_frame, text="type") gen_typ_frame.grid(row=len(target_frame.winfo_children()), sticky=W) for gen_t in generation_types: gen_t_entry = Radiobutton(gen_typ_frame, value=gen_t, text=gen_t, anchor=W, variable=getattr(self, types_name)) gen_t_entry.bind('<ButtonRelease-1>', self.wt_handler) gen_t_entry.ref = types_name gen_t_entry.grid(row=len(gen_typ_frame.winfo_children()), sticky=W) pp_frame = LabelFrame(target_frame, text="harmonics") for pp in partial_pools: pp_entry = Radiobutton(pp_frame, value=pp, text=pp, anchor=W, variable=getattr(self, pools_name)) pp_entry.bind('<ButtonRelease-1>', self.wt_handler) pp_entry.ref = pools_name pp_entry.grid(row=len(pp_frame.winfo_children()), sticky=E + W) this_num_partials = Scale(pp_frame, label='number of harmonics', orient=HORIZONTAL, from_=1, to=24, resolution=1) this_num_partials.ref = prefix + 'num_partials' this_num_partials.grid(column=0, row=len(pp_frame.winfo_children()), sticky=E + W) this_num_partials.bind("<ButtonRelease>", self.scale_handler) pp_frame.grid(row=len(target_frame.winfo_children()), sticky=E + W)
class testGUI: def __init__(self, master): """initialize GUI""" self.root = master self.on = True self.connection = None Tk().withdraw() self.basicframe = Frame(self.root) self.basicframe.grid() self.basicframe.configure(bg=bgcolor) self.fr = Frame(self.basicframe) self.fr.grid(row=0, column=0, sticky='new') # , sticky='W') self.fr.configure(bg=bgcolor) Grid.columnconfigure(self.root, 0, weight=1) self.port = None self.baud = None # self.inputTypes = ['ascii', 'bin', 'hex', 'mix'] self.inputType = StringVar() self.inputType.set('ascii') self.input = 'ascii' self.labelPort = Label(self.fr, width=10, text='PORT', justify='left', anchor='w', bg=bgcolor, fg=fgcolor, font=("Calibri", 12)) self.entryPort = Entry(self.fr, width=20, bd=3, justify='left', bg=inputbox, fg=fgcolor) self.labelBaud = Label(self.fr, text='BAUD', justify='left', anchor='w', bg=bgcolor, fg=fgcolor, font=("Calibri", 12)) self.entryBaud = Entry(self.fr, width=20, bd=3, justify='right', bg=inputbox, fg=fgcolor) self.labelType = Label(self.fr, text='TYPE', justify='left', anchor='w', bg=bgcolor, fg=fgcolor, font=("Calibri", 12)) self.radioType1 = Radiobutton(self.fr, text='ascii', variable=self.inputType, value='ascii', indicatoron=0) self.radioType2 = Radiobutton(self.fr, text='bin', variable=self.inputType, value='bin', width=20, indicatoron=0) self.radioType3 = Radiobutton(self.fr, text='hex', variable=self.inputType, value='hex', indicatoron=0) self.radioType4 = Radiobutton(self.fr, text='mix', variable=self.inputType, value='mix', width=20, indicatoron=0) self.labelInput = Label(self.fr, text='INPUT', justify='left', anchor='w', bg=bgcolor, fg=fgcolor, font=("Calibri", 12)) self.entryInput = Entry(self.fr, width=20, bd=3, justify='left', bg=inputbox, fg=fgcolor) self.buttonSend = Button(self.fr, text='SEND', justify='center', bg=buttoncolor, command=self.send) self.buttonRead = Button(self.fr, text='READ', justify='center', bg=buttoncolor, command=self.read) self.buttonExit = Button(self.fr, text='EXIT', justify='center', bg='red', fg='white', command=self.exit) self.response = StringVar() self.response.set('') self.responseBar = Label(self.fr, textvariable=self.response, justify='left', anchor='w', bg=bgcolor, fg=fgcolor, font=("Calibri", 12)) self.status = StringVar() self.statusBar = Label(self.fr, textvariable=self.status, justify='left', anchor='nw', bg=bgcolor, fg=fgcolor, font=("Calibri", 10)) self.status.set('Initialized') def emptyRow(self, nrow): Label(self.fr, text="", bg=bgcolor).grid(row=nrow, column=0) def configure_connection(self): self.status.set('Configuring connection') print ('Configuring connection') self.port = self.entryPort.get() self.baud = self.entryBaud.get() print ('{}:{}'.format(self.port, self.baud)) try: self.baud = int(self.baud) except: print ('Something went wrong, setting baud to 0') self.entryBaud.delete(0, END) self.entryBaud.insert(0, '0') self.baud = 0 self.connection = RS232(comport=self.port, baud=self.baud, dictionary={}, timeout=1) self.connection.connect() print ('Connection status: {}'.format(self.connection)) if self.connection and self.connection.conn: print ('Connection established, locking current settings') self.entryPort.configure(state='disabled') self.entryBaud.configure(state='disabled') else: print ('No connection') self.status.set('<No connection>') def convertInput(self): self.status.set('Converting input') typ = self.inputType.get() self.input = self.entryInput.get() if typ == 'bin': newInput = ''.join(lambda x: x in '01', self.input) self.input = chr(int(newInput, 2)) elif typ == 'hex': newInput = ''.join(lambda x: x in '0123456789ABCDEF', self.input) self.input = chr(int(newInput, 16)) elif typ == 'mix': newInput = self.input for i in re.findall('<(\d+?)>', inp): newInput = newInput.replace('<{}>'.format(i), chr(int(i))) self.input = newInput print ('Converted input: {}'.format(self.input)) def send(self): # self.input = self.entryInput.get() self.convertInput() self.status.set('Sending Data: {}'.format(self.input[:5])) if not self.connection or not self.connection.conn: # print ('Connection must be configured') self.configure_connection() if self.connection and self.connection.conn: # print ('Connection seems to be OK') stat = self.connection.send(bytes(self.input, 'utf-8')) self.status.set('') if not stat: print ('Sending not successful.') return stat else: # print ('Connection probably not established') pass return None # self.status.set('<No connection>') def read(self): self.status.set('Reading Data') print ('Read data') if not self.connection or not self.connection.conn: print ('Configuring connection') self.configure_connection() # self.input = self.entryInput.get() response = self.connection.receive() if response: print ('Response {}'.format(response)) self.response.set(response) else: print ('No response') self.response.set('<No response>') # self.status.set('') def exit(self): # for thread in (self.timerthread, self.connthread, self.statusthread, self.autologthread, self.readexternalsthread): # thread.join() # if self.active: # self.startStop() self.on = False self.connection and self.connection.disconnect() self.root.destroy() self.root.quit() def mainDialog(self): self.labelPort.grid(row=0, column=0, sticky='we', padx=(5, 0)) self.entryPort.grid(row=0, column=1, sticky='we') self.labelBaud.grid(row=1, column=0, sticky='we', padx=(5, 0)) self.entryBaud.grid(row=1, column=1, sticky='we') self.labelType.grid(row=2, column=0, sticky='we', padx=(5, 0)) self.radioType1.grid(row=2, column=1, sticky='we') self.radioType2.grid(row=2, column=2, sticky='we') self.radioType3.grid(row=3, column=1, sticky='we') self.radioType4.grid(row=3, column=2, sticky='we') self.labelInput.grid(row=4, column=0, sticky='we', padx=(5, 0)) self.entryInput.grid(row=4, column=1) self.responseBar.grid(row=5, column=1) self.statusBar.grid(row=6, column=1) Label(self.fr, text="", bg=bgcolor).grid(row=7, column=0) self.buttonSend.grid(row=8, column=0) self.buttonRead.grid(row=8, column=1) self.buttonExit.grid(row=8, column=2)
def _popupsearchcondwindow(self, index=-1): if index < 0: cond = ValueSearchCondition("", "") else: cond = self._getselectedfile().searchconds[index] window = Toplevel(self) title = Label(window, text="New Search Condition") title.grid(row=0, column=0, padx=5, pady=5, sticky=W + N) fieldlabel = Label(window, text="Field Name: ") fieldlabel.grid(row=1, column=0, padx=5, pady=5, sticky=W) fields = csvhandler.getfields(self._getselectedfile().filename) fieldvar = StringVar(window) fieldinput = Combobox(window, textvariable=fieldvar, values=fields, width=20) fieldinput.grid(row=1, column=1, columnspan=2, padx=5, pady=5, sticky=W) valuelabel = Label(window, text="Value: ") valuelabel.grid(row=3, column=0, padx=5, pady=5, sticky=W) valueinput = Entry(window) valueinput.grid(row=3, column=1, columnspan=2, padx=5, pady=5, sticky=W) minlabel = Label(window, text="Min Value: ") minlabel.grid(row=4, column=0, padx=5, pady=5, sticky=W) mininput = Entry(window) mininput.grid(row=4, column=1, columnspan=2, padx=5, pady=5, sticky=W) maxlabel = Label(window, text="Max Value: ") maxlabel.grid(row=5, column=0, padx=5, pady=5, sticky=W) maxinput = Entry(window) maxinput.grid(row=5, column=1, columnspan=2, padx=5, pady=5, sticky=W) sarchkind = IntVar() def _enablesingle(): valueinput.config(state=NORMAL) mininput.config(state=DISABLED) maxinput.config(state=DISABLED) singlebutton.select() def _enablejoin(): valueinput.config(state=DISABLED) mininput.config(state=NORMAL) maxinput.config(state=NORMAL) joinbutton.select() typelabel = Label(window, text="Search Type: ") typelabel.grid(row=2, column=0, padx=5, pady=5, sticky=W) singlebutton = Radiobutton(window, text="Single", variable=sarchkind, value=1, command=_enablesingle) singlebutton.grid(row=2, column=1, columnspan=1, padx=5, pady=5, sticky=W) joinbutton = Radiobutton(window, text="Range", variable=sarchkind, value=2, command=_enablejoin) joinbutton.grid(row=2, column=2, columnspan=1, padx=5, pady=5, sticky=W) # init value fieldvar.set(cond.field) if isinstance(cond, ValueSearchCondition): valueinput.insert(0, cond.val) _enablesingle() elif isinstance(cond, RangeSearchCondition): mininput.insert(0, cond.valmin) maxinput.insert(0, cond.valmax) _enablejoin() def _newcond(): '''create new condition ''' if sarchkind.get() == 1: cond = ValueSearchCondition(fieldvar.get(), valueinput.get()) else: cond = RangeSearchCondition(fieldvar.get(), mininput.get(), maxinput.get()) selectedfile = self._getselectedfile() if index < 0: selectedfile.searchconds.append(cond) else: del selectedfile.searchconds[index] selectedfile.searchconds[index:index] = [cond] self._inflatesearchcondlist(selectedfile) window.destroy() okbtn = Button(window, text="Confirm", width=7, command=_newcond) okbtn.grid(row=6, column=1, rowspan=1, columnspan=1, sticky=E, padx=5, pady=5) clsbtn = Button(window, text="Close", width=7, command=lambda: window.destroy()) clsbtn.grid(row=6, column=2, rowspan=1, columnspan=1, sticky=E, padx=5, pady=5)
class fen_info(Tk): """ Fenêtre permettant de saisir les informations sur les joueurs """ def __init__(self): super().__init__() # Initialisation des pions à la valeur initiale. self.pion1 = "X" self.pion2 = "O" # Titre de la fenêtre self.title("Ultimate TIC-TAC-TOE") # Pour changer taille minimum de fenêtre et taille centrer, # changer variable self.width_fen, self.height_fen. self.width_fen, self.height_fen = 430, 500 # Taille minimum de la fenêtre self.minsize(self.width_fen, self.height_fen) # Centrer la fenêtre. centreFen(self, self.width_fen, self.height_fen) # Création d'un canvas avec l'image "logo.gif" canvas = Canvas(self, width=280, height=100) self.img = PhotoImage(file="logo.gif") canvas.create_image(280, 100, anchor=SE, image=self.img) canvas.grid(row=0, columnspan=5, pady=10) # Libellé - Nouvelle Partie Label(self, text="Nouvelle partie", font=("Arial", 16), fg="#0080FF", justify=CENTER).grid( row=1, columnspan=5, padx = 20, pady = 5) separateur(20).grid(row=10,columnspan=5) # Sélection du type de partie avec bouton radio self.choixJoueur = IntVar() r1 = Radiobutton(self, text="Jouer avec l'ordinateur", variable = self.choixJoueur, value = 1, command=self.define_choix) r1.select() r1.grid(row=20, column=0) r2 = Radiobutton(self, text="Jouer avec un autre joueur", variable = self.choixJoueur, value = 2, command=self.define_choix) r2.grid(row=20, column=1) # Saisie du nom du joueur 1. f_j1 = Frame(self, borderwidth=1, padx=5, pady=5, relief=SUNKEN) f_j1.grid(row=30, columnspan=5, padx=5, pady=5) Label(f_j1, text="Nom joueur 1:").grid(row=1, column=0, sticky=E, padx = 5, pady = 5) self.nom_joueur1 = Entry(f_j1) self.nom_joueur1.grid(row=1,column=1) # Sélection du pion joueur 1. Le pion restant est automatiquement attribué au joueur 2. Label(f_j1, text="Choix de pion:").grid(row=1, column=2, padx=5) self.sel_pion=IntVar() p1 = Radiobutton(f_j1, indicatoron=0, width=5, text="X", variable=self.sel_pion, value=1, command=self.choix_pion) p1.grid(row=1, column=3, padx=2) p1.select() Radiobutton(f_j1, indicatoron=0, width=5, text="O", variable=self.sel_pion, value=2, command=self.choix_pion).grid(row=1, column=4, padx=2) # Saisie du nom du joueur 2. Apparaît seulement si on sélection 2 joueurs. Voir define_choix self.f_j2 = Frame(self, width=420, borderwidth=1, padx=5, pady=5, relief=SUNKEN) Label(self.f_j2, text="Nom joueur 2").grid(row=1, column=0, sticky=E, padx = 5, pady = 5) self.nom_joueur2 = Entry(self.f_j2, state="disabled") self.nom_joueur2.grid(row=1, column=1) self.label_pion2 = Label(self.f_j2, text="Pion Joueur 2 = O") self.label_pion2.grid(row=1, column=2, padx=5) # Information sur l'ordinateur. Disparaît si on choisi 2 joueurs. self.f_ordi = Frame(self, width=420, borderwidth=1, padx=5, pady=5, relief=SUNKEN) self.f_ordi.grid(row=40, columnspan=5, padx=5, pady=5) Label(self.f_ordi, text="Ordinateur = Colosse", font=("Arial", 12), fg="#0080FF")\ .grid(row=1, column=0, sticky=E, padx = 5, pady = 5) self.pion_ordi = Label(self.f_ordi, text="| Pion de l'ordinateur = O", font=("Arial", 12), fg="#0080FF") self.pion_ordi.grid(row=1, column=2) separateur(20).grid(row=50,columnspan=5) # Sélection de la force de l'ordinateur self.choixForce = IntVar() self.f1 = Radiobutton(self, indicatoron=0, width = 20, padx = 20, text="Facile", variable=self.choixForce, value=1, command=self.define_choix) self.f1.select() self.f1.grid(row=60, columnspan=5) self.f2 = Radiobutton(self, indicatoron=0, width = 20, padx = 20, text="Moyen", variable=self.choixForce, value=2, command=self.define_choix) self.f2.grid(row=61, columnspan=5) self.f3 = Radiobutton(self, indicatoron=0, width = 20, padx = 20, text="Difficile", variable=self.choixForce, value=3, command=self.define_choix) self.f3.grid(row=62, columnspan=5) separateur(40).grid(row=70, column=0) #Button pour démarrer la partie self.bt_start = Button(text="Démarrer", font=("Arial", 12), fg="green", command=self.demarrer_jeu) self.bt_start.grid(row=80, columnspan=5) def define_choix(self): """ Fonction qui active ou désactive le nom du joueur 2 selon si on joue contre l'ordinateur ou contre un autre joueur """ if self.choixJoueur.get()==1: self.nom_joueur2.delete(0, END) self.nom_joueur2["state"]="disabled" self.f1["state"]="normal" self.f2["state"]="normal" self.f3["state"]="normal" self.f_j2.grid_remove() self.f_ordi.grid(row=40, columnspan=5, padx=5, pady=5) elif self.choixJoueur.get()==2: self.nom_joueur2["state"]="normal" self.f1["state"]="disabled" self.f2["state"]="disabled" self.f3["state"]="disabled" self.f_j2.grid(row=40, columnspan=5, padx=5, pady=5) self.f_ordi.grid_remove() def choix_pion(self): # Définition des pions if self.sel_pion.get()==1: self.pion1="X" self.pion2="O" self.label_pion2["text"]="Pion Joueur 2 = {}".format(self.pion2) self.pion_ordi["text"]="| Pion de l'ordinateur = {}".format(self.pion2) else: self.pion1="O" self.pion2="X" self.label_pion2["text"]="Pion Joueur 2 = {}".format(self.pion2) self.pion_ordi["text"]="| Pion de l'ordinateur = {}".format(self.pion2) def demarrer_jeu(self): """ Démarrer la partie avec les informations saisie. Afficher le plateau """ if self.choixJoueur.get()==1: type2 = "Ordinateur" if self.nom_joueur1.get()!='': j1 = self.nom_joueur1.get() j2 = "Colosse" else: j1 = "Joueur 1" j2 = "Colosse" elif self.choixJoueur.get()==2: type2 = "Personne" if self.nom_joueur1.get()!='' and self.nom_joueur2.get()!='': j1 = self.nom_joueur1.get() j2 = self.nom_joueur2.get() elif self.nom_joueur1.get()=='': j1 = "Joueur 1" if self.nom_joueur2.get()=='': j2 = "Joueur 2" else: j2 = self.nom_joueur2.get() else: j1 = self.nom_joueur1.get() if self.nom_joueur2.get()=='': j2 = "Joueur 2" else: j2 = self.nom_joueur2.get() p1 = self.pion1 p2 = self.pion2 force = self.choixForce.get() self.destroy() ma_fenetre = Fenetre(j1, j2, type2, p1, p2, force) ma_fenetre.mainloop()
option_frame.pack(side=RIGHT) tag_frame = Frame(option_frame, height=50, width=150) tag_frame.pack(side=TOP) tag_frame_top = Frame(tag_frame) tag_frame_top.pack(side=TOP) corpus_label = Label(tag_frame_top, text='Corpus path:') corpus_label.pack(side=LEFT) corpus_file_var = StringVar() corpus_entry = Entry(tag_frame_top, textvariable=corpus_file_var, bd=5) corpus_entry.pack(side=LEFT) tag_frame_bottom = Frame(tag_frame) tag_frame_bottom.pack(side=TOP) language_var = StringVar() english_radio = Radiobutton( tag_frame_bottom, text='English', variable=language_var, value='en') english_radio.pack(side=LEFT) spanish_radio = Radiobutton( tag_frame_bottom, text='Spanish', variable=language_var, value='es') spanish_radio.pack(side=LEFT) tag_button = Button( tag_frame_bottom, text='OK', command=tag_button_cmd) tag_button.pack(side=LEFT) pattern_frame = Frame(option_frame, height=50, width=150) pattern_frame.pack(side=TOP) pattern_content = Text(pattern_frame, height=10, width=50) pattern_content.pack() pattern_button = Button(pattern_frame, text='OK', command=pattern_button_cmd) pattern_button.pack()
class GUI: def __init__(self, master): """initialize GUI""" self.root = master self.on = True Tk().withdraw() self.starttime = datetime.now() # status bar, info for user self.statusString = StringVar() self.statusText = 'Ready' self.statusString.set(self.statusText) self.comparatorStatus = 'inactive' # self.comparatorStatuses = ['inactive', 'active', # 'steady', 'moving', 'paused', 'finished'] # 2 manual statuses + 4 auto statuses self.levelStatus = StringVar() self.ifmStatus = StringVar() self.nivelStatus = StringVar() self.thermoStatus = StringVar() self.active = 0 # 0 - inactive state, 1 - active (in motion), 2 - steady (waiting while taking data) self.auto = 0 # COMPARATOR MOTION CONTROL self.step = StringVar() # mm self.begin = StringVar() # mm self.end = StringVar() # mm self.autoVal = IntVar() self.labelTop = StringVar() self.labelTop.set('VERTICAL COMPARATOR') # LABELS ON BUTTONS self.label10 = StringVar() # initialize self.label11 = StringVar() # start/stop self.label12 = StringVar() # pause/continue self.label21 = StringVar() # manual self.label22 = StringVar() # auto self.label31 = StringVar() # step self.label32 = StringVar() # start self.label33 = StringVar() # stop self.label51 = StringVar() # manual read interferometer self.label52 = StringVar() # manual read digi level self.label53 = StringVar() # manual read nivel (inclinometer) self.label54 = StringVar() # manual read thermometer self.autoVal.set(0) # init PLC, interferometer and level self.plc = Comparator(comsettings['COMPARATOR_PORT'], int(comsettings['COMPARATOR_BAUD'])) self.conn = self.plc.conn self.paused = None self.ifm = Interferometer(comsettings['IFM_PORT'], int(comsettings['IFM_BAUD'])) self.level = Level(comsettings['LEVEL_PORT'], int(comsettings['LEVEL_BAUD'])) self.nivel = Nivel(comsettings['NIVEL_PORT'], int(comsettings['NIVEL_BAUD'])) self.thermo = Thermometer(comsettings['THERMO_PORT'], int(comsettings['THERMO_BAUD'])) self.observer = '' # operator self.label10.set('Initialize') self.label11.set({0: 'START', 1: 'STOP', 2:'STOP'}[self.active]) # start/stop self.setStatus({0: 'ready', 1: 'active', 2:'steady'}[self.active]) self.label12.set('PAUSE') self.label21.set('MANUAL') # manual self.label22.set('AUTO') # auto self.label31.set('LOW') # start height self.label32.set('HIGH') # stop height self.label33.set('STEP') # step self.label51.set('READ IFM') # read interferometer self.label52.set('READ LVL') # read digi level self.label53.set('READ NVL') # read inclinometer self.label54.set('READ THM') # read thermometer self.chksumText = StringVar() self.responseText = StringVar() self.timestring = StringVar() self.connstring = StringVar() # self.queue = queue.Queue() self.timerthread = threading.Thread(target=self.timer, name='Timer') self.timerthread.start() self.readdata = '' self.connthread = threading.Thread(target=self.checkConnection, name='ConnChk') self.connthread.start() self.statusthread = threading.Thread(target=self.checkStatus, name='StatChk') self.statusthread.start() self.readexternalsthread = threading.Thread(target=self.readExternals, name='ReadExt') self.readexternalsthread.start() self.autologthread = threading.Thread(target=self.autolog, name='Autolog') self.autologthread.start() # starttimer() # startautolog() # startautoserialcheck() # def toggleStartStop(self): # # if start then stop else otherwise # # change button and text color if possible # pass def timer(self): while self.on: dt = datetime.now() - self.starttime self.timestring.set('%-10s' % str(dt).split('.')[0]) time.sleep(0.1) def autolog(self, timeout=60): while self.on: print('Autolog') (s, low, hi, step, ifm, lvl, nvl, thm, obs) = tuple(['']*9) try: s = self.statusText except BaseException: s = 'N/A' try: low = self.lowEntry.get().strip() except BaseException: low = 'N/A' try: hi = self.hiEntry.get().strip() except BaseException: hi = 'N/A' try: step = self.stepEntry.get().strip() except BaseException: step = 'N/A' try: ifm = self.ifm.getReading() except BaseException: ifm = 'N/A' try: lvl = self.level.getReading() except BaseException: lvl = 'N/A' try: nvl = self.nivel.getReading() except BaseException: nvl = 'N/A' try: thm = self.thermo.getReading() except BaseException: thm = 'N/A' try: obs = self.entryObserver.get().strip() except BaseException: obs = 'N/A' log('AUTOLOG! status: %s, low: %s, hi: %s, step: %s, ifm: %s, lvl: %s, nvl:%s, thm: %s, obs: %s' % ( s, low, hi, step, ifm, lvl, nvl, thm, obs)) time.sleep(timeout) def checkConnection(self): connection = False while self.on: if self.conn: try: d = self.conn.read(1) self.readdata += d connection = True except: self.conn.close() try: self.connect() except: connection = False else: try: self.connect() except: connection = False self.connstring.set({True: 'isConn', False: 'notConn'}[connection]) time.sleep(0.5) def checkStatus(self): if self.conn: moving = self.plc.query('is_moving') if moving is None: self.status = 'unknown' elif not self.auto: if moving: self.status = 'active' else: self.status = 'inactive' else: if moving: self.status = 'moving' else: if self.paused: self.status = 'paused' else: self.status = 'steady' else: self.status = 'not connected' def readExternals(self): while self.on: # self.getIfm() # self.getLevel() self.getNivel() self.getThermo() time.sleep(15) def evaluateEntries(self): s, b, e = self.stepEntry, self.beginEntry, self.endEntry res = [None, None, None] for i in range(3): try: res[i] = float([s, b, e][i]) except: pass # leave it None if b > e and s > 0: # if step is negative, it can move downwards (from hi to low) b, e = e, b # otherwise it begin and end must be changed if b>e elif b < e and s < 0: b, e = e, b # INPUT IN MM !! cannot recognize 0.5mm from 0.5m step or 3mm vs 3m end # input values converted to mm # [s,b,e] = [i*1000. if (i is not None and i<5.) else i for i in [s,b,e]] return s, b, e def emptyRow(self, nrow): Label(self.fr, text="", bg=bgcolor).grid(row=nrow, column=0) def setStatus(self, text): self.statusText = text self.statusString.set(self.statusText) def setIfmStatus(self, text): self.ifmStatus.set(text) def setLevelStatus(self, text): self.levelStatus.set(text) def setNivelStatus(self, text): self.nivelStatus.set(text) def setThermoStatus(self, text): self.thermoStatus.set(text) def getIfm(self): # log('Get Ifm reading') response = self.ifm.getReading() or "No response" self.setIfmStatus(response) return response def getLevel(self): # log('Get Level reading') response = self.level.getReading() or "No response" self.setLevelStatus(response) return response def getNivel(self): # log('Get Nivel reading') response = '-'.join(map(str,self.nivel.getReading())) if any(self.nivel.getReading()) else "No response" self.setNivelStatus(response) return response def getThermo(self): # log('Get Thermo reading') response = self.thermo.getReading() or "No response" self.setThermoStatus(response) return response # #set stop button # def setStop(self): # pass # # #set start # def setStart(self): # pass # toggle start stop def startStop(self): # ask comparator if moving, then set "not response" self.active = not self.active # self.setStatus({0: 'ready', 1: 'active'}[self.active]) self.setStatus(self.comparatorStatus) self.label10.set({0: 'START', 1: 'STOP'}[self.active]) self.buttonStartStop.configure(bg=startstopbg[self.active], fg=startstopfg[self.active]) print(self.active) self.observer = self.entryObserver.get().strip() if not self.active: log('CMP stopped %s' % self.observer) else: log('CMP started %s' % self.observer) if self.active: pass # action after comparator is stopped else: pass # action after comparator is started # CURRENT_POSITION, NEXT_POSITION, TARGET_POSITION, ITERATION def writePauseParams(self,**params): with open('.pause') as f: f.write('\n'.join([k+' '+' '.join(vals) for k, vals in params.items()])) return True def readPauseParams(self): params = {} with open('.pause','r') as f: for line in f.readlines(): key = line.split()[0] vals = line.split()[1:] params[key] = vals os.remove('.pause') return params def pauseSession(self): self.paused = True self.stop() self.writePauseParams() def continueSession(self): self.paused = False params = self.readPauseParams() self.moveto(params['NEXT_POS']) self.session(float(params['NEXT_POS']), float(params['TARGET_POS']), float(params['STEP']), int(params['NEXT_ITER'])) def session(self, **params): start = float(params.get('START_POS')) target = float(params.get('TARGET_POS')) step = float(params.get('STEP',5)) iteration = int(params.get('NEXT_ITER',0)) self.plc.moveto(start) self.paused = False op = operator.le if step > 0 else operator.ge while op(self.plc.getPosition(), target): iteration += 1 self.getMeasurement() next_position = self.plc.getPosition() + step if next_position < target: self.plc.moveto(next_position) def initialize(self): if not self.plc.isInit(): log('Initialize') else: log('Already initialized, reinitialize.') self.plc.initialize() def pause(self): # comparator status: # man/inactive, man/active, # auto/steady (measurement), auto/active, auto/paused, auto/finished #['inactive', 'active', 'steady', 'moving', 'paused', 'finished'] if self.comparatorStatus in ('moving', 'steady'): self.pauseSession() elif self.comparatorStatus == 'paused': self.continueSession() # active / inactive - button should be disabled def stop(self): self.plc.command('STOP') def getEntries(self): return self.stepEntry, self.beginEntry, self.endEntry def close(self): self.on = False # for thread in (self.timerthread, self.connthread, self.statusthread, self.autologthread, self.readexternalsthread): # thread.join() # TODO CLOSE ALL CONNECTIONS!! if self.active: self.startStop() self.root.destroy() self.root.quit() def gotoLow(self): low = None self.setStatus('Going to LOW') try: low = float(self.lowEntry.get().strip()) except: pass pass # move carriage to set low return low def gotoHi(self): hi = None self.setStatus('Going to HIGH') try: hi = float(self.hiEntry.get().strip()) except: pass pass # move carriage to set low return hi def moveStep(self): pos = self.plc.getPosition() or 0 # remove 0 when connection established step = 0 try: step = float(self.stepEntry.get().strip()) except BaseException: log('Cannot determine step entry.') targetpos = pos + step if step != 0: self.setStatus('Moving to %f' % targetpos) self.plc.moveto(targetpos) return targetpos def resetIfmStatus(self): self.ifmStatus.set('') def resetLevelStatus(self): self.levelStatus.set('') def resetNivelStatus(self): self.nivelStatus.set('') def resetThermoStatus(self): self.thermoStatus.set('') def submit(self): calculate_checksum = True port = self.portEntry.get().strip() message = self.messageEntry.get() chksumtyp = self.portChecksumType.get() from externals import RS232 from pycrc import pycrc, crc_algorithms, Crc rs = RS232() r = rs.connect(port, baud=38400) if r: print ('Successfully connected to %s' % r.name) checksum = '' if calculate_checksum: from pycrc.crc_algorithm import Crc # params = filter(lambda x: x['name']==chksumtyp, cmodels)[0] params = {'width': 16, 'poly':0x1021, 'reflect_in':True, 'xor_in':0x0000, 'reflect_out':True, 'xor_out':0x0000} crc = Crc(**params) print("{0:#x}".format(crc.bit_by_bit(message))) # crc = Crc(width=16, poly=0x8005, # reflect_in = True, xor_in = 0x0000, # reflect_out = True, xor_out = 0x0000) # >> > print("{0:#x}".format(crc.bit_by_bit("123456789"))) # >> > print("{0:#x}".format(crc.bit_by_bit_fast("123456789"))) # >> > print("{0:#x}".format(crc.table_driven("123456789"))) rs.send() # self.chksumLabel = (self.fr, textvariable = self.chksumText, anchor = 'w', # bg = bgcolor, fg = statuscolor, font = ( # "Calibri", 9)) # self.chksumLabel.grid(row=23, column=2) # # buttonSubmit = Button(self.fr, text="SUBMIT", width=15, justify='center', # bg="black", fg="yellow", command=self.submit, # font=("Calibri", 14, "bold")) # buttonSubmit.grid(row=23, column=0) # # self.responseLabel = (self.fr, textvariable = self.responseText, anchor = 'w', # bg = bgcolor, fg = statuscolor, font = ( # "Calibri", 9)) # self.responseLabel.grid(row=23, column=1) # # self.emptyRow(24) def mainDialog(self): self.basicframe = Frame(self.root) self.basicframe.grid() self.basicframe.configure(bg=bgcolor) self.fr = Frame(self.basicframe) self.fr.grid(row=0, column=0, sticky='new') # , sticky='W') self.fr.configure(bg=bgcolor) # Grid.rowconfigure(root, 0, weight=1) Grid.columnconfigure(root, 0, weight=1) self.emptyRow(0) Label(self.fr, textvariable=self.labelTop, justify='center', bg=bgcolor, font=("Calibri", 24) ).grid(row=1, column=0, columnspan=3, sticky='we') self.emptyRow(2) Label(self.fr, text='STATUS:', justify='left', anchor='w', bg=bgcolor, fg=statuscolor, font=("Calibri", 12) ).grid(row=3, column=0, sticky='we', padx=(5, 0)) self.statusLine = Label(self.fr, textvariable=self.statusString, justify='left', anchor='w', bg=bgcolor, fg=statuscolor, font=("Calibri", 14, "bold") ).grid(row=3, column=1, columnspan=2, sticky='we') self.emptyRow(4) # AUTO / MANUAL self.my_var.set(1) self.buttonManual = Radiobutton(self.fr, text="MANUAL", variable=self.auto, value=0, width=15, justify='center', # bg=buttoncolor2, bg="moccasin", indicatoron=0) # self.exit_root) self.buttonManual.grid(row=5, column=0, sticky='ew', padx=(0, 10)) # self.buttonManual.configure(state='selected') self.buttonAuto = Radiobutton(self.fr, text="AUTO", variable=self.auto, value=1, width=15, justify='center', # bg=buttoncolor2, bg="moccasin", indicatoron=0) # self.exit_root) self.buttonAuto.grid(row=5, column=2, sticky='ew', padx=(10, 0)) self.emptyRow(6) #should be disabled if initialized already self.buttonInitialize = Button(self.fr, text='Initialize', justify='center', bg=buttoncolor, command=self.initialize) self.buttonInitialize.grid(row=7, column=0, sticky='nsew') self.buttonStartStop = Button(self.fr, textvariable=self.label11, command=self.startStop, bg=startstopbg[self.active], fg=startstopfg[self.active], font=("Calibri", 16, "bold"), width=10) self.buttonStartStop.grid(row=7, column=1, sticky='nsew') self.buttonPause = Button(self.fr, textvariable=self.label12, justify='center', bg=buttoncolor, state={0: 'disabled', 1: 'enabled'}[self.auto], command=self.pause) self.buttonPause.grid(row=7, column=2, sticky='nsew') self.emptyRow(8) # put Labels here Label(self.fr, textvariable=self.label31, justify='center', bg=bgcolor, fg=statuscolor, font=("Calibri", 10) ).grid(row=8, column=0, sticky='we') Label(self.fr, textvariable=self.label32, justify='center', bg=bgcolor, fg=statuscolor, font=("Calibri", 10) ).grid(row=8, column=1, sticky='we') Label(self.fr, textvariable=self.label33, justify='center', bg=bgcolor, fg=statuscolor, font=("Calibri", 10) ).grid(row=8, column=2, sticky='we') # input boxes: step start stop (mm) self.lowEntry = Entry(self.fr, width=20, bd=3, justify='right', bg=inputbox, fg=statuscolor) self.lowEntry.grid(row=9, column=0, sticky='we') # , columnspan=2) # SET DEFAULT LOW # self.lowEntry.delete(0,END) # self.lowEntry.insert(0, MINPOS) self.hiEntry = Entry(self.fr, width=20, bd=3, justify='right', bg=inputbox, fg=statuscolor) self.hiEntry.grid(row=9, column=1, sticky='we') # , columnspan=2) # SET DEFAULT HIGH # self.hiEntry.delete(0,END) # self.hiEntry.insert(0, MAXPOS) self.stepEntry = Entry(self.fr, width=20, bd=3, justify='right', bg=inputbox, fg=statuscolor) self.stepEntry.grid(row=9, column=2, sticky='we') # , columnspan=2) # put buttons for GOTO and MOVE self.butGotoLow = Button(self.fr, text="Go To Low", justify='center', bg=buttoncolor, command=self.gotoLow) self.butGotoLow.grid(row=10, column=0, sticky='we') self.butGotoHi = Button(self.fr, text="Go To High", justify='center', bg=buttoncolor, command=self.gotoHi) self.butGotoHi.grid(row=10, column=1, sticky='we') self.butMoveStep = Button(self.fr, text="Move a Step", justify='center', bg=buttoncolor, command=self.moveStep) self.butMoveStep.grid(row=10, column=2, sticky='we') self.emptyRow(11) Label(self.fr, text='EXTERNAL SENSORS', justify='left', anchor='w', bg=bgcolor, fg=statuscolor, font=("Calibri", 12) ).grid(row=12, column=0, columnspan=3, sticky='we', padx=(5, 0)) # function buttons # RIadok 13-16: Externals # Interferometer buttonIfm = Button(self.fr, text="Read IFM", width=15, justify='center', bg=buttoncolor, command=self.getIfm) # self.exit_root) buttonIfm.grid(row=13, column=0, sticky='we') self.labelIfmStatus = Label(self.fr, textvariable=self.ifmStatus, justify='left', anchor='w', bg=bgcolor, fg=statuscolor, font=("Calibri", 12)) self.labelIfmStatus.grid(row=13, column=1, columnspan=2, sticky='we', padx=(15, 0)) self.labelIfmStatus.bind('<Button-1>', self.resetIfmStatus) # Digital level (Leica /Trimble) buttonLevel = Button(self.fr, text="Read Level", width=15, justify='center', bg=buttoncolor, command=self.getLevel) # self.exit_root) buttonLevel.grid(row=14, column=0, sticky='we') self.labelLevelStatus = Label(self.fr, textvariable=self.levelStatus, justify='left', anchor='w', bg=bgcolor, fg=statuscolor, font=("Calibri", 12)) self.labelLevelStatus.grid(row=14, column=1, columnspan=2, sticky='we', padx=(15, 0)) self.labelLevelStatus.bind('<Button-1>', self.resetLevelStatus) # Nivel - inclinometer buttonNivel = Button(self.fr, text="Read Nivel", width=15, justify='center', bg=buttoncolor, command=self.getNivel) # self.exit_root) buttonNivel.grid(row=15, column=0, sticky='we') self.labelNivelStatus = Label(self.fr, textvariable=self.nivelStatus, justify='left', anchor='w', bg=bgcolor, fg=statuscolor, font=("Calibri", 12)) self.labelNivelStatus.grid(row=15, column=1, columnspan=2, sticky='we', padx=(15, 0)) self.labelNivelStatus.bind('<Button-1>', self.resetNivelStatus) # Thermometer line buttonThermo = Button(self.fr, text="Read Thermo", width=15, justify='center', bg=buttoncolor, command=self.getThermo) # self.exit_root) buttonThermo.grid(row=16, column=0, sticky='we') self.labelThermoStatus = Label(self.fr, textvariable=self.thermoStatus, justify='left', anchor='w', bg=bgcolor, fg=statuscolor, font=("Calibri", 12)) self.labelThermoStatus.grid(row=16, column=1, columnspan=2, sticky='we', padx=(15, 0)) self.labelThermoStatus.bind('<Button-1>', self.resetThermoStatus) self.emptyRow(17) Label(self.fr, text='OBSERVER:', anchor='w', justify='left', bg=bgcolor, fg=statuscolor, font=("Calibri", 12) ).grid(row=19, column=0, sticky='we', padx=(5, 0)) self.entryObserver = Entry(self.fr, textvariable=self.observer, bg=inputbox, fg=statuscolor, font=("Calibri", 12), justify='left') self.entryObserver.grid(row=19, column=1, columnspan=2, sticky='we') # row 18> empty (or test connection) self.emptyRow(20) if ADMIN_MODE: # port, message, checksum_type?, resulting checksum?, submit, response self.portEntry = Entry(self.fr, width=20, bd=3, justify='left', bg=inputbox, fg=statuscolor) self.portEntry.grid(row=21, column=0, sticky='we') Label(self.fr, text='PORT', anchor='w', justify='left', bg=bgcolor, fg=statuscolor, font=("Calibri", 12) ).grid(row=22, column=0, sticky='we', padx=(5, 0)) self.messageEntry = Entry(self.fr, width=20, bd=3, justify='left', bg=inputbox, fg=statuscolor) self.messageEntry.grid(row=21, column=1, sticky='we') Label(self.fr, text='MESSAGE', anchor='w', justify='left', bg=bgcolor, fg=statuscolor, font=("Calibri", 12) ).grid(row=22, column=1, sticky='we', padx=(5, 0)) self.portChecksumType = Entry(self.fr, width=20, bd=3, justify='left', bg=inputbox, fg=statuscolor) self.portChecksumType.grid(row=21, column=2, sticky = 'we') Label(self.fr, text='CHKSUM TYPE', anchor='w', justify='left', bg=bgcolor, fg=statuscolor, font=("Calibri", 12) ).grid(row=22, column=2, sticky='we', padx=(5, 0)) self.chksumLabel = Label(self.fr, textvariable=self.chksumText, anchor='w', bg=bgcolor, fg=statuscolor, font=("Calibri", 9)) self.chksumLabel.grid(row=23, column=2) buttonSubmit = Button(self.fr, text="SUBMIT", width=15, justify='center', bg="black", fg="yellow", command=self.submit, font=("Calibri", 14, "bold")) buttonSubmit.grid(row=23, column=0) self.responseLabel = Label(self.fr, textvariable=self.responseText, anchor='w', bg=bgcolor, fg=statuscolor, font=("Calibri", 9)) self.responseLabel.grid(row=23, column=1) self.emptyRow(24) lastLine = 21 if not ADMIN_MODE else 25 self.timeLabel = Label(self.fr, textvariable=self.timestring, anchor='w', bg=bgcolor, fg=statuscolor, font=("Calibri", 9)) self.timeLabel.grid(row=lastLine, column=0) self.connLabel = Label(self.fr, textvariable=self.connstring, anchor='w', bg=bgcolor, fg=statuscolor, font=("Calibri", 9)) self.connLabel.grid(row=lastLine, column=1) butexit = Button(self.fr, text="EXIT", width=15, justify='center', bg="black", fg="yellow", command=self.close, font=("Calibri", 14, "bold")) butexit.grid(row=lastLine, column=2)
def __init__(self, master): # we will define everything in the UI below logger.info("Program start") self.master = master self.master.wm_title("Lautaloader v.1.03") # title of window self.master.resizable(width=FALSE, height=FALSE) # window is not resizable self.master.geometry('420x240') # resolution of the window in pixels self.master.grid_propagate(False) # window will not resize in any case self.r_selection = IntVar() # these are radiobuttons and checkbuttons self.c1_selection = IntVar() self.c2_selection = IntVar() self.c1_selection.set(0) # checkbuttons will be off at launch self.c2_selection.set(0) self.r_selection.set(1) # we need one radiobutton selected at start self.status_text = StringVar() # status text is visible at the bottom of GUI self.status_text.set('Ready to work') # we can (and will) set the status text like this self.save_folder = '' # we will save into this folder self.filenames = [] # this is our folder filenames list self.url_text = StringVar() self.num_pics = 0 self.num_mp4 = 0 self.num_mp3 = 0 self.image_url = '' self.name_of_file = '' self.res = '' self.imagefile = '' self.filesize = '' self.imagewritten = False self.read_timeout = 1.0 self.headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) ' 'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36', 'Upgrade-Insecure-Requests': '1', 'Referer': '', 'DNT': '1', 'Accept-Language': 'fi-FI,fi;q=0.8,en-US;q=0.6,en;q=0.4', 'Accept-Encoding': 'gzip, deflate, sdch', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8' } # need to send some headers or server refuses connection self.lf = LabelFrame(master, text=' Get ') self.lf.grid(row=1, column=1, rowspan=4) self.lf2 = LabelFrame(master, text=' Options ') self.lf2.grid(row=1, column=2) self.R1 = Radiobutton(self.lf, text="All", variable=self.r_selection, value=1) self.R1.grid(row=1, column=1, sticky=W) self.R2 = Radiobutton(self.lf, text="only img", variable=self.r_selection, value=2) self.R2.grid(row=2, column=1, sticky=W) self.R3 = Radiobutton(self.lf, text="only mp4", variable=self.r_selection, value=3) self.R3.grid(row=3, column=1, sticky=W) self.R4 = Radiobutton(self.lf, text="only mp3", variable=self.r_selection, value=4) self.R4.grid(row=4, column=1, sticky=W) self.C1 = Checkbutton(self.lf2, text="Create new filenames", variable=self.c1_selection, state=NORMAL, onvalue=1, offvalue=0) self.C1.grid(row=1, column=2, sticky=W) self.C2 = Checkbutton(self.lf2, text="Overwrite if found", variable=self.c2_selection, state=NORMAL, onvalue=1, offvalue=0) self.C2.grid(row=2, column=2, sticky=W) self.folder_label = Label(master, text="Folder: ") self.folder_label.grid(row=5, sticky=E) self.url_label = Label(root, text="URL: ") self.url_label.grid(row=6, sticky=E) self.folder_entry = Entry(master, textvariable=self.save_folder, state="readonly", width=50) self.folder_entry.grid(row=5, column=1, columnspan=2) self.url_entry = Entry(master, textvariable=self.url_text, width=50) self.url_entry.grid(row=6, column=1, columnspan=2) self.selectbutton = Button(master, text="Select..", state=NORMAL, command=self.get_folder) self.selectbutton.grid(row=5, column=3, sticky=W) self.openfolderbutton = Button(master, text="Open folder", state=DISABLED, command=self.openfolder) self.openfolderbutton.grid(row=3, column=2, sticky=W, padx=22) self.urlbutton = Button(master, text="Download", state=DISABLED, command=self.logic) self.urlbutton.grid(row=6, column=3, sticky=W) self.status = Label(master, textvariable=self.status_text, wraplength=300) self.status.grid(row=9, columnspan=4, sticky=W) self.progressbar = Progressbar(master, orient="horizontal", length=100, mode="determinate") self.progressbar.grid(row=8, sticky='we', columnspan=3, pady=3) self.manage_config() # process through config file self.url_1 = config.get('basic_config', 'url_1') logging.debug("url_1 set to %s" % self.url_1) self.url_2 = config.get('basic_config', 'url_2') logging.debug("url_2 set to %s" % self.url_2) if self.save_folder != '': # if save folder is not empty, we probably have a valid folder self.urlbutton['state'] = 'normal' # so we can enable urlbutton already self.openfolderbutton['state'] = 'normal' # and we can also enable open folder button