Example #1
0
class paint:
	def __init__(self,root):
		self.root = root
		self.root.title("Paint")
		self.root.geometry("800x520")
		self.root.configure(background = 'white')
		self.root.resizable(0,0)
		self.pen_color="black"
		self.eraser_color = "white"
		#adding widgets to tkinter window
		self.color_frame = LabelFrame(self.root,text="Color",font=('arial',15),bd=4,relief=RIDGE,bg="white")
		self.color_frame.place(x = 0,y = 0, width =98, height = 195)
		colors = ['#ff0000', '#00ff00', '#0000ff' , '#ffff00', '#00ffff', '#ff00ff','#ffffff', '#000000', '#99ffcc', '#ff99cc']
		i = j = 0
		for color in colors:
			Button(self.color_frame,bg = color,bd =2, relief=RIDGE,width=2,command = lambda col=color:self.select_color(col)).grid(row = i, column = j)
			i += 1
			if i==5:
				i = 0
				j+=1 
		self.eraser_button = Button(self.root, text = "Eraser",bd = 4,bg="white",command = self.eraser,width = 8,relief=RIDGE)
		self.eraser_button.place(x = 0,y = 207)
		self.clear_button = Button(self.root, text = "Clear",bd = 4,bg="white",command = lambda:self.canvas.delete("all"),width = 8,relief=RIDGE)
		self.clear_button.place(x = 0,y = 247)
		self.canvas_color = Button(self.root, text = "Canvas",bd = 4,bg="white",command = self.canvas,width = 8,relief=RIDGE)
		self.canvas_color.place(x = 0,y = 287)
		
		
		#creating a scale for pen and eraser size..
		
		self.pen_size_scale_frame = LabelFrame(self.root, text="Size", bd=5,bg='white',font=('arial', 15,'bold'),relief=RIDGE)
		self.pen_size = Scale(self.pen_size_scale_frame,orient=VERTICAL,from_=50,to=0,length=170)
		self.pen_size.set(1)
		self.pen_size.grid(row=0,column=1,padx=15)
		
		#creating canvas
		
		self.canvas = Canvas(self.root,bg='white',bd=5,relief=GROOVE, height=488,width=680)
		self.canvas.place(x=105,y=7)
		self.pen_size_scale_frame.place(x=0,y=325,height=190,width=98)
		
		#bind canvas with mouse drag
		self.canvas.bind("<B1-Motion>",self.paint)
		
		#function creation
	def paint(self,event):
		x1,y1 = (event.x-2),(event.y-2)
		x2,y2 = (event.x+2),(event.y+2)
		
		self.canvas.create_oval(x1,y1,x2,y2,fill=self.pen_color,outline=self.pen_color,width=self.pen_size.get())
	def select_color(self,col):
		self.pen_color =col
	
	def eraser(self):
		self.pen_color = self.eraser_color
		
	def canvas(self):
		color = colorchooser.askcolor()
		self.canvas.configure(background = color[1])
		self.eraser_color = color[1]
Example #2
0
    def __init__(self, master, **kw):
        super().__init__(master)

        # self.grid_propagate(0)
        # self.columnconfigure(0, weight=1)
        # self.rowconfigure(0, weight=1)

        self.var = kw.get('variable', IntVar())
        kw['variable'] = self.var
        kw['from_'] = ConfidenceLevel.Low.value
        kw['to'] = ConfidenceLevel.VeryHigh.value
        # kw['command'] = self.scale_change
        kw['orient'] = HORIZONTAL

        self.lbl_scale = Label(self)
        self.scale = Scale(self, **kw)

        self.scale_font = tkfont.nametofont(Style().lookup('TLabel',
                                                           'font')).copy()
        self.scale_font.config(weight=tkfont.BOLD, size=9)
        self.lbl_scale.config(font=self.scale_font, width=3, anchor=CENTER)
        self.var.trace_variable('w', lambda a, b, c: self.scale_change())

        self.scale.grid(row=0, column=0, sticky='ns')
        self.lbl_scale.grid(row=0, column=1, sticky='ns', padx=(3, 0))
Example #3
0
class Example(Frame):
    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):
        self.master.title("Scale")
        self.style = Style()
        self.style.theme_use("default")

        self.frame = Frame(height=10, width=100, relief=SUNKEN)
        self.frame.pack(fill=X, expand=1)
        self.frame.grid_columnconfigure(0, weight=1)

        self.scale = Scale(self.frame, from_=0, to=100, command=self.onScale)
        self.scale.grid(row=0,
                        column=0,
                        columnspan=2,
                        padx=10,
                        pady=10,
                        sticky=E + W)
        #scale.pack(fill=X, padx=15, expand=1)
        #scale.pack(fill=X, padx=15)

        self.var = IntVar()
        self.label = Label(self.frame, text=0, textvariable=self.var)
        self.label.grid(row=0, column=2, sticky=W, padx=10)
        # self.label.pack(side=LEFT)

    def onScale(self, val):

        v = int(float(val))
        self.var.set(v)
Example #4
0
class Example(Frame):
    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):
        self.master.title("Scale")
        self.style = Style()
        self.style.theme_use("default")

        self.pack(fill=BOTH, expand=True)

        self.scale = Scale(self, from_=0, to=100, command=self.onScale)
        self.scale.grid(row=0, column=0, padx=10, pady=10, sticky=E + W)

        self.var = IntVar()
        self.label = Label(self, text=0, textvariable=self.var)
        self.label.grid(row=0, column=1, sticky=W, padx=10)

        self.grid_columnconfigure(0, weight=1)

    def onScale(self, val):

        v = int(float(val))
        self.var.set(v)
Example #5
0
    def __init__(self, w, *args, **kwargs):

        super().__init__(w, *args, **kwargs)

        #___

        self.state_txt_time1 = StringVar()
        self.state_txt_time1.set(INIT_TIME)

        self.txt_time1 = Label(self,
            textvariable=self.state_txt_time1,
            background=config.colors["BG"],
            font=font.nametofont("font_small_size"))
        self.txt_time1.grid(row=0, column=0, sticky="sw")

        #___

        self.state_txt_song = StringVar()
        self.state_txt_song.set(INIT_SONG)

        self.txt_song = Label(self,
            textvariable=self.state_txt_song,
            background=config.colors["BG"])
        self.txt_song.grid(row=0, column=1, pady=(0,2))

        #___

        self.state_txt_time2 = StringVar()
        self.state_txt_time2.set(INIT_TIME)

        self.txt_time1 = Label(self,
            textvariable=self.state_txt_time2,
            background=config.colors["BG"],
            font=font.nametofont("font_small_size"))
        self.txt_time1.grid(row=0, column=2, sticky="se")

        #___

        self.state_scale_time = DoubleVar()

        self.scale_time = Scale(self,
            orient="horizontal",
            length=300,
            from_=0, to_=100,
            value=0, variable=self.state_scale_time)
        self.scale_time.grid(row=1, column=0, columnspan=3)

        #___

        #Set time when direct click on the timeline
        self.scale_time.bind("<Button-1>", self._setTimeDirect)

        #___

        self.song_playing = None
    def __init__(self, root):
        
        #Properties of the objects
        self.root = root
        self.root.title("Paint")
        self.root.geometry("800x520")
        self.root.configure(background="white")
        self.root.resizable(0, 0)
        
        # Important things
        self.pen_color = "black"
        self.eraser_color = "white"

        #Adding widgets to tkinter window

        self.color_frame = LabelFrame(self.root, text="color", font = ("arial", 15), bd=5, relief=RIDGE, bg="white")
        self.color_frame.place(x=0, y=0, width=70, height=185)

        colors = ["#000000","#FFFFFF"	, "#FF0000", "#00FF00", "#0000FF", "#FFFF00", "#00FFFF", "#FF00FF", "#C0C0C0", "#808080", "#800000", "#808000", "#008000", "#800080", "#008080", "#000080"]
        i=j=0
        for color in colors:
            Button(self.color_frame, bg=color, bd=2, relief=RIDGE, width=3, command=lambda col =color:self.select_color(col)).grid(row=i, column=j)
            i+=1
            if i==6:
                i=0
                j=1

        self.eraser_button = Button(self.root, text="ERASER", bg="white", bd=4, command=self.eraser, width=8, relief=RIDGE)
        self.eraser_button.place(x=0, y=187)

        self.clear_button = Button(self.root, text="CLEAR", bg="white", bd=4, command=lambda : self.canvas.delete("all"), width=8, relief=RIDGE)
        self.clear_button.place(x=0, y=217)

        self.save_button = Button(self.root, text="SAVE", bg="white", bd=4, command=self.save_paint, width=8, relief=RIDGE)
        self.save_button.place(x=0, y=247)

        self.canvas_color_button = Button(self.root, text="CANVAS", bg="white", bd=4, command=self.canvas, width=8, relief=RIDGE)
        self.canvas_color_button.place(x=0, y=277)

        #Creating a scale for pen and eraser size

        self.pen_size_scale_frame = LabelFrame(self.root, text="size", bd=5, bg="white", font=("arial", 15, 'bold'), relief=RIDGE)
        self.pen_size_scale_frame.place(x=0, y=310, height=200, width=70)

        self.pen_size = Scale(self.pen_size_scale_frame, orient=VERTICAL, from_=50, to_=0, length=170)
        self.pen_size.set(1)
        self.pen_size.grid(row=0, column=1, padx=15)

        #Creating Canvas

        self.canvas = Canvas(self.root, bg="white", bd=5, relief=GROOVE, height=500, width=700)
        self.canvas.place(x=80, y=0)

        #Bind the canvas with mouse drag
        self.canvas.bind("<B1-Motion>", self.paint)
    def __init__(self, master, **kw):
        self.__multiplyValue = kw.pop("multiplyValue", False)

        twoRows = kw.pop("twoRows", False)

        kw["columns"] = 1 if twoRows else 3
        kw["rows"] = 1

        valueIsNone = "value" not in kw

        SmartWidget._setVariable(kw, "IntVar")

        self.__frame = Frame(master) if twoRows else None

        super().__init__(master, **kw)

        if self.__frame:
            master = self.__frame

        # = Step = #
        self.__step = kw.get("step", 1)

        # = Caption = #
        self.__caption = Label(master, text=kw["text"])
        self.__valueLabel = Label(master, anchor=E)

        # = Scale = #
        self.getRawValue().trace_add("write", self.onChanged)

        storage = self._getValueStorage()

        for index, key in enumerate(("from_", "to")):
            if key in storage:
                kw["range"][index] = storage[key]

        self.getRawValue().set(
            StaticUtils.setIfAbsentAndGet(
                storage, "value",
                (kw["range"][0] if valueIsNone else self.getValue()) //
                self.__step))

        from_, to = tuple(v // self.__step for v in kw["range"])

        self.__scale = Scale(master,
                             from_=from_,
                             length=400,
                             to=to,
                             variable=self.getRawValue())

        if "state" in kw:
            self.__scale["state"] = kw["state"]

        self.__setValueWidth()
Example #8
0
 def _criar_scale(self):
     '''
     Criar widget Scale.
     '''
     self._scale = Scale(self, from_=self.MINIMO, 
                                 to=self.MAXIMO, 
                             orient='horizontal')
     
     self._scale['command'] = lambda e: \
         self.set_atual(self._scale.get(), widget=self._scale)  
                                     
     self._scale.pack(side='left', fill='x', anchor='center', expand=True, )
Example #9
0
    def __init__(self, *args, **kwargs):
        self.__i_range   =   i_range  = kwargs.pop('i_range')
        self.__q_range   =   q_range  = kwargs.pop('q_range')
        Frame.__init__(self, *args, **kwargs)
        Observable.__init__(self)
                       
        self.__canvas   = canvas    = ComplexCanvas(self)

        canvas.grid(row=0, column=0, sticky='wens')
        canvas['bg']    = 'black'

        self.__q_slider  = q_slider   = Scale(self, from_=q_range, to=-q_range, orient='vertical')

        q_slider.grid(row=0, column=1, sticky='e')
        self.__i_slider  = i_slider   = Scale(self, from_=-i_range, to=i_range, orient='horizontal')        

        i_slider.grid(row=1, column=0, sticky='s')
        
        self.grid_rowconfigure(0, weight=1)
        self.grid_columnconfigure(0, weight=1)
        
        self.__pad  = 10        
        self.__width    = 0
        self.__height   = 0
        self.__center   = None
        self.__radius   = 0
        self.__bbox     = None
        
        self.__complex_magnitude  = 0 + 0j
        
        canvas.bind('<Configure>', self._on_resize)
        self.__borderBox    = canvas.create_rectangle(0, 0, 10, 10, outline='green')        
        self.__borderCircle = canvas.create_oval(0, 0, 10, 10, outline='green', dash=[1, 2])
        self.__middleCircle = canvas.create_oval(0, 0, 10, 10, outline='green', dash=[1, 2])
        self.__vLine        = canvas.create_line(0, 0, 10, 10, fill='green', dash=[1, 2])
        self.__hLine        = canvas.create_line(0, 0, 10, 10, fill='green', dash=[1, 2])
        self.__dLine        = canvas.create_line(0, 0, 10, 10, fill='green', dash=[1, 2])
        self.__cdLine       = canvas.create_line(0, 0, 10, 10, fill='green', dash=[1, 2])
        self.__scale_circles = []
        for k in range(60):
            if k % 5 == 0:
                color   = 'gold'
            else:
                color   = 'green'
            self.__scale_circles.append(canvas.create_oval(0, 0, 10, 10, fill=color))
            
        self.__indicator1   = self.Indicator(self, solid=False)
        self.__indicator2   = self.Indicator(self)
        
        canvas.bind('<Motion>', self._on_mouse_move)
        canvas.bind('<Button-1>', self._on_click)
        i_slider['command']  = self._on_iq_scale
        q_slider['command']  = self._on_iq_scale
Example #10
0
    def __init__(self):
        self.root= Tk()
        self.root.title("My Paint")
        self.root.geometry("800x500")
        self.size=Canvas(self.root, width=800, height=500)
        self.root.configure(bg="white")

        self.pen_color="black"
        self.eraser_color="white"
        
        
        self.color_frame=LabelFrame(self.root, text="Color", font=('arial', 15, 'bold'), bd=5, relief=RIDGE, bg="#6FA5F5")
        self.color_frame.place(x=10, y=400, width=240, height=90)

        colors=['white', 'black', 'brown','red', 'orange','yellow','green', 'blue', '#3E1C91', '#F20A85']
        i=j=0
        for color in colors:                                                            #col is value of color
            Button(self.color_frame, bg=color, bd=2, relief=RIDGE, width=5, command=lambda col= color: self.select_color(col)).grid(row=i, column=j)
            j+=1
            if j==5:
                j=0
                i=1

        self.edit_color_button=Button(self.root, text="Edit Color",font=('arial', 11, 'bold'), bd=3, bg="#6FA5F5", command=self.edit_color, width=12,height=2, relief=RIDGE)
        self.edit_color_button.place(x=255, y=400)

        self.eraser_button=Button(self.root, text="Eraser",font=('arial', 11, 'bold'), bd=3, bg="#6FA5F5", command=self.eraser, width=12,height=2, relief=RIDGE)
        self.eraser_button.place(x=255, y=445)

        self.clear_button=Button(self.root, text="Clear",font=('arial', 11, 'bold'), bd=3, bg="#6FA5F5", command=lambda : self.canvas.delete("all"), width=12,height=2, relief=RIDGE)
        self.clear_button.place(x=355, y=400)

        self.save_button=Button(self.root, text="Save",font=('arial', 11, 'bold'), bd=3, bg="#6FA5F5", command=self.save_paint, width=12,height=2, relief=RIDGE)
        self.save_button.place(x=355, y=445)

        

        self.pen_size_scale_frame=LabelFrame(self.root, text="size", bd=5, bg="#6FA5F5", font=('areal',15,'bold'), relief=RIDGE)
        self.pen_size_scale_frame.place(x=480, y=400, height=70, width=250)

        self.pen_size=Scale(self.pen_size_scale_frame, orient=HORIZONTAL, from_=0, to=50, length=220)
        self.pen_size.set(1)
        self.pen_size.grid(row=0, column=1, padx=15)

        self.canvas=Canvas(self.root, bg='white', bd=5, relief=GROOVE, height=380, width=787)
        self.canvas.place(x=0, y=0)

        #self.setup()
        self.canvas.bind('<B1-Motion>', self.paint)
        

        self.root.mainloop()
Example #11
0
    def initUI(self):
        self.master.title("Scale")
        self.style = Style()
        self.style.theme_use("default")

        self.pack(fill=BOTH, expand=1)

        scale = Scale(self, from_=0, to=100, command=self.on_scale)
        scale.pack(side=LEFT, padx=15)

        self.var = IntVar()
        self.label = Label(self, text=0, textvariable=self.var)
        self.label.pack(side=LEFT)
Example #12
0
    def __init__(self, root):
        self.root = root
        self.root.title("paint")
        self.root.geometry("800x520")
        self.root.configure(background="white")
        self.root.resizable(0,0)

        self.pen_color = "black"
        self.eraser_color = "white"
        #adding widges to paint

        self.color_frame = LabelFrame(self.root,text='Color',font = ('Times New Roman',15),bd=5,relief=RIDGE,bg="white")
        self.color_frame.place(x=0,y=0,width=70,height=195)
        colors = ['red','black','pink','blue','grey','cyan','brown','yellow','purple','hotpink','green','olive','plum','indigo']
        i=j=0
        for color in colors:
            Button(self.color_frame,bg=color,bd=1,relief=RIDGE,width=3,command=lambda col =color:self.select_color(col)).grid(row=i,column=j)
            i+=1
            if i==7:
                i=0
                j+=1
        self.eraser_button = Button(self.root,text="ERASER",bd=4,bg="white",command=self.eraser,width=8,relief=RIDGE)
        self.eraser_button.place(x=0,y=192)

        self.clear_button = Button(self.root, text="CLEAR", bd=4, bg="white", command=lambda : self.canvas.delete("all"), width=8, relief=RIDGE)
        self.clear_button.place(x=0, y=222)

        self.save_button = Button(self.root, text="SAVE", bd=4, bg="white", command=None, width=8, relief=RIDGE)
        self.save_button.place(x=0, y=252)

        self.canvas_color_button = Button(self.root, text="FILL", bd=4, bg="white", command=self.canvas_color, width=8, relief=RIDGE)
        self.canvas_color_button.place(x=0, y=282)

        #creating a Scale for pen and Eraser Size

        self.pen_size_scale_frame = LabelFrame(self.root,text="size",bd=5,bg="white",font=('Times New Roman',15,'bold'),relief=RIDGE)
        self.pen_size_scale_frame.place(x=0,y=313,height=200,width=70)

        self.pen_size = Scale(self.pen_size_scale_frame,orient=VERTICAL,from_=50,to=0,length=170)
        self.pen_size.set(1)
        self.pen_size.grid(row=0,column=1,padx=15)

        #creating canvas

        self.canvas = Canvas(self.root,bg="white",bd=5,relief=GROOVE,height=500,width=700)
        self.canvas.place(x=80,y=0)

        #bind canvas with mouse drag
        self.canvas.bind("<B1-Motion>",self.paint)
Example #13
0
    def initUI(self):
        self.master.title("Scale")
        self.style = Style()
        self.style.theme_use("default")

        self.pack(fill=BOTH, expand=True)

        self.scale = Scale(self, from_=0, to=100, command=self.onScale)
        self.scale.grid(row=0, column=0, padx=10, pady=10, sticky=E + W)

        self.var = IntVar()
        self.label = Label(self, text=0, textvariable=self.var)
        self.label.grid(row=0, column=1, sticky=W, padx=10)

        self.grid_columnconfigure(0, weight=1)
    def __init__(self, *args, **kwargs):
        default_range = kwargs.pop("default_range", (60, 90))

        super().__init__(*args, **kwargs)

        color_list = ["green", "yellow"]
        label_list = []
        scale_list = []

        range_list = [*default_range]

        def on_scale0(value):
            value = int(float(value))
            if value > range_list[1]:
                scale_list[1].set(value)
                label_list[1]["text"] = f"{value: 3d}%"
            range_list[0] = value
            label_list[0]["text"] = f"{value: 3d}%"

        def on_scale1(value):
            value = int(float(value))
            if value < range_list[0]:
                scale_list[0].set(value)
                label_list[0]["text"] = f"{value: 3d}%"
            range_list[1] = value
            label_list[1]["text"] = f"{value: 3d}%"

        callback_list = [on_scale0, on_scale1]

        for index in range(2):
            frame = Frame(self)
            frame.pack(expand="yes", fill="x")
            label = Label(frame,
                          bg=color_list[index],
                          text=f"{default_range[index]: 3d}%",
                          width=5)
            label.pack(side="left")
            label_list.append(label)
            scale = Scale(frame,
                          from_=0,
                          to=100,
                          value=default_range[index],
                          orient="horizontal",
                          command=callback_list[index])
            scale.pack(side="left", fill="x", expand="yes")
            scale_list.append(scale)

        self.__scale_list = scale_list
Example #15
0
    def make_slider(self, name, valmin, valmax, valinit, valfmt, label, forceint):
        from tkinter import IntVar, DoubleVar, StringVar
        from tkinter.ttk import Label, Scale, Frame
        if self.slider_frame is None:
            frame = self.slider_frame = Frame(self.widget_frame, )
        else:
            frame = self.slider_frame

        if forceint:
            v = IntVar(self.widget_frame)
        else:
            v = DoubleVar(self.widget_frame)

        s = self._scales[name] = Scale(frame, variable=v, from_=valmin, to=valmax, length=250)

        num_sv = StringVar(self.widget_frame)

        def label_callback(*args):
            num_sv.set(valfmt % v.get())

        v.trace_variable('w', label_callback)

        nl = self._labels[name + 'num'] = Label(frame, textvariable=num_sv, width=6, anchor='e')
        tl = self._labels[name + 'text'] = Label(frame, text=label if label is not None else name, anchor='w')
        v.set(valinit)
        nl.grid(column=0, row=self.slider_row, sticky='e')
        s.grid(column=1, row=self.slider_row)
        tl.grid(column=2, row=self.slider_row, sticky='w')
        self.slider_row += 1
        frame.pack()
        return TkWidgetWrapper(s, forceint)
Example #16
0
    def _create_bottomframe(self) -> None:
        self.bottomframe = Frame(self.rightframe)
        self.bottomframe.pack()

        self.mutePhoto = PhotoImage(file=self.assets_path + '/icons/mute.png')
        self.volumePhoto = PhotoImage(file=self.assets_path + '/icons/volume.png')
        self.volumeBtn = Button(self.bottomframe, image=self.volumePhoto, command=self.mute_music)
        self.volumeBtn.grid(row=0, column=1)

        self.rewindPhoto = PhotoImage(file=self.assets_path + '/icons/rewind.png')
        rewindBtn = Button(self.bottomframe, image=self.rewindPhoto, command=self.rewind_music)
        rewindBtn.grid(row=0, column=0)

        self.scale = Scale(self.bottomframe, from_=0, to=100, orient=HORIZONTAL, command=self.set_vol)
        self.scale.set(self.init_vol)
        mixer.music.set_volume(self.init_vol / 100)
        self.scale.grid(row=0, column=2, pady=15, padx=30)
Example #17
0
	def __build_fog_slider(self):
		""" Builds a slider that allows the user to adjust light intensity
			on the scene
		"""
		can = self.canvas
		self.add_title('Fog Scalar',6)
		
		def adjust(event=None):
			d = 1
			s = int(fog_meter.get())
			can.config('lighting').set_fog_scale(s)
			if s > 0 and s != 70:
				textvar.set("Fog Magnitude: "+str(s))
			elif s == 70:
				textvar.set("Fog Magnitude: :)")
			else:
				textvar.set("Fog Magnitude: OFF")
			can.update_idletasks()
		
		fog_meter = Scale( self, to = 120, from_ = 0, length = 200 )
		fog_meter.grid(row=7,column=0)
		textvar = tk.StringVar()
		textvar.set("Darkness: 0")
		tk.Label(self,textvariable=textvar).grid(row=7,column=1)
		fog_meter.set(0)
		fog_meter.configure(command=adjust)
Example #18
0
	def __build_lightness_slider(self):
		""" Builds a slider that allows the user to adjust light intensity
			on the scene
		"""
		can = self.canvas
		self.add_title('Light Brightness',4)
		
		def adjust(event=None):
			d = 1
			s = int(light_meter.get())
			pos = can.config('lighting').get_lighting_parameters()[2][0]
			can.config('lighting').clear()
			can.create_light([s,s,s,s],Lighting.Point,position=pos,sharpness=4)

			can.create_light([s,s,s,s],Lighting.Ambient)
			textvar.set("Brightness: "+str(s))
			can.update_idletasks()
		
		light_meter = Scale( self, to = 255, from_ = 1, length = 200 )
		light_meter.grid(row=5,column=0)
		textvar = tk.StringVar()
		textvar.set("Brightness: 178")
		tk.Label(self,textvariable=textvar).grid(row=5,column=1)
		light_meter.set(178)
		light_meter.configure(command=adjust)
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.imageName = ""

        self.w = Scale(parent, from_=1, to=100, orient=HORIZONTAL)
        self.w.place(x=600, y=140)
        self.w.set(100)

        GPIO.setup(self.Motor1A, GPIO.OUT)
        GPIO.setup(self.Motor1B, GPIO.OUT)
        GPIO.setup(self.Motor1E, GPIO.OUT)

        GPIO.setup(self.Motor2A, GPIO.OUT)
        GPIO.setup(self.Motor2B, GPIO.OUT)
        GPIO.setup(self.Motor2E, GPIO.OUT)

        self.initUI()
Example #20
0
    def initialize(self):
        self.slider = Scale(self.root, orient=VERTICAL, from_=self.min, to=self.max, value=float(self.gain.get()), command=self._updateValue)
        self.slider.grid(row=0,column=self.id, padx=10)

        self.valueLbl = Label(self.root, anchor="w", textvariable=self.value)
        self.valueLbl.grid(row=1,column=self.id, padx=10)

        self.freqLbl = Label(self.root,text=str(self.freq)+" Hz")
        self.freqLbl.grid(row=2,column=self.id, padx=10)
Example #21
0
    def onClick(self):
        if self.columns.get() == 0:
            self.scale = Scale(self,
                               from_=1,
                               to=self.clades.get() - 1,
                               command=self.onScale,
                               orient=HORIZONTAL)
            self.scale.grid(sticky=W, row=3, column=2)

            self.labScale = Label(
                self, text="Number of clades in the first column: ")
            self.labScale.grid(sticky=W, row=2, column=2)

            self.ScaleVal = Label(self, textvariable=self.var)
            self.ScaleVal.grid(sticky=E, row=2, column=2)

        else:
            self.scale.grid_remove()
            self.labScale.grid_remove()
            self.ScaleVal.grid_remove()
Example #22
0
class ConfidenceScale(Frame):
    def __init__(self, master, **kw):
        super().__init__(master)

        # self.grid_propagate(0)
        # self.columnconfigure(0, weight=1)
        # self.rowconfigure(0, weight=1)

        self.var = kw.get('variable', IntVar())
        kw['variable'] = self.var
        kw['from_'] = ConfidenceLevel.Low.value
        kw['to'] = ConfidenceLevel.VeryHigh.value
        # kw['command'] = self.scale_change
        kw['orient'] = HORIZONTAL

        self.lbl_scale = Label(self)
        self.scale = Scale(self, **kw)

        self.scale_font = tkfont.nametofont(Style().lookup('TLabel',
                                                           'font')).copy()
        self.scale_font.config(weight=tkfont.BOLD, size=9)
        self.lbl_scale.config(font=self.scale_font, width=3, anchor=CENTER)
        self.var.trace_variable('w', lambda a, b, c: self.scale_change())

        self.scale.grid(row=0, column=0, sticky='ns')
        self.lbl_scale.grid(row=0, column=1, sticky='ns', padx=(3, 0))

    def scale_change(self):
        rval = self.get()

        if rval >= ConfidenceLevel.High:
            fg = '#4CAF50'
        elif rval >= ConfidenceLevel.Medium:
            fg = '#FF9800'
        else:
            fg = '#FF5722'
        self.lbl_scale.config(foreground=fg, text=str(rval))

    def get(self):
        return round(float(self.var.get()))
Example #23
0
class SliderFrequency(Frame):
    def __init__(self,root, freq, val, Min=0.0, Max=1.0, sId=0):
        Frame.__init__(self,root)

        self.root = root

        self.id = sId
        self.freq = freq
        self.min = Min
        self.max = Max
        self.gain = StringVar()
        self.gain.set(val)
        self.value = StringVar()
        self.value.set( str(self._Gain(val))+" dB")

        self.initialize()
        self.gain.set(self._Gain(val))

    def initialize(self):
        self.slider = Scale(self.root, orient=VERTICAL, from_=self.min, to=self.max, value=float(self.gain.get()), command=self._updateValue)
        self.slider.grid(row=0,column=self.id, padx=10)

        self.valueLbl = Label(self.root, anchor="w", textvariable=self.value)
        self.valueLbl.grid(row=1,column=self.id, padx=10)

        self.freqLbl = Label(self.root,text=str(self.freq)+" Hz")
        self.freqLbl.grid(row=2,column=self.id, padx=10)

    def _updateValue(self,event):
        self.gain.set(self._Gain(self.slider.get()))
        self.value.set(str(self.gain.get())+" dB")
        self.valueLbl.update()

    def _Gain(self, value):
        v = -(float(value)-((self.max-self.min)/2))
        v = int(v*10)/10
        return v

    def getGain(self):
        return float(self.gain.get())
Example #24
0
    def initUI(self):
        self.master.title("Scale")
        self.style = Style()
        self.style.theme_use("default")

        self.frame = Frame(height=10, width=100, relief=SUNKEN)
        self.frame.pack(fill=X, expand=1)
        self.frame.grid_columnconfigure(0, weight=1)

        self.scale = Scale(self.frame, from_=0, to=100, command=self.onScale)
        self.scale.grid(row=0,
                        column=0,
                        columnspan=2,
                        padx=10,
                        pady=10,
                        sticky=E + W)
        #scale.pack(fill=X, padx=15, expand=1)
        #scale.pack(fill=X, padx=15)

        self.var = IntVar()
        self.label = Label(self.frame, text=0, textvariable=self.var)
        self.label.grid(row=0, column=2, sticky=W, padx=10)
Example #25
0
    def _create_master(self):
        output_device = self.player.get_output_device()

        master_frame = LabelFrame(self,
                                  text="Master",
                                  relief=tkinter.GROOVE,
                                  borderwidth=5)

        Label(master_frame, text="Volume").pack()

        vol_tracker = tkinter.DoubleVar()
        vol_tracker.set(self.player.volume)

        Scale(
            master_frame,
            variable=vol_tracker,
            from_=1.0,
            to=0.0,
            orient=tkinter.VERTICAL,
            command=self.player.set_volume,
        ).pack()

        Label(master_frame, text=f"Device: {output_device['name']}").pack()

        Label(master_frame, text=f"Channels: {self.player.channels}").pack()

        Label(master_frame,
              text=f"Sample Rate: {output_device['default_samplerate']}Hz"
              ).pack()

        Label(master_frame,
              text=f"Block Size: {self.player.stream.blocksize}").pack()

        Label(master_frame,
              text=f"Latency: {self.player.stream.latency * 1000}ms").pack()

        graph_frame = self._create_graph_frame(
            master_frame, lambda: self.player.master_sample)
        graph_frame.pack()

        self.plot_frames.append(graph_frame)

        return master_frame
Example #26
0
    def Sliders(self, txt, value, x, y, bind_func, **kw):
        kw = var_check(kw)

        self.Labels(txt, x, y, relwidth=0.2)
        self.widget_frame.value = DoubleVar()
        self.widget_frame.value.set(value)

        self.widget_frame.scale = Scale(self.widget_frame,
                                        variable=self.widget_frame.value,
                                        from_=0,
                                        to=value * 10,
                                        orient=kw["slider_orient"])

        self.widget_frame.scale.bind("<B1-Motion>", bind_func)
        self.widget_frame.scale.place(relx=x + 0.2,
                                      rely=y,
                                      anchor=kw['anchor'],
                                      relwidth=kw['relwidth'],
                                      relheight=kw['relheight'])

        return self.widget_frame.value
Example #27
0
class paint(object):
    DEFAULT_PEN_SIZE = 10.0
    
    def __init__(self):
        self.root= Tk()
        self.root.title("My Paint")
        self.root.geometry("800x500")
        self.size=Canvas(self.root, width=800, height=500)
        self.root.configure(bg="white")

        self.pen_color="black"
        self.eraser_color="white"
        
        
        self.color_frame=LabelFrame(self.root, text="Color", font=('arial', 15, 'bold'), bd=5, relief=RIDGE, bg="#6FA5F5")
        self.color_frame.place(x=10, y=400, width=240, height=90)

        colors=['white', 'black', 'brown','red', 'orange','yellow','green', 'blue', '#3E1C91', '#F20A85']
        i=j=0
        for color in colors:                                                            #col is value of color
            Button(self.color_frame, bg=color, bd=2, relief=RIDGE, width=5, command=lambda col= color: self.select_color(col)).grid(row=i, column=j)
            j+=1
            if j==5:
                j=0
                i=1

        self.edit_color_button=Button(self.root, text="Edit Color",font=('arial', 11, 'bold'), bd=3, bg="#6FA5F5", command=self.edit_color, width=12,height=2, relief=RIDGE)
        self.edit_color_button.place(x=255, y=400)

        self.eraser_button=Button(self.root, text="Eraser",font=('arial', 11, 'bold'), bd=3, bg="#6FA5F5", command=self.eraser, width=12,height=2, relief=RIDGE)
        self.eraser_button.place(x=255, y=445)

        self.clear_button=Button(self.root, text="Clear",font=('arial', 11, 'bold'), bd=3, bg="#6FA5F5", command=lambda : self.canvas.delete("all"), width=12,height=2, relief=RIDGE)
        self.clear_button.place(x=355, y=400)

        self.save_button=Button(self.root, text="Save",font=('arial', 11, 'bold'), bd=3, bg="#6FA5F5", command=self.save_paint, width=12,height=2, relief=RIDGE)
        self.save_button.place(x=355, y=445)

        

        self.pen_size_scale_frame=LabelFrame(self.root, text="size", bd=5, bg="#6FA5F5", font=('areal',15,'bold'), relief=RIDGE)
        self.pen_size_scale_frame.place(x=480, y=400, height=70, width=250)

        self.pen_size=Scale(self.pen_size_scale_frame, orient=HORIZONTAL, from_=0, to=50, length=220)
        self.pen_size.set(1)
        self.pen_size.grid(row=0, column=1, padx=15)

        self.canvas=Canvas(self.root, bg='white', bd=5, relief=GROOVE, height=380, width=787)
        self.canvas.place(x=0, y=0)

        #self.setup()
        self.canvas.bind('<B1-Motion>', self.paint)
        

        self.root.mainloop()

        
        #dragging of mouse
    def paint(self, event):
        x1, y1=(event.x-2), (event.y-2)
        x2, y2=(event.x+2),(event.y+2)

        self.canvas.create_oval(x1, y1, x2, y2, fill=self.pen_color, outline=self.pen_color, width=self.pen_size.get())
        
        
    def select_color(self, col):
        self.pen_color=col

    def eraser(self):
        self.pen_color=self.eraser_color

    def edit_color(self):
        color=colorchooser.askcolor()
        self.pen_color=color[1]

    def save_paint(self):
        try:
            #self.canvas.update()
            filename = filedialog.asksaveasfilename(defaultextension='.jpg')
            #print(filename)
            x = self.root.winfo_rootx() + self.canvas.winfo_x()
            #print(x, self.canvas.winfo_x())
            y = self.root.winfo_rooty() + self.canvas.winfo_y()
            #print(y)
            x1 = x + self.canvas.winfo_width()
            #print(x1)
            y1 = y + self.canvas.winfo_height()
            #print(y1)
            ImageGrab.grab().crop(x, y, x1, y1).save(filename)
            messagebox.showinfo('paint says image is saved as ', + str(filename))
            
        except:
            messagebox.showerror("paint says", "unable to save image, \n something went wrong")
    def __init__(self, root):
        self.root = root
        self.root.title("Paint")
        self.root.geometry("800x520")
        self.root.configure(background="white")
        self.root.resizable(0, 0)

        self.pen_color = "#000000"

        self.color_frame = LabelFrame(self.root,
                                      text="Color",
                                      font=('arial', 15, 'bold'),
                                      bd=5,
                                      relief=RIDGE,
                                      bg='white')
        self.color_frame.place(x=0, y=0, width=70, height=185)

        Colors = [
            '#ff0000',
            '#ff4dd2',
            '#ffff33',
            '#000000',
            '#0066ff',
            '#660033',
            '#4dff4d',
            '#b300b3',
            '#00ffff',
            '#808080',
            '#99ffcc',
            '#336600',
            '#ff9966',
            '#ff99ff',
            '#00cc99',
        ]
        i = j = 0
        for color in Colors:
            Button(self.color_frame,
                   bg=color,
                   command=lambda col=color: self.select_color(col),
                   width=3,
                   bd=2,
                   relief=RIDGE).grid(row=i, column=j)
            i += 1
            if i == 6:
                i = 0
                j = 1

        self.erase_button = Button(self.root,
                                   text="Eraser",
                                   bd=4,
                                   relief=RIDGE,
                                   width=8,
                                   command=self.eraser,
                                   bg="white")
        self.erase_button.place(x=0, y=187)

        self.clear_sreen_button = Button(
            self.root,
            text="Clear",
            bd=4,
            relief=RIDGE,
            width=8,
            command=lambda: self.canvas.delete("all"),
            bg="white")
        self.clear_sreen_button.place(x=0, y=217)

        self.save_button = Button(self.root,
                                  text="Save",
                                  bd=4,
                                  relief=RIDGE,
                                  width=8,
                                  command=self.save_paint,
                                  bg="white")
        self.save_button.place(x=0, y=247)

        self.canvas_color_button = Button(self.root,
                                          text="Canvas",
                                          bd=4,
                                          relief=RIDGE,
                                          width=8,
                                          command=self.canvas_color,
                                          bg="white")
        self.canvas_color_button.place(x=0, y=277)

        self.pen_size_scale_frame = LabelFrame(self.root,
                                               text="Size",
                                               bd=5,
                                               relief=RIDGE,
                                               bg="white",
                                               font=('arial', 15, 'bold'))
        self.pen_size_scale_frame.place(x=0, y=310, height=200, width=70)

        self.pen_size = Scale(self.pen_size_scale_frame,
                              orient='vertical',
                              from_=50,
                              to=0,
                              command=None,
                              length=170)
        self.pen_size.set(1)
        self.pen_size.grid(row=0, column=1, padx=15)

        self.canvas = Canvas(self.root,
                             bg='white',
                             bd=5,
                             relief='groove',
                             height=500,
                             width=700)
        self.canvas.place(x=80, y=0)

        # Blind mouse dragging event to canvas
        self.canvas.bind("<B1-Motion>", self.paint)
class Paint():
    def __init__(self, root):
        self.root = root
        self.root.title("Paint")
        self.root.geometry("800x520")
        self.root.configure(background="white")
        self.root.resizable(0, 0)

        self.pen_color = "#000000"

        self.color_frame = LabelFrame(self.root,
                                      text="Color",
                                      font=('arial', 15, 'bold'),
                                      bd=5,
                                      relief=RIDGE,
                                      bg='white')
        self.color_frame.place(x=0, y=0, width=70, height=185)

        Colors = [
            '#ff0000',
            '#ff4dd2',
            '#ffff33',
            '#000000',
            '#0066ff',
            '#660033',
            '#4dff4d',
            '#b300b3',
            '#00ffff',
            '#808080',
            '#99ffcc',
            '#336600',
            '#ff9966',
            '#ff99ff',
            '#00cc99',
        ]
        i = j = 0
        for color in Colors:
            Button(self.color_frame,
                   bg=color,
                   command=lambda col=color: self.select_color(col),
                   width=3,
                   bd=2,
                   relief=RIDGE).grid(row=i, column=j)
            i += 1
            if i == 6:
                i = 0
                j = 1

        self.erase_button = Button(self.root,
                                   text="Eraser",
                                   bd=4,
                                   relief=RIDGE,
                                   width=8,
                                   command=self.eraser,
                                   bg="white")
        self.erase_button.place(x=0, y=187)

        self.clear_sreen_button = Button(
            self.root,
            text="Clear",
            bd=4,
            relief=RIDGE,
            width=8,
            command=lambda: self.canvas.delete("all"),
            bg="white")
        self.clear_sreen_button.place(x=0, y=217)

        self.save_button = Button(self.root,
                                  text="Save",
                                  bd=4,
                                  relief=RIDGE,
                                  width=8,
                                  command=self.save_paint,
                                  bg="white")
        self.save_button.place(x=0, y=247)

        self.canvas_color_button = Button(self.root,
                                          text="Canvas",
                                          bd=4,
                                          relief=RIDGE,
                                          width=8,
                                          command=self.canvas_color,
                                          bg="white")
        self.canvas_color_button.place(x=0, y=277)

        self.pen_size_scale_frame = LabelFrame(self.root,
                                               text="Size",
                                               bd=5,
                                               relief=RIDGE,
                                               bg="white",
                                               font=('arial', 15, 'bold'))
        self.pen_size_scale_frame.place(x=0, y=310, height=200, width=70)

        self.pen_size = Scale(self.pen_size_scale_frame,
                              orient='vertical',
                              from_=50,
                              to=0,
                              command=None,
                              length=170)
        self.pen_size.set(1)
        self.pen_size.grid(row=0, column=1, padx=15)

        self.canvas = Canvas(self.root,
                             bg='white',
                             bd=5,
                             relief='groove',
                             height=500,
                             width=700)
        self.canvas.place(x=80, y=0)

        # Blind mouse dragging event to canvas
        self.canvas.bind("<B1-Motion>", self.paint)

    def paint(self, event):
        global pen_color
        x1, y1 = (event.x - 2), (event.y - 2)
        x2, y2 = (event.x + 2), (event.y + 2)
        if (i):
            self.canvas.config(cursor='plus')
        self.canvas.create_oval(x1,
                                y1,
                                x2,
                                y2,
                                fill=self.pen_color,
                                outline=self.pen_color,
                                width=self.pen_size.get())

    def select_color(self, col):
        global i
        i = 1
        self.pen_color = col

    def eraser(self):
        global color
        global i
        self.pen_color = color
        self.canvas.config(cursor='dot')
        i = 0

    def canvas_color(self):
        global color
        color = colorchooser.askcolor()
        color = color[1]
        self.canvas.config(background=color)

    def save_paint(self):
        try:
            self.canvas.update()
            filename = asksaveasfilename(defaultextension='.jpg')
            print(filename)
            x = self.root.winfo_rootx() + self.canvas.winfo_x()
            #print(x)
            y = self.root.winfo_rooty() + self.canvas.winfo_y()
            #print(y)
            x1 = x + self.canvas.winfo_width()
            #print(x1)
            y1 = y + self.canvas.winfo_height()
            #print(y1)
            ImageGrab.grab().crop((x, y, x1, y1)).save(filename)
            messagebox.showinfo('paint says ',
                                'image is saved as ' + str(filename))

        except:
            pass
Example #30
0
    def __init__(self, root_frame_instance):
        super().__init__(volume_callback=self.update_volume,
                         mute_callback=self.update_mute,
                         state_callback=self.update_state)

        self.root_frame_instance = root_frame_instance

        # ______________ DISPLAY NAME ______________
        self.app_name = self.magic_root_session.app_exec

        print(f":: new session: {self.app_name}")
        # ______________ CREATE FRAME ______________
        # super(MagicSession, self).__init__(root_frame_instance)
        Frame.__init__(self, root_frame_instance)

        # _______________ NAME LABEL _______________
        self.name_label = Label(self,
                                text=self.app_name,
                                font=("Consolas", 12, "italic"))

        # _____________ VOLUME SLIDER _____________
        self.volume_slider_state = DoubleVar()

        self.volume_slider = Scale(self,
                                   variable=self.volume_slider_state,
                                   command=self._slide_volume,
                                   from_=0,
                                   to=100,
                                   takefocus=False,
                                   orient=HORIZONTAL)

        # set initial:
        self.volume_slider_state.set(self.volume * 100)

        # ______________ MUTE BUTTON ______________

        self.mute_button_state = StringVar()

        self.mute_button = Button(self,
                                  style="",
                                  textvariable=self.mute_button_state,
                                  command=self._toogle_mute,
                                  takefocus=False)

        # set initial:
        self.update_mute(self.mute)

        # _____________ SESSION STATUS _____________
        self.status_line = Frame(self, style="", width=6)

        # set initial:
        self.update_state(self.state)

        # ________________ SEPARATE ________________
        self.separate = Separator(self, orient=HORIZONTAL)

        # ____________ ARRANGE ELEMENTS ____________
        # set column[1] to take the most space
        # and make all others as small as possible:
        self.columnconfigure(1, weight=1)

        # grid
        self.name_label.grid(row=0, column=0, columnspan=2, sticky="EW")
        self.mute_button.grid(row=1, column=0)
        self.volume_slider.grid(row=1, column=1, sticky="EW", pady=10, padx=20)
        self.separate.grid(row=2, column=0, columnspan=3, sticky="EW", pady=10)
        self.status_line.grid(row=0, rowspan=2, column=2, sticky="NS")

        # _____________ DISPLAY FRAME _____________
        self.pack(pady=0, padx=15, fill='x')
Example #31
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        timer = TkTimer(widget=self, interval=200, active=False)
        
        self.__battery_images = battery_images = {}
        image_dir = Path(Scripting.root_node.get_gui_image_path('battery'))
        for image_name in ['10per', '25per', '50per', '75per', '100per',
                           '10per_charge', '25per_charge', 
                           '50per_charge', '75per_charge', '100per_charge']:
            battery_images[image_name] = ImageTk.PhotoImage(
                file=str(image_dir/(image_name+'.png')))
            
        self.__busy_images = busy_images = {}
        image_dir = Path(Scripting.root_node.get_gui_image_path('busysignal'))
        busy_images['busy'] = ImageTk.PhotoImage(file=str(image_dir/('busy'+'.png')))
        busy_images['available'] = ImageTk.PhotoImage(file=str(image_dir/('available'+'.png')))

        balloon = Scripting.root_node.gui.balloon
                        
        self.__busy_lamp = busy_lamp = Label(self)
        busy_lamp['image'] = busy_images['available']
        busy_lamp.pack(side='right', fill='y')
        
        balloon.bind_widget(busy_lamp, balloonmsg='''Main-thread status.
Green: main-thread is available;
Red:   main-thread is busy.''')
        
        battery_meter = Label(self)
        battery_meter.pack(side='right', fill='y')
        battery_meter_tip = balloon.bind_widget(battery_meter, balloonmsg='Battery: ')
        def battery_meter_tip_show_callback():
            battery_status = Scripting.root_node.interfaces.os.get_battery_status()
            if battery_status is None:
                return 'No battery detected.'
            else:
                return f'{battery_status.percent}%'
        battery_meter_tip.show_callback = battery_meter_tip_show_callback
        
        self.__membar = IntVar(0)
        self.__cpubar = IntVar(0)
        self._make_cpu_mem_status()

        # Transparent Scale {
        def on_scale(val):
            Scripting.root_node.gui.console.set_opacity(val)
        trans_scale = Scale(self, from_=0.2, to=1.0, orient='horizontal', value=1, command=on_scale)
        trans_scale.pack(side='right')
        balloon.bind_widget(trans_scale, balloonmsg='Set the opacity of the console.')
        # } End Transparent Scale

        # Topmost Button {
        import tkinter
        topmost_button = tkinter.Button(self, text='TOP', relief='groove') 
        topmost_button.pack(side='right')
        
        def on_click():
            console =Scripting.root_node.gui.console
            b = console.is_topmost
            fg = 'black' if b else 'lime green'
            topmost_button['fg'] = fg
            with code_printer(True):
                console.set_topmost(not b)
            
        topmost_button['command'] = on_click
        balloon.bind_widget(topmost_button, balloonmsg='Set the console as a topmost window.')
        # } End Topmost Button 
        
        # Doc Button {
        docbtn = tkinter.Button(self, text='DOC', relief='groove')
        docbtn.pack(side='right')
        
        def on_click():
            docwin = Scripting.root_node.gui.console.doc_window
            with code_printer(True):
                docwin.show_window()
                
        docbtn['command'] = on_click
        balloon.bind_widget(docbtn, balloonmsg='Show document window.')
        #} End Doc Window        
        
        # Debug Button {
        debbtn = tkinter.Button(self, text='DEB', relief='groove')
        debbtn.pack(side='right')
        
        def on_click():
            debwin = Scripting.root_node.gui.console.debug_window
            with code_printer(True):
                debwin.show_window()
                
        debbtn['command'] = on_click
        balloon.bind_widget(debbtn, balloonmsg='Show debug window.')
        #} End Debug Button
        
        #{ Window Combo
        window_combo = Combobox(self, value=[], takefocus=1, stat='readonly')
        def on_selected(event):
            text = event.widget.get()
            wid = int(text.split(':')[1].strip())
            Scripting.root_node.gui.windows[wid].tk_object.deiconify()
        window_combo.bind('<<ComboboxSelected>>', on_selected)
        window_combo.pack(side='right', fill='y') # deiconify a window
        
        @Scripting.root_node.gui.windows.add_observer
        def on_windows_change(node, command):
            values = window_combo['values']
            if values == '':
                values = []
            if isinstance(values, tuple):
                values = list(values)
            node_id = id(node)
            if command == 'new':
                type_name = node.__class__.__name__
                values.append(f'{type_name}: {node_id}')
            elif command == 'del':
                for index, value in enumerate(values):
                    wid = int(value.split(':')[1].strip())
                    if node_id == wid:
                        del values[index]
            window_combo['values'] = values
            if len(values) > 0:
                window_combo.current(len(values)-1)
            else:
                window_combo.set('')
        #} End Window Combo
                        
        self.__lock = thread.allocate_lock()
        self.__busy = False
             
        os_node = Scripting.root_node.interfaces.os
        get_memory_usage = os_node.get_memory_usage
        get_cpu_usage    = os_node.get_cpu_usage
        get_battery_status = os_node.get_battery_status
                                
        def check_cpu_mem_battery():
            with code_printer(print_=False):
                self.__membar.set(get_memory_usage())
                self.__cpubar.set(get_cpu_usage())
                battery_status = get_battery_status()
                if battery_status:
                    percent = battery_status.percent
                    if percent > 75:
                        percent = 100
                    elif percent > 50:
                        percent = 75
                    elif percent > 25:
                        percent = 50
                    elif percent > 10:
                        percent = 25
                    else:
                        percent = 10
                    
                    charge = '_charge' if battery_status.power_plugged else ''
                    image_name = f'{percent}per{charge}'
                    image = battery_images[image_name]
                    if battery_meter['image'] != image:
                        battery_meter['image'] = image
                
        timer.divider(divide_by=10).add_observer(check_cpu_mem_battery)                
        timer.active = True
Example #32
0
    def add_widgets(self):
        #self.controls.grid(row = 0, column = 0, sticky=NE)
        self.color_frame = Frame(self.root, bd=1, relief=RIDGE, bg="white")
        #self.color_frame.place(x = 0, y = 0, width = 185, height = 70)
        self.color_frame.grid(sticky=NW, row=0, column=0, padx=15, pady=10)
        self.color_frame.config(cursor="hand2")
        #self.color_frame.pack()

        self.palette_image = PhotoImage(file='paint.png')
        self.palette_button = Button(self.root,
                                     image=self.palette_image,
                                     command=self.select_palette_color)
        #self.canvas_button.place(x = 247, y = 0)
        self.palette_button.grid(sticky="W", row=0, column=1, padx=10, pady=10)
        self.palette_button.config(cursor="hand2")
        self.palette_tooltip = CreateToolTip(
            self.palette_button, 'Select a color from the color palette')

        colors = [
            'black', 'white', '#4d4d4d', 'grey', '#990033', '#993300', 'red',
            'pink', 'orange', '#ffcc99', 'yellow', '#ffff99', 'lime',
            '#d9ffb3', 'green', '#88cc00', '#0099ff', 'turquoise', '#3333ff',
            '#6699cc', 'purple', '#bfbff2'
        ]
        i = j = 0
        for color in colors:
            Button(self.color_frame,
                   bg=color,
                   bd=2,
                   relief=RIDGE,
                   height=1,
                   width=3,
                   command=lambda col=color: self.select_color(col)).grid(
                       row=i, column=j)
            i += 1
            if i == 2:
                i = 0
                j += 1

        self.pencil_image = PhotoImage(file='pencil.png')
        self.pencil_button = Button(self.root,
                                    image=self.pencil_image,
                                    command=self.pencil)
        #self.pencil.place(x = 0, y = 187)
        self.pencil_button.grid(sticky="W", row=1, column=0, padx=16)
        self.pencil_button.config(cursor="hand2")
        self.pencil_tooltip = CreateToolTip(self.pencil_button, 'Pencil')

        self.bg_image = PhotoImage(file='bg.png')
        self.bg_button = Button(self.root,
                                image=self.bg_image,
                                command=self.bg_color)
        self.bg_button.grid(sticky="W", row=2, column=0, padx=16)
        self.bg_button.config(cursor="hand2")
        self.bg_tooltip = CreateToolTip(self.bg_button,
                                        'Change background color')

        self.eraser_image = PhotoImage(file='eraser.png')
        self.eraser_button = Button(self.root,
                                    image=self.eraser_image,
                                    command=self.eraser)
        #self.eraser.place(x = 0, y = 187)
        self.eraser_button.grid(sticky="W", row=3, column=0, padx=16)
        self.eraser_button.config(cursor="hand2")
        self.eraser_tooltip = CreateToolTip(self.eraser_button, 'Eraser')

        self.clear_image = PhotoImage(file='clear.png')
        self.clear_button = Button(self.root,
                                   image=self.clear_image,
                                   command=self.clear)
        #self.clear.place(x = 0, y = 217)
        self.clear_button.grid(sticky="W", row=4, column=0, padx=16)
        self.clear_button.config(cursor="hand2")
        self.clear_tooltip = CreateToolTip(self.clear_button,
                                           'Clear the canvas area')

        self.line_image = PhotoImage(file='line.png')
        self.line_button = Button(self.root,
                                  image=self.line_image,
                                  command=self.line)
        #self.line.place(x = 0, y = 367)
        self.line_button.grid(sticky="W", row=5, column=0, padx=16)
        self.line_button.config(cursor="hand2")
        self.line_tooltip = CreateToolTip(self.line_button, 'Draw a line')

        self.arrow_image = PhotoImage(file='arrow.png')
        self.arrow_button = Button(self.root,
                                   image=self.arrow_image,
                                   command=self.arrow)
        #self.line.place(x = 0, y = 367)
        self.arrow_button.grid(sticky="W", row=6, column=0, padx=16)
        self.arrow_button.config(cursor="hand2")
        self.arrow_tooltip = CreateToolTip(self.arrow_button, 'Draw an arrow')

        self.rectangle_image = PhotoImage(file='rectangle.png')
        self.rectangle_button = Button(self.root,
                                       image=self.rectangle_image,
                                       command=self.rectangle)
        #self.rectangle.place(x = 0, y = 307)
        self.rectangle_button.grid(sticky="W", row=7, column=0, padx=16)
        self.rectangle_button.config(cursor="hand2")
        self.rectangle_tooltip = CreateToolTip(self.rectangle_button,
                                               'Draw a rectangle')

        self.oval_image = PhotoImage(file='oval.png')
        self.oval_button = Button(self.root,
                                  image=self.oval_image,
                                  command=self.oval)
        #self.oval.place(x = 0, y = 397)
        self.oval_button.grid(sticky="W", row=8, column=0, padx=16)
        self.oval_button.config(cursor="hand2")
        self.oval_tooltip = CreateToolTip(self.oval_button,
                                          'Draw an oval/a circle')

        self.undo_image = PhotoImage(file='undo.png')
        self.undo_button = Button(self.root,
                                  image=self.undo_image,
                                  command=self.undo)
        #self.oval.place(x = 0, y = 397)
        self.undo_button.grid(sticky="W", row=9, column=0, padx=16)
        self.undo_button.config(cursor="hand2")
        self.undo_tooltip = CreateToolTip(self.undo_button, 'Undo')

        # creating a scale for pen and eraser size
        self.slider = Frame(self.root, bd=3, bg="white", relief=RIDGE)
        #self.slider.place(x = 0, y = 400)
        self.slider.grid(sticky="W", row=10, column=0, padx=16, pady=20)
        self.pen_size = Scale(self.slider,
                              orient=VERTICAL,
                              from_=50,
                              to=0,
                              length=170)
        self.pen_size.set(1)
        self.pen_size.grid(sticky="W",
                           row=10,
                           column=0,
                           ipadx=2,
                           padx=7,
                           pady=7)
        self.slider.config(cursor="hand2")
        self.slider_tooltip = CreateToolTip(self.slider, 'Size')

        # creating canvas
        self.canvas = Canvas(self.root,
                             relief=GROOVE,
                             height=self.height_value,
                             width=self.width_value,
                             bg="white")
        self.canvas.place(x=70, y=75)
        # self.canvas.grid(row = 0, column = 1)

        # bind the canvas with mouse drag
        self.canvas.bind('<B1-Motion>', self.paint)
        self.canvas.bind('<ButtonRelease-1>', self.reset)

        self.msg = Message(self.root, text=self.choice, width=70, bg="white")
        self.msg.grid(sticky="W", row=11, column=0)

        menu = Menu(self.root)
        self.root.config(menu=menu)
        filemenu = Menu(menu)
        colormenu = Menu(menu)
        menu.add_cascade(label='File', menu=filemenu)
        filemenu.add_command(label='Save File', command=self.save_file)
        optionmenu = Menu(menu)
        menu.add_cascade(label='Options', menu=optionmenu)
        optionmenu.add_command(label='Exit', command=self.root.destroy)
Example #33
0
class Paint(object):
    def __init__(self, root):
        self.root = root
        self.root.title("Paint")
        self.width_value = self.root.winfo_screenwidth()
        self.height_value = self.root.winfo_screenheight()
        self.root.geometry("900x700")
        self.root.configure(background='white')
        #self.root.resizable(0, 0)
        self.pen_color = "black"
        self.eraser_color = "white"
        self.save_color = "black"
        self.old_x = None
        self.old_y = None
        self.stack = []
        self.line_stack = []
        self.item = None
        self.choice = "    Pencil"
        self.add_widgets()

    def add_widgets(self):
        #self.controls.grid(row = 0, column = 0, sticky=NE)
        self.color_frame = Frame(self.root, bd=1, relief=RIDGE, bg="white")
        #self.color_frame.place(x = 0, y = 0, width = 185, height = 70)
        self.color_frame.grid(sticky=NW, row=0, column=0, padx=15, pady=10)
        self.color_frame.config(cursor="hand2")
        #self.color_frame.pack()

        self.palette_image = PhotoImage(file='paint.png')
        self.palette_button = Button(self.root,
                                     image=self.palette_image,
                                     command=self.select_palette_color)
        #self.canvas_button.place(x = 247, y = 0)
        self.palette_button.grid(sticky="W", row=0, column=1, padx=10, pady=10)
        self.palette_button.config(cursor="hand2")
        self.palette_tooltip = CreateToolTip(
            self.palette_button, 'Select a color from the color palette')

        colors = [
            'black', 'white', '#4d4d4d', 'grey', '#990033', '#993300', 'red',
            'pink', 'orange', '#ffcc99', 'yellow', '#ffff99', 'lime',
            '#d9ffb3', 'green', '#88cc00', '#0099ff', 'turquoise', '#3333ff',
            '#6699cc', 'purple', '#bfbff2'
        ]
        i = j = 0
        for color in colors:
            Button(self.color_frame,
                   bg=color,
                   bd=2,
                   relief=RIDGE,
                   height=1,
                   width=3,
                   command=lambda col=color: self.select_color(col)).grid(
                       row=i, column=j)
            i += 1
            if i == 2:
                i = 0
                j += 1

        self.pencil_image = PhotoImage(file='pencil.png')
        self.pencil_button = Button(self.root,
                                    image=self.pencil_image,
                                    command=self.pencil)
        #self.pencil.place(x = 0, y = 187)
        self.pencil_button.grid(sticky="W", row=1, column=0, padx=16)
        self.pencil_button.config(cursor="hand2")
        self.pencil_tooltip = CreateToolTip(self.pencil_button, 'Pencil')

        self.bg_image = PhotoImage(file='bg.png')
        self.bg_button = Button(self.root,
                                image=self.bg_image,
                                command=self.bg_color)
        self.bg_button.grid(sticky="W", row=2, column=0, padx=16)
        self.bg_button.config(cursor="hand2")
        self.bg_tooltip = CreateToolTip(self.bg_button,
                                        'Change background color')

        self.eraser_image = PhotoImage(file='eraser.png')
        self.eraser_button = Button(self.root,
                                    image=self.eraser_image,
                                    command=self.eraser)
        #self.eraser.place(x = 0, y = 187)
        self.eraser_button.grid(sticky="W", row=3, column=0, padx=16)
        self.eraser_button.config(cursor="hand2")
        self.eraser_tooltip = CreateToolTip(self.eraser_button, 'Eraser')

        self.clear_image = PhotoImage(file='clear.png')
        self.clear_button = Button(self.root,
                                   image=self.clear_image,
                                   command=self.clear)
        #self.clear.place(x = 0, y = 217)
        self.clear_button.grid(sticky="W", row=4, column=0, padx=16)
        self.clear_button.config(cursor="hand2")
        self.clear_tooltip = CreateToolTip(self.clear_button,
                                           'Clear the canvas area')

        self.line_image = PhotoImage(file='line.png')
        self.line_button = Button(self.root,
                                  image=self.line_image,
                                  command=self.line)
        #self.line.place(x = 0, y = 367)
        self.line_button.grid(sticky="W", row=5, column=0, padx=16)
        self.line_button.config(cursor="hand2")
        self.line_tooltip = CreateToolTip(self.line_button, 'Draw a line')

        self.arrow_image = PhotoImage(file='arrow.png')
        self.arrow_button = Button(self.root,
                                   image=self.arrow_image,
                                   command=self.arrow)
        #self.line.place(x = 0, y = 367)
        self.arrow_button.grid(sticky="W", row=6, column=0, padx=16)
        self.arrow_button.config(cursor="hand2")
        self.arrow_tooltip = CreateToolTip(self.arrow_button, 'Draw an arrow')

        self.rectangle_image = PhotoImage(file='rectangle.png')
        self.rectangle_button = Button(self.root,
                                       image=self.rectangle_image,
                                       command=self.rectangle)
        #self.rectangle.place(x = 0, y = 307)
        self.rectangle_button.grid(sticky="W", row=7, column=0, padx=16)
        self.rectangle_button.config(cursor="hand2")
        self.rectangle_tooltip = CreateToolTip(self.rectangle_button,
                                               'Draw a rectangle')

        self.oval_image = PhotoImage(file='oval.png')
        self.oval_button = Button(self.root,
                                  image=self.oval_image,
                                  command=self.oval)
        #self.oval.place(x = 0, y = 397)
        self.oval_button.grid(sticky="W", row=8, column=0, padx=16)
        self.oval_button.config(cursor="hand2")
        self.oval_tooltip = CreateToolTip(self.oval_button,
                                          'Draw an oval/a circle')

        self.undo_image = PhotoImage(file='undo.png')
        self.undo_button = Button(self.root,
                                  image=self.undo_image,
                                  command=self.undo)
        #self.oval.place(x = 0, y = 397)
        self.undo_button.grid(sticky="W", row=9, column=0, padx=16)
        self.undo_button.config(cursor="hand2")
        self.undo_tooltip = CreateToolTip(self.undo_button, 'Undo')

        # creating a scale for pen and eraser size
        self.slider = Frame(self.root, bd=3, bg="white", relief=RIDGE)
        #self.slider.place(x = 0, y = 400)
        self.slider.grid(sticky="W", row=10, column=0, padx=16, pady=20)
        self.pen_size = Scale(self.slider,
                              orient=VERTICAL,
                              from_=50,
                              to=0,
                              length=170)
        self.pen_size.set(1)
        self.pen_size.grid(sticky="W",
                           row=10,
                           column=0,
                           ipadx=2,
                           padx=7,
                           pady=7)
        self.slider.config(cursor="hand2")
        self.slider_tooltip = CreateToolTip(self.slider, 'Size')

        # creating canvas
        self.canvas = Canvas(self.root,
                             relief=GROOVE,
                             height=self.height_value,
                             width=self.width_value,
                             bg="white")
        self.canvas.place(x=70, y=75)
        # self.canvas.grid(row = 0, column = 1)

        # bind the canvas with mouse drag
        self.canvas.bind('<B1-Motion>', self.paint)
        self.canvas.bind('<ButtonRelease-1>', self.reset)

        self.msg = Message(self.root, text=self.choice, width=70, bg="white")
        self.msg.grid(sticky="W", row=11, column=0)

        menu = Menu(self.root)
        self.root.config(menu=menu)
        filemenu = Menu(menu)
        colormenu = Menu(menu)
        menu.add_cascade(label='File', menu=filemenu)
        filemenu.add_command(label='Save File', command=self.save_file)
        optionmenu = Menu(menu)
        menu.add_cascade(label='Options', menu=optionmenu)
        optionmenu.add_command(label='Exit', command=self.root.destroy)

    # functions
    def change_label(self):
        self.msg.config(text=self.choice)

    def paint(self, event):
        if self.old_x and self.old_y:
            self.line_stack.append(
                self.canvas.create_line(self.old_x,
                                        self.old_y,
                                        event.x,
                                        event.y,
                                        width=self.pen_size.get(),
                                        fill=self.pen_color,
                                        capstyle=ROUND,
                                        smooth=True))

        self.oldx = self.old_x
        self.oldy = self.old_y
        self.old_x = event.x
        self.old_y = event.y
        self.newx = event.x
        self.newy = event.y

    def reset(self, event):  # reset x and y
        # self.line_stack.append(self.canvas.create_line(self.oldx, self.oldy, self.newx, self.newy, arrow = 'last', width = self.pen_size.get(), fill = self.pen_color, capstyle=ROUND, smooth=True))
        self.old_x = None
        self.old_y = None
        self.line_stack.append('#')
        # print(self.line_stack)

    def select_color(self, col):
        self.pen_color = col
        self.save_color = col

    def eraser(self):
        self.pen_color = self.eraser_color
        self.canvas.bind('<B1-Motion>', self.paint)
        self.canvas.bind('<ButtonRelease-1>', self.reset)
        self.canvas.config(cursor="dot")
        self.choice = "    Eraser"
        self.change_label()

    def select_palette_color(self):
        self.choice = "   Palette"
        self.change_label()
        color = colorchooser.askcolor()
        self.pen_color = color[1]
        self.save_color = color[1]
        #self.canvas.configure(background = color[1])
        #self.eraser_color = color[1]

    def bg_color(self):
        self.canvas.configure(background=self.pen_color)
        self.eraser_color = self.pen_color
        self.choice = "   Canvas\n    Color"
        self.change_label()

    def clear(self):
        self.canvas.configure(background="white")
        self.canvas.delete("all")

    def undo(self):
        try:
            if self.line_stack[-1] == '$':
                self.item = self.stack.pop()
                self.line_stack.pop()

            else:
                if self.line_stack[-1] == '#':
                    self.item = self.line_stack.pop()
                while (1):
                    if len(self.line_stack) == 0:
                        break
                    elif len(self.stack) != 0 or len(self.line_stack) != 0:
                        # print(self.line_stack)
                        if self.line_stack[-1] != '#' and self.line_stack[
                                -1] != '$':
                            self.item = self.line_stack.pop()
                            self.canvas.delete(self.item)
                        else:
                            break
                    else:
                        break
            self.canvas.delete(self.item)

        except LookupError:
            print("LookupError: list index out of range")
        self.choice = "    Undo"
        self.change_label()

    def pencil(self):
        self.pen_color = self.save_color
        self.canvas.unbind("<Button-1>")
        self.canvas.unbind("<ButtonRelease-1>")
        self.canvas.unbind("<B1-Motion>")
        self.canvas.bind("<B1-Motion>", self.paint)
        self.canvas.bind("<ButtonRelease-1>", self.reset)
        self.canvas.config(cursor="pencil")
        self.choice = "    Pencil"
        self.change_label()

    def rectangle(self):
        self.rectx0 = 0
        self.recty0 = 0
        self.rectx1 = 0
        self.recty1 = 0
        self.rectid = None
        self.pen_color = self.save_color
        self.canvas.unbind("<Button-1>")
        self.canvas.unbind("<ButtonRelease-1>")
        self.canvas.unbind("<B1-Motion>")
        self.canvas.bind("<Button-1>", self.startRect)
        self.canvas.bind("<ButtonRelease-1>", self.stopRect)
        self.canvas.bind("<B1-Motion>", self.movingRect)
        self.canvas.config(cursor="crosshair")
        self.choice = " Rectangle"
        self.change_label()

    def startRect(self, event):
        self.rectx0 = self.canvas.canvasx(event.x)
        self.recty0 = self.canvas.canvasy(event.y)
        self.rectid = self.canvas.create_rectangle(self.rectx0,
                                                   self.recty0,
                                                   self.rectx0,
                                                   self.recty0,
                                                   outline=self.pen_color,
                                                   width=self.pen_size.get())

    def movingRect(self, event):
        self.rectx1 = self.canvas.canvasx(event.x)
        self.recty1 = self.canvas.canvasy(event.y)
        self.canvas.coords(self.rectid, self.rectx0, self.recty0, self.rectx1,
                           self.recty1)

    def stopRect(self, event):
        self.rectx1 = self.canvas.canvasx(event.x)
        self.recty1 = self.canvas.canvasy(event.y)
        self.canvas.coords(self.rectid, self.rectx0, self.recty0, self.rectx1,
                           self.recty1)
        self.stack.append(self.rectid)
        self.line_stack.append('$')

    def line(self):
        self.linex0 = 0
        self.liney0 = 0
        self.linex1 = 0
        self.liney1 = 0
        self.lineid = None
        self.pen_color = self.save_color
        self.canvas.unbind("<Button-1>")
        self.canvas.unbind("<ButtonRelease-1>")
        self.canvas.unbind("<B1-Motion>")
        self.canvas.bind("<Button-1>", self.startLine)
        self.canvas.bind("<ButtonRelease-1>", self.stopLine)
        self.canvas.bind("<B1-Motion>", self.movingLine)
        self.canvas.config(cursor="crosshair")
        self.choice = "     Line"
        self.change_label()

    def startLine(self, event):
        self.linex0 = self.canvas.canvasx(event.x)
        self.liney0 = self.canvas.canvasy(event.y)
        self.lineid = self.canvas.create_line(self.linex0,
                                              self.liney0,
                                              self.linex0,
                                              self.liney0,
                                              fill=self.pen_color,
                                              width=self.pen_size.get())

    def movingLine(self, event):
        self.linex1 = self.canvas.canvasx(event.x)
        self.liney1 = self.canvas.canvasy(event.y)
        self.canvas.coords(self.lineid, self.linex0, self.liney0, self.linex1,
                           self.liney1)

    def stopLine(self, event):
        self.linex1 = self.canvas.canvasx(event.x)
        self.liney1 = self.canvas.canvasy(event.y)
        self.canvas.coords(self.lineid, self.linex0, self.liney0, self.linex1,
                           self.liney1)
        self.stack.append(self.lineid)
        self.line_stack.append('$')

    def arrow(self):
        self.arrowx0 = 0
        self.arrowy0 = 0
        self.arrowx1 = 0
        self.arrowy1 = 0
        self.arrowid = None
        self.pen_color = self.save_color
        self.canvas.unbind("<Button-1>")
        self.canvas.unbind("<ButtonRelease-1>")
        self.canvas.unbind("<B1-Motion>")
        self.canvas.bind("<Button-1>", self.startArrow)
        self.canvas.bind("<ButtonRelease-1>", self.stopArrow)
        self.canvas.bind("<B1-Motion>", self.movingArrow)
        self.canvas.config(cursor="crosshair")
        self.choice = "     Arrow"
        self.change_label()

    def startArrow(self, event):
        self.arrowx0 = self.canvas.canvasx(event.x)
        self.arrowy0 = self.canvas.canvasy(event.y)
        self.arrowid = self.canvas.create_line(self.arrowx0,
                                               self.arrowy0,
                                               self.arrowx0,
                                               self.arrowy0,
                                               arrow='last',
                                               fill=self.pen_color,
                                               width=self.pen_size.get())

    def movingArrow(self, event):
        self.arrowx1 = self.canvas.canvasx(event.x)
        self.arrowy1 = self.canvas.canvasy(event.y)
        self.canvas.coords(self.arrowid, self.arrowx0, self.arrowy0,
                           self.arrowx1, self.arrowy1)

    def stopArrow(self, event):
        self.arrowx1 = self.canvas.canvasx(event.x)
        self.arrowy1 = self.canvas.canvasy(event.y)
        self.canvas.coords(self.arrowid, self.arrowx0, self.arrowy0,
                           self.arrowx1, self.arrowy1)
        self.stack.append(self.arrowid)
        self.line_stack.append('$')

    def oval(self):
        self.ovalx0 = 0
        self.ovaly0 = 0
        self.ovalx1 = 0
        self.ovaly1 = 0
        self.ovalid = None
        self.pen_color = self.save_color
        self.canvas.unbind("<Button-1>")
        self.canvas.unbind("<ButtonRelease-1>")
        self.canvas.unbind("<B1-Motion>")
        self.canvas.bind("<Button-1>", self.startOval)
        self.canvas.bind("<ButtonRelease-1>", self.stopOval)
        self.canvas.bind("<B1-Motion>", self.movingOval)
        self.canvas.config(cursor="crosshair")
        self.choice = "     Oval"
        self.change_label()

    def startOval(self, event):
        self.ovalx0 = self.canvas.canvasx(event.x)
        self.ovaly0 = self.canvas.canvasy(event.y)
        self.ovalid = self.canvas.create_oval(self.ovalx0,
                                              self.ovaly0,
                                              self.ovalx0,
                                              self.ovaly0,
                                              outline=self.pen_color,
                                              width=self.pen_size.get())

    def movingOval(self, event):
        self.ovalx1 = self.canvas.canvasx(event.x)
        self.ovaly1 = self.canvas.canvasy(event.y)
        self.canvas.coords(self.ovalid, self.ovalx0, self.ovaly0, self.ovalx1,
                           self.ovaly1)

    def stopOval(self, event):
        self.ovalx1 = self.canvas.canvasx(event.x)
        self.ovaly1 = self.canvas.canvasy(event.y)
        self.canvas.coords(self.ovalid, self.ovalx0, self.ovaly0, self.ovalx1,
                           self.ovaly1)
        self.stack.append(self.ovalid)
        self.line_stack.append('$')

    def save_file(self):
        try:
            filename = filedialog.asksaveasfilename(defaultextension='.png')
            '''x = self.root.winfo_rootx() + self.canvas.winfo_x()
			y = self.root.winfo_rooty() + self.canvas.winfo_y()
			x1 = x + self.canvas.winfo_width()
			y1 = y + self.canvas.winfo_height()'''
            ImageGrab.grab().save(filename)
            messagebox.showinfo('Paint', 'Image is saved as ' + str(filename))

        except:
            messagebox.showerror('Paint', 'Unable to save image!')
Example #34
0
class Dialogue(Frame):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.style = Style()
        self.style.theme_use("default")
        self.master.title("LineChart")

        self.pack(fill=BOTH, expand=True)

        self.SSU = BooleanVar()
        self.SSU.set(1)
        self.COX1 = BooleanVar()
        self.COX1.set(1)
        self.EF1A = BooleanVar()
        self.EF1A.set(1)
        self.EF1A_variants = BooleanVar()
        self.EF1A_variants.set(1)
        self.filelabel = StringVar(self, "File not chosen")
        self.filename = ""
        self.var = IntVar()
        self.var.set(1)
        self.clades = IntVar()
        self.clades.set(0)

        # self.columnconfigure(2, weight=1)
        # self.rowconfigure(2, weight=1)

        cbSSU = Checkbutton(self,
                            text="SSU",
                            variable=self.SSU,
                            state=DISABLED,
                            onvalue=1,
                            offvalue=0)
        cbSSU.select()
        cbSSU.grid(sticky=W, padx=5, pady=5)
        cbCOX1 = Checkbutton(self,
                             text="COX1",
                             variable=self.COX1,
                             onvalue=1,
                             offvalue=0)
        cbCOX1.select()
        cbCOX1.grid(sticky=W, row=1, padx=5, pady=5)
        cbEF1A = Checkbutton(self,
                             text="EF1A",
                             variable=self.EF1A,
                             onvalue=1,
                             offvalue=0)
        cbEF1A.select()
        cbEF1A.grid(sticky=W, row=2, padx=5, pady=5)
        cbEcomb = Checkbutton(self,
                              text="EF1A combinations",
                              variable=self.EF1A_variants,
                              onvalue=1,
                              offvalue=0)
        cbEcomb.select()
        cbEcomb.grid(sticky=W, row=3, padx=5, pady=5)

        openButton = Button(self, text="Choose file", command=self.onOpen)
        openButton.grid(sticky=W, row=0, column=1, padx=5, pady=5)

        labFile = Label(self, textvariable=self.filelabel)
        labFile.grid(sticky=W, row=0, column=2, columnspan=2, padx=5, pady=5)

        closeButton = Button(self, text="Exit", command=self.quit)
        closeButton.grid(sticky=E, row=4, column=3, padx=5, pady=5)

        okButton = Button(self, text="OK", command=self.onOK)
        okButton.grid(sticky=W, row=4, column=0, padx=5, pady=5)

    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 readExcel(self, filename):
        self.dataframe = read_excel(filename, index_col="Specimen")

        if self.clades.get() != 0:
            self.labClades.grid_remove()

        self.clades.set(len(set(self.dataframe.loc[:, "Clade"])))

        self.labClades = Label(self,
                               text="Number of clades: " +
                               str(self.clades.get()))
        self.labClades.grid(sticky=W, row=1, column=1, padx=5, pady=5)

    def onClick(self):
        if self.columns.get() == 0:
            self.scale = Scale(self,
                               from_=1,
                               to=self.clades.get() - 1,
                               command=self.onScale,
                               orient=HORIZONTAL)
            self.scale.grid(sticky=W, row=3, column=2)

            self.labScale = Label(
                self, text="Number of clades in the first column: ")
            self.labScale.grid(sticky=W, row=2, column=2)

            self.ScaleVal = Label(self, textvariable=self.var)
            self.ScaleVal.grid(sticky=E, row=2, column=2)

        else:
            self.scale.grid_remove()
            self.labScale.grid_remove()
            self.ScaleVal.grid_remove()

    def onScale(self, val):
        v = int(float(val))
        self.var.set(v)
        # print(self.var.get())

    def onOK(self):
        dataframe = self.dataframe
        SSU = self.SSU.get()
        COX1 = self.COX1.get()
        EF1A = self.EF1A.get()
        EF1A_combinations = self.EF1A_variants.get()
        change = self.var.get()
        onecolumn = self.columns.get()

        # graphical parameters: distance between columns and lines of variants, total height etc.
        top = 200  # uppermost position
        xS = 1  # X position of SSU column on the graph
        xE = 2  # X position of EF1A column on the graph
        xC = 0  # X position of COX1 column on the graph
        cladeX = 3.3  # X position of clade names on the graph
        distance = 5  # distance between lines
        shift = 5  # distance between two columns

        vardict = {}
        ssu_set = set()
        ef1a_set = set()
        cox1_set = set()

        # Count the number of specimens for each clade that have a valid SSU and at least one other valid gene variant
        countdict = {}
        for specimen in dataframe.index.values:
            valid = 0
            if findall("[A-Za-z]", str(dataframe.loc[specimen, "SSU"])) == []:
                if EF1A and COX1:
                    if findall("[A-Za-z]", str(
                            dataframe.loc[specimen, "EF1A"])) == [] or findall(
                                "[A-Za-z]", str(dataframe.loc[specimen,
                                                              "COX1"])) == []:
                        valid = 1
                elif EF1A:
                    if findall("[A-Za-z]", str(dataframe.loc[specimen,
                                                             "EF1A"])) == []:
                        valid = 1
                elif COX1:
                    if findall("[A-Za-z]", str(dataframe.loc[specimen,
                                                             "COX1"])) == []:
                        valid = 1
            if dataframe.loc[specimen, "Clade"] not in countdict:
                countdict[dataframe.loc[specimen, "Clade"]] = valid
            else:
                countdict[dataframe.loc[specimen, "Clade"]] += valid

        # build a dict of connections for every SSU variant, regardless of clades
        for i in dataframe.index.values:
            if findall("[A-Za-z]", str(dataframe.loc[
                    i, "SSU"])) == []:  # choosing ony valid SSU variants
                if dataframe.loc[i, "SSU"] not in vardict:
                    vardict[dataframe.loc[i, "SSU"]] = {
                        "SSU_count": 1,
                        "EF1A": {},
                        "COX1": {}
                    }  # adding new SSU variant into dictionary
                    ssu_set.add(dataframe.loc[i, "SSU"])
                else:
                    vardict[dataframe.loc[i, "SSU"]][
                        "SSU_count"] += 1  # increasing SSU variant count
                if COX1:
                    if findall("[A-Za-z]", str(dataframe.loc[i, "COX1"])
                               ) == []:  # choosing ony valid COX1 variants
                        if dataframe.loc[i, "COX1"] not in vardict[
                                dataframe.loc[i, "SSU"]]["COX1"]:
                            vardict[dataframe.loc[i, "SSU"]]["COX1"][
                                dataframe.loc[
                                    i, "COX1"]] = 1  # adding new COX1 variant
                            cox1_set.add(dataframe.loc[i, "COX1"])
                        else:
                            vardict[dataframe.loc[i, "SSU"]]["COX1"][
                                dataframe.loc[
                                    i,
                                    "COX1"]] += 1  # increasing COX1 variant count
                if EF1A and EF1A_combinations:
                    if "homozygous" in str(dataframe.loc[i, "EF1A_combinations"]) \
                            or "both" in str(dataframe.loc[i, "EF1A_combinations"]) \
                            and findall("[A-Za-z]", str(dataframe.loc[
                                                            i, "EF1A"])) == []:  # choosing ony homozygous EF1A variants or unique unknown heterozygous
                        if dataframe.loc[i, "EF1A"] not in vardict[
                                dataframe.loc[i, "SSU"]]["EF1A"]:
                            vardict[dataframe.loc[i, "SSU"]]["EF1A"][
                                dataframe.loc[
                                    i, "EF1A"]] = 1  # adding new EF1A variant
                            ef1a_set.add(dataframe.loc[i, "EF1A"])
                        else:
                            vardict[dataframe.loc[i, "SSU"]]["EF1A"][
                                dataframe.loc[
                                    i,
                                    "EF1A"]] += 1  # increasing EF1A variant count

                    elif "+" in str(dataframe.loc[i, "EF1A_combinations"]
                                    ):  # choosing known heterozygous variants
                        for var in findall(
                                "[0-9]+",
                                str(dataframe.loc[i, "EF1A_combinations"])):
                            if var not in vardict[dataframe.loc[
                                    i, "SSU"]]["EF1A"]:
                                vardict[dataframe.loc[i, "SSU"]]["EF1A"][
                                    var] = 1  # adding new EF1A variant
                                ef1a_set.add(int(var))
                            else:
                                vardict[dataframe.loc[i, "SSU"]]["EF1A"][
                                    var] += 1  # increasing EF1A variant count
                elif EF1A and findall("[A-Za-z]", str(
                        dataframe.loc[i, "EF1A"])) == []:
                    if dataframe.loc[i, "EF1A"] not in vardict[dataframe.loc[
                            i, "SSU"]]["EF1A"]:
                        vardict[dataframe.loc[i, "SSU"]]["EF1A"][dataframe.loc[
                            i, "EF1A"]] = 1  # adding new EF1A variant
                        ef1a_set.add(dataframe.loc[i, "EF1A"])
                    else:
                        vardict[dataframe.loc[i, "SSU"]]["EF1A"][dataframe.loc[
                            i, "EF1A"]] += 1  # increasing EF1A variant count

        # print(vardict)

        # # modify dataframe by adding known heterozygous variants into EF1A column.

        new_dataframe = dataframe

        if EF1A_combinations:
            for i in range(len(new_dataframe["EF1A_combinations"])):
                if "+" in str(new_dataframe["EF1A_combinations"][i]):
                    if len(
                            findall("[0-9]+",
                                    str(new_dataframe["EF1A_combinations"]
                                        [i]))) == 1:
                        new_dataframe.loc[
                            new_dataframe.index.values[i], "EF1A"] = int(
                                findall(
                                    "[0-9]+",
                                    str(new_dataframe["EF1A_combinations"][i]))
                                [0])
                    elif len(
                            findall("[0-9]+",
                                    str(new_dataframe["EF1A_combinations"]
                                        [i]))) == 2:
                        new_dataframe.loc[
                            new_dataframe.index.values[i], "EF1A"] = int(
                                findall(
                                    "[0-9]+",
                                    str(new_dataframe["EF1A_combinations"][i]))
                                [0])
                        new_dataframe = new_dataframe.append(
                            new_dataframe.iloc[i], ignore_index=True)
                        new_dataframe.loc[
                            new_dataframe.index.values[-1], "EF1A"] = int(
                                findall(
                                    "[0-9]+",
                                    str(new_dataframe["EF1A_combinations"][i]))
                                [1])
                        new_dataframe.loc[new_dataframe.index.values[-1],
                                          "COX1"] = ""

        grouping_columns = ["Clade", "SSU"]
        if COX1:
            grouping_columns.append("COX1")
        if EF1A:
            grouping_columns.append("EF1A")

        grouped = new_dataframe.groupby(grouping_columns).aggregate(
            {"SSU": "count"})
        # print(grouped)

        # starting Y coordinates
        yS = top
        yE = top
        yC = top

        # dictionaries with pairs of coordinates for every variant of every gene
        ssu_coo = {}
        cox1_coo = {}
        ef1a_coo = {}
        clade_coo = {}

        # sets of clades and variants that were catalogued already to avoid duplicates
        clade_done = set()
        ssu_done = set()
        cox1_done = set()
        ef1a_done = set()

        # Gives XY coordinates to every genetic variant iterating through clades.
        # Variants are sorted acending; clades are sorted alphabetically
        counter = 0

        # adjusting distance between columns by adding the size of the longest clade name length
        shift_adj = 0.1 * max(
            [len(i) for i in grouped.index.get_level_values("Clade")]) + 0.3
        shift += shift_adj

        for clade in grouped.index.get_level_values("Clade"):
            if clade not in clade_done:
                if not onecolumn and counter == change:  # if a specified change value is reached, starts the second column with a specified shift
                    xS += shift
                    yS = top
                    if COX1:
                        xC += shift
                        yC = top
                    if EF1A:
                        xE += shift
                        yE = top
                    cladeX += shift

                counter += 1

                yS -= distance
                if COX1:
                    yC -= distance
                if EF1A:
                    yE -= distance

                # add coordinates of the clade name and vertical line at the side
                ssuvalid = set([
                    i
                    for i in grouped.loc[(clade)].index.get_level_values("SSU")
                    if findall("[A-Za-z]", str(i)) == [] and str(i) != ""
                ])
                if COX1:
                    cox1valid = set([
                        i for i in grouped.loc[(
                            clade)].index.get_level_values("COX1")
                        if findall("[A-Za-z]", str(i)) == [] and str(i) != ""
                    ])

                if EF1A:
                    ef1avalid = set([
                        i for i in grouped.loc[(
                            clade)].index.get_level_values("EF1A")
                        if findall("[A-Za-z]", str(i)) == [] and str(i) != ""
                    ])

                genelenlist = [len(ssuvalid)]
                if COX1:
                    genelenlist.append(len(cox1valid))
                if EF1A:
                    genelenlist.append(len(ef1avalid))

                cladeY = yS - (max(genelenlist) - 1) * distance * 0.5
                linestart = yS + 0.5 * distance
                lineend = yS - (max(genelenlist) -
                                1) * distance - 0.5 * distance
                clade_coo[clade] = [
                    cladeX, cladeY, cladeX - 0.2, linestart, lineend,
                    countdict[clade]
                ]

                # within-clade vertical position adjustments
                if COX1 and not EF1A:
                    if len(ssuvalid) - len(cox1valid) >= 2:
                        yC -= distance * (len(ssuvalid) - len(cox1valid)) // 2
                    elif len(cox1valid) - len(ssuvalid) >= 2:
                        yS -= distance * (len(cox1valid) - len(ssuvalid)) // 2

                elif EF1A and COX1:
                    if len(ssuvalid) - len(cox1valid) >= 2:
                        yC -= distance * (len(ssuvalid) - len(cox1valid)) // 2
                        if len(ssuvalid) - len(ef1avalid) >= 2:
                            yE -= distance * (len(ssuvalid) -
                                              len(ef1avalid)) // 2
                        elif len(ef1avalid) - len(ssuvalid) >= 2:
                            yS -= distance * (len(ef1avalid) -
                                              len(ssuvalid)) // 2
                            yC -= distance * (len(ef1avalid) -
                                              len(ssuvalid)) // 2

                    elif len(cox1valid) - len(ssuvalid) >= 2:
                        yS -= distance * (len(cox1valid) - len(ssuvalid)) // 2
                        if len(cox1valid) - len(ef1avalid) >= 2:
                            yE -= distance * (len(cox1valid) -
                                              len(ef1avalid)) // 2
                        elif len(ef1avalid) - len(cox1valid) >= 2:
                            yC -= distance * (len(ef1avalid) -
                                              len(cox1valid)) // 2
                            yS -= distance * (len(ef1avalid) -
                                              len(cox1valid)) // 2

                    elif len(ef1avalid) - len(ssuvalid) >= 2:
                        yS -= distance * (len(ef1avalid) - len(ssuvalid)) // 2
                        yC -= distance * (len(ef1avalid) - len(cox1valid)) // 2

                    elif len(ssuvalid) - len(ef1avalid) >= 2:
                        yE -= distance * (len(ssuvalid) - len(ef1avalid)) // 2

                elif EF1A:
                    if len(ssuvalid) - len(ef1avalid) >= 2:
                        yE -= distance * (len(ssuvalid) - len(ef1avalid)) // 2
                    elif len(ef1avalid) - len(ssuvalid) >= 2:
                        yS -= distance * (len(ef1avalid) - len(ssuvalid)) // 2

                # finally, assign coordinates
                for ssu in grouped.loc[(clade)].index.get_level_values("SSU"):
                    if findall("[A-Za-z]", str(ssu)) == [] and str(
                            ssu
                    ) != "":  # choose only valid genetic variants (no text, only numbers)
                        if ssu not in ssu_done:
                            ssu_coo[ssu] = [xS, yS]
                            yS -= distance

                        ssu_done.add(ssu)
                if COX1:
                    for cox1 in grouped.loc[(
                            clade)].index.get_level_values("COX1"):
                        if findall("[A-Za-z]", str(cox1)) == [] and str(
                                cox1
                        ) != "":  # choose only valid genetic variants (no text, only numbers)
                            if cox1 not in cox1_done:
                                cox1_coo[cox1] = [xC, yC]
                                yC -= distance
                            cox1_done.add(cox1)
                if EF1A:
                    for ef1a in grouped.loc[(
                            clade)].index.get_level_values("EF1A"):
                        if findall("[A-Za-z]", str(ef1a)) == [] and str(
                                ef1a
                        ) != "":  # choose only valid genetic variants (no text, only numbers)
                            if ef1a not in ef1a_done:
                                ef1a_coo[ef1a] = [xE, yE]
                                yE -= distance
                            ef1a_done.add(ef1a)

            clade_done.add(clade)

            geneXlist = [xS]
            geneYlist = [yS]
            if COX1:
                geneXlist.append(xC)
                geneYlist.append(yC)
            if EF1A:
                geneXlist.append(xE)
                geneYlist.append(yE)

            lowest = min(geneYlist)

            yS = lowest
            yC = lowest
            yE = lowest

        # print(grouped)

        # Building a plot

        def choose_line(size):  # a rule for choosing line width for the plot
            size = int(size)
            if size in (1, 2):
                width = 1
            elif size == 3:
                width = 1.5
            elif size < 6:
                width = 2
            elif size < 11:
                width = 2.5
            else:
                width = 3
            return width

        # remove axes
        ax1 = axes(frameon=False)
        ax1.set_frame_on(False)
        ax1.get_xaxis().set_visible(False)
        ax1.get_yaxis().set_visible(False)

        # build the lines between genetic variants
        for ssu in vardict:
            if EF1A:
                for ef1a in vardict[ssu]["EF1A"]:
                    if findall("[A-Za-z]", str(ef1a)) == []:
                        size = vardict[ssu]["EF1A"][ef1a]
                        plot([
                            ef1a_coo[int(ef1a)][0] + 0.4, ssu_coo[ssu][0] + 0.5
                        ], [ef1a_coo[int(ef1a)][1], ssu_coo[ssu][1]],
                             linestyle="dashed" if size == 1 else "solid",
                             linewidth=choose_line(size),
                             color="black")
                        text(ef1a_coo[int(ef1a)][0] + 0.7,
                             ef1a_coo[int(ef1a)][1],
                             ef1a,
                             ha="center",
                             va="center")
            if COX1:
                for cox1 in vardict[ssu]["COX1"]:
                    if findall("[A-Za-z]", str(cox1)) == []:
                        size = vardict[ssu]["COX1"][cox1]
                        plot([cox1_coo[cox1][0], ssu_coo[ssu][0]],
                             [cox1_coo[cox1][1], ssu_coo[ssu][1]],
                             linestyle="dashed" if size == 1 else "solid",
                             linewidth=choose_line(vardict[ssu]["COX1"][cox1]),
                             color="black")
                        text(cox1_coo[cox1][0] - 0.3,
                             cox1_coo[cox1][1],
                             cox1,
                             ha="center",
                             va="center")
            text(ssu_coo[ssu][0] + 0.25,
                 ssu_coo[ssu][1],
                 ssu,
                 ha="center",
                 va="center")

        # add gene names above the variants for the second column

        if not onecolumn:
            text(xS - shift + 0.25, top + distance + 0.2, "SSU", ha="center")
            text(xS + 0.25, top + distance + 0.2, "SSU", ha="center")
            if EF1A:
                text(xE - shift + 0.7,
                     top + distance + 0.2,
                     "EF1A",
                     ha="center")
                text(xE + 0.7, top + distance + 0.2, "EF1A", ha="center")
            if COX1:
                text(xC - shift - 0.3,
                     top + distance + 0.2,
                     "COI",
                     ha="center")
                text(xC - 0.3, top + distance + 0.2, "COI", ha="center")
        else:
            text(xS + 0.25, top + distance + 0.2, "SSU", ha="center")
            if EF1A:
                text(xE + 0.7, top + distance + 0.2, "EF1A", ha="center")
            if COX1:
                text(xC - 0.3, top + distance + 0.2, "COI", ha="center")

        # add clade names and vertical lines to the right of the column
        for clade in clade_coo:
            if EF1A:
                text(clade_coo[clade][0],
                     clade_coo[clade][1],
                     "%s (%d)" % (clade, clade_coo[clade][5]),
                     ha="left",
                     va="center")

                plot([clade_coo[clade][2], clade_coo[clade][2]],
                     [clade_coo[clade][3], clade_coo[clade][4]],
                     linewidth=2,
                     color="black")
            else:
                text(clade_coo[clade][0] - shift * 0.5 + shift_adj + 0.65,
                     clade_coo[clade][1],
                     "%s (%d)" % (clade, clade_coo[clade][5]),
                     ha="left",
                     va="center")

                plot([
                    clade_coo[clade][2] - shift * 0.5 + shift_adj + 0.7,
                    clade_coo[clade][2] - shift * 0.5 + shift_adj + 0.7
                ], [clade_coo[clade][3], clade_coo[clade][4]],
                     linewidth=2,
                     color="black")

        # set limits for X axis to avoid overlapping with legend
        if not onecolumn and EF1A:
            xlim(0, 14)
        elif not onecolumn:
            xlim(0, 12)
        elif onecolumn and EF1A:
            xlim(0, 7)
        elif onecolumn:
            xlim(0, 5)

        # produce lines for a legend
        leg_lines = [
            Line2D([0], [0], color="black", linestyle="dashed", linewidth=1),
            Line2D([0], [0], color="black", linewidth=1),
            Line2D([0], [0], color="black", linewidth=1.5),
            Line2D([0], [0], color="black", linewidth=2),
            Line2D([0], [0], color="black", linewidth=2.5),
            Line2D([0], [0], color="black", linewidth=3)
        ]

        # plot legend
        legend(leg_lines, ["1", "2", "3", "4-5", "6-10", "11-20"],
               loc="upper right")

        # show the plot
        show()
Example #35
0
    def initUI(self):
        self.parent.title("PRIMEP")
        self.pack(fill=BOTH, expand=True)
        global value
        value = 0
        global var
        var = IntVar()
        global num
        num = StringVar()
        global res
        res = StringVar()

        frame1 = Frame(self, style='My.TFrame')
        frame1.pack(fill=X)

        lbl1 = Label(frame1,
                     text="Enter a number :",
                     width=16,
                     background='orange')
        lbl1.pack(side=LEFT, padx=5, pady=5)

        entry1 = Entry(frame1, textvariable=num, style='My.TEntry')
        entry1.pack(fill=X, padx=5, expand=True)

        frame2 = Frame(self, style='My.TFrame')
        frame2.pack(fill=X)

        lbl2 = Label(frame2,
                     text="Set certainty :",
                     width=16,
                     background='orange')
        lbl2.pack(side=LEFT, padx=5, pady=5)

        #entry2 = Entry(frame2,textvariable=cer,style='My.TEntry')
        #entry2.pack(fill=X, padx=5, expand=True)

        scale = Scale(frame2,
                      from_=1,
                      to=25,
                      orient=HORIZONTAL,
                      command=self.onScale)
        scale.pack(side=LEFT, padx=5)

        #var = IntVar()
        label = Label(frame2, text=1, textvariable=var)
        label.pack(side=LEFT, padx=5)

        frame3 = Frame(self, style='My.TFrame')
        frame3.pack(fill=X)

        result = Label(frame3, textvariable=res, width=28, background='orange')
        result.pack(side=LEFT, padx=60, pady=5)

        frame4 = Frame(self, style='My.TFrame')
        frame4.pack(fill=X)

        btntest = Button(frame4,
                         text="Test",
                         width=10,
                         command=self.test,
                         style='My.TButton')
        btntest.pack(side=LEFT, anchor=N, padx=5, pady=5)

        btnclear = Button(frame4,
                          text="Clear",
                          width=10,
                          command=self.clear,
                          style='My.TButton')
        btnclear.pack(side=LEFT, anchor=N, padx=5, pady=5)

        btnclose = Button(frame4,
                          text="Close",
                          width=10,
                          command=self.quit,
                          style='My.TButton')
        btnclose.pack(side=LEFT, anchor=N, padx=5, pady=5)
Example #36
0
class SliderFrequency(Frame):
    """
        A slider with label wich indicate the gain in dB and Frequency in Hz

        parameters:
            root: Canvas
                the canvas to place the slider
            freq: float
                the frequency in Hz
            val: float
                initial value of the slider
            Min: float
                the min value of the slider
            Max: float
                the maximum of value of the slider
            sId: int
                the ID of the slider
    """
    def __init__(self,root, freq, val, Min=0.0, Max=1.0, sId=0):
        Frame.__init__(self,root)

        self.root = root

        self.id = sId
        self.freq = freq
        self.min = Min
        self.max = Max
        self.gain = StringVar()
        self.gain.set(self._Gain(val))
        self.value = StringVar()
        self.value.set( str(val)+" dB")

        self.initialize()
        self.gain.set(self._Gain(val))

    def initialize(self):
        """ Initialize the slider and the label"""
        self.slider = Scale(self.root, orient=VERTICAL, from_=self.min, to=self.max, value=float(self.gain.get()), command=self._updateValue)
        self.slider.grid(row=0,column=self.id, padx=14)

        self.valueLbl = Label(self.root, anchor="w", textvariable=self.value)
        self.valueLbl.grid(row=1,column=self.id, padx=14)

        self.freqLbl = Label(self.root,text=str(self.freq)+" Hz")
        self.freqLbl.grid(row=2,column=self.id, padx=14)

    def _updateValue(self,event):
        """ update the gain value and label when the slider is changing """
        self.gain.set(self.slider.get())
        self.value.set(str(self._Gain(self.gain.get()))+" dB")
        self.valueLbl.update()

    def _Gain(self, value):
        """ Transform the value of the slider to correct gain value  """
        v = (((self.max-self.min))-float(value))
        v = int(v*10)/10.0
        return v

    def getGain(self):
        """ Return the gain """
        return float(self._Gain(self.gain.get()))

    def getFrequency(self):
        """ Return the frequency """
        return self.freq