class TimeBase(Frame): """ Base de temps scale_time : controle de la base de temps """ def __init__(self, parent=None): """ Initialisation parent : oscilloscope """ Frame.__init__(self) self.configure(bd=1, relief="sunken") self.parent = parent self.scale_time = Scale(self, length=100, orient="horizontal", label="Temps", showvalue=1, from_=1, to=10, tickinterval=1, command=self.update) self.scale_time.pack(expand="yes", fill="both") def get_time(self): """ recuperer la valeur courante de la base de temps """ return self.scale_time.get() def update(self, event): """mise a jour de la base de temps""" if not isinstance(self.parent, Tk): self.parent.update_time(self.scale_time.get())
def FDL(k, fName): """Infitie loop function which constantly runs the display given the file name of the sequences and an initial k""" global kInput #Gets the initial de Bruijn Graph fdlNodes, minSeqLen = getFDLNodes(k, fName) #Sets up kInput to the appriate scale (3 to the shortest length - 1 ) to ensure # all sequence reads are always included if not kInput: minSeqLen -= 1 kInput = Scale(root, from_=3, to=minSeqLen, orient=HORIZONTAL, label="K", relief=FLAT) kInput.set(k) #sets the initial k value kInput.pack(side=LEFT, padx=50, pady=10) #generates all lines from the initial graph lines = addLines(fdlNodes) #starts inifinite recursive loop for redraw function move_nodes(fdlNodes, kInput.get(), kInput.get(), lines, root, fName) #starts display root.mainloop()
class TimeBase(Frame): def __init__(self, parent=None): """ Description : Creation d'un controleur pour la base de temps Proprietes : - un parent (classe Oscilloscope) - controleur de la base de temps (classe Scale) Methodes : - update_time_base(self, event) : callback de demande de mise a jour sur l'oscilloscope - get_time(self) : observateur sur la valeur de la base de temps """ Frame.__init__(self) self.configure(bd=1, relief="sunken") self.parent = parent self.scale_T = Scale(self, length=300, orient="horizontal", label="Temps", showvalue=1, from_=1, to=10, tickinterval=1, command=self.update_time_base) self.scale_T.pack(expand="yes", fill="both") def update_time_base(self, event): """ Mise a jour de la base de temps """ print("TimeBase.update_time_base()") print("Base de temps : ", self.scale_T.get()) if not isinstance(self.parent, Tk): self.parent.update_time(self.scale_T.get()) def get_time(self): """ Retour : valeur courante de la base de temps """ return self.scale_T.get()
class TimeBase(Frame): """controleur pour la base de temps scale : controle de la valeur de la base de temps """ def __init__(self, parent=None): """ initialisation parent : oscilloscope """ Frame.__init__(self) self.configure(bd=1, relief="sunken") self.parent = parent self.scale = Scale(self, length=300, orient="horizontal", label="Temps", showvalue=1, from_=1, to=10, tickinterval=1, command=self.update_time_base) self.scale.pack(expand="yes", fill="both") def get_time(self): """valeur courante de la base de temps""" return self.scale.get() def update_time_base(self, event): """mise a jour de la base de temps""" print("TimeBase.update_time_base()") print("Base de temps : ", self.scale.get()) if not isinstance(self.parent, Tk): self.parent.update_time(self.scale.get())
def initUI(self): self.parent.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.onScale) scale.pack(side=LEFT, padx=15) self.var = IntVar() self.label = Label(self, text=0, textvariable=self.var) self.label.pack(side=LEFT)
class TimeBase(Frame): """ Base de temps scale_time : controle de la base de temps """ def __init__(self, parent=None): """ Initialisation parent : oscilloscope """ Frame.__init__(self) self.configure(bd=1, relief="sunken") self.parent = parent self.scale_time = Scale(self, length=100, orient="horizontal", label="Temps", showvalue=1, from_=1, to=10, tickinterval=1, command=self.update) self.scale_time.pack(expand="yes", fill="both") # choix d'afficher lissajoux ou pas self.check = Checkbutton(self, text="Afficher lissajou", selectcolor=self.parent.lissajoux.color_XY, command=self.parent.plot_all, variable=self.parent.drawXY, onvalue=1, offvalue=0) self.check.pack(side="top", expand="yes", fill="x") self.check.select() def get_time(self): """ recuperer la valeur courante de la base de temps """ return self.scale_time.get() def update(self, event): """mise a jour de la base de temps""" print("TimeBase.update_time_base()") print("Base de temps : ", self.scale_time.get()) if not isinstance(self.parent, Tk): self.parent.update_time(self.scale_time.get())
class Playbar(Frame): def __init__(self, parent=None): Frame.__init__(self, parent) self.pack(side=BOTTOM, anchor=S, fill=X) self.scale = Scale(self, from_=0, to=1, sliderlength = 10, showvalue=YES, tickinterval=10, orient='horizontal') self.scale.pack(fill=X) # We don't set the initial value of the scale here because # that's done by tying it to the global variable "slidert" # Resetscale: takes a frame count and resets scale parms appropriately def resetscale(self, frames): temp = floor(log10(frames)) tickinterval = int(pow(10,temp)) if(tickinterval<1): tickinterval = 1 self.scale.config(to=frames, tickinterval=tickinterval)
def create_scale(self, region): """ Create scale for this parameter""" if self._is_int: resolution = 1 else: resolution = 0.001 frame = Frame(region) label = Label(frame, text=self._label) label.pack() scale = Scale(frame, from_=self._top, to=self._bottom, command=self.update_value, resolution=resolution) scale.set(self._value) scale.pack() frame.pack(side=LEFT)
class Controller(Observer): def __init__(self, parent, subject): print("Controller : __init__") self.subject = subject self.amp = IntVar() self.scale_amp = Scale(parent, variable=self.amp, label="Amplitude", orient="horizontal", length=250, from_=0, to=5, relief="sunken", sliderlength=20, tickinterval=1, command=self.update_amplitude) self.freq = IntVar() self.scale_freq = Scale(parent, variable=self.freq, label="Frequence", orient="horizontal", length=250, from_=0, to=5, relief="sunken", sliderlength=20, tickinterval=1, command=self.update_frequence) def update(self, subject): pass def update_amplitude(self, event): print("Controller : update_amplitude", self.amp.get()) self.subject.set_magnitude(self.amp.get()) def update_frequence(self, event): print("Controller : update_frequence", self.freq.get()) self.subject.set_frequency(self.freq.get()) def packing(self): self.scale_amp.pack(expand=1, fill="x", padx=6) self.scale_freq.pack(expand=1, fill="x", padx=6)
def FDL(k,fName): """Infitie loop function which constantly runs the display given the file name of the sequences and an initial k""" global kInput #Gets the initial de Bruijn Graph fdlNodes,minSeqLen = getFDLNodes(k,fName) #Sets up kInput to the appriate scale (3 to the shortest length - 1 ) to ensure # all sequence reads are always included if not kInput: minSeqLen -= 1 kInput = Scale(root, from_=3, to=minSeqLen,orient=HORIZONTAL,label="K",relief = FLAT) kInput.set(k) #sets the initial k value kInput.pack(side=LEFT, padx=50, pady=10) #generates all lines from the initial graph lines = addLines(fdlNodes) #starts inifinite recursive loop for redraw function move_nodes(fdlNodes, kInput.get(), kInput.get(), lines, root,fName) #starts display root.mainloop()
class Screen(Observer): def __init__(self,parent,bg="white"): self.canvas=Canvas(parent,bg=bg) print("parent",parent.cget("width"),parent.cget("height")) self.magnitude=Scale(parent,length=250,orient="horizontal", label="Magnitude", sliderlength=20, showvalue=0,from_=0,to=5, tickinterval=25) def update(self,model): print("View update") signal=model.get_signal() self.plot_signal(signal) def get_magnitude(self): return self.magnitude def plot_signal(self,signal,color="red"): w,h=self.canvas.cget("width"),self.canvas.cget("height") width,height=int(w),int(h) # print(self.canvas.find_withtag("signal")) if self.canvas.find_withtag("signal") : self.canvas.delete("signal") if signal and len(signal) > 1: plot = [(x*width, height/2.0*(y+1)) for (x, y) in signal] signal_id = self.canvas.create_line(plot, fill=color, smooth=1, width=3,tags="signal") return def grid(self, steps): w,h=self.canvas.cget("width"),self.canvas.cget("height") width,height=int(w),int(h) self.canvas.create_line(10,height/2,width,height/2,arrow="last") self.canvas.create_line(10,height-5,10,5,arrow="last") step=(width-10)/steps*1. for t in range(1,steps+2): x =t*step self.canvas.create_line(x,height/2-4,x,height/2+4) def packing(self) : self.canvas.pack() self.magnitude.pack()
class Playbar(Frame): def __init__(self, parent=None): Frame.__init__(self, parent) self.pack(side=BOTTOM, anchor=S, fill=X) self.scale = Scale(self, from_=0, to=1, sliderlength=10, showvalue=YES, tickinterval=10, orient='horizontal') self.scale.pack(fill=X) # We don't set the initial value of the scale here because # that's done by tying it to the global variable "slidert" # Resetscale: takes a frame count and resets scale parms appropriately def resetscale(self, frames): temp = floor(log10(frames)) tickinterval = int(pow(10, temp)) if (tickinterval < 1): tickinterval = 1 self.scale.config(to=frames, tickinterval=tickinterval)
def __init__(self, master): super(GUI, self).__init__(master) row1, row2, row3, row4 = self.set_rows(4) desc = Label(row1, text="Unify Walk Lengths by mean-Binning the Time Series") desc.pack(fill=tk.X, ipadx=10, ipady=10, side=tk.TOP) dirbutton = Button(row1, text="Select Folder", command=self.define_dir) dirbutton.pack(side=tk.LEFT, expand=True) o = Label(row1, text="or") o.pack(side=tk.LEFT, padx=20, expand=True) filebutton = Button(row1, text="Select Specific File", command=self.define_file) filebutton.pack(side=tk.LEFT, expand=True) self.show_chosen = Label(row2, textvariable=self.chosen, background='white') self.show_chosen.pack(fill=tk.X, side=tk.LEFT, pady=10, ipady=5, ipadx=5, expand=True) nb = Label(row3, text="Number of Bins:", pady=10) nb.pack(side=tk.LEFT) scale = Scale(row3, from_=0, to=150, orient=tk.HORIZONTAL) scale.set(100) scale.pack(side=tk.LEFT, fill=tk.X, expand=True) self.scale = scale row4.pack(fill=tk.NONE) self.go_button = Button(row4, text="GO") self.go_button.pack(side=tk.LEFT, padx=10) self.close_button = Button(row4, text="Close", command=master.destroy) self.close_button.pack(side=tk.RIGHT, padx=10)
class Simulator(Tk): def __init__(self, network): Tk.__init__(self) self.title("DATK") self.network = network self.n_steps = network.count_snapshots() self.network.restore_snapshot(0) self.canvas = Canvas(self, width=800, height=500) self.canvas.draw(self.network) self.canvas.pack() self.slider = Scale(self, from_=0, to=self.n_steps-1, length=300, orient=HORIZONTAL, command=self.updateValue) self.slider.pack(padx=10, pady=10) def updateValue(self, val): self.network.restore_snapshot(int(float(val))) self.canvas.draw(self.network) def destroy(self): self.network.restore_snapshot(-1) Tk.destroy(self)
class TimeBase(Frame): """ Base de temps scale_time : controle de la base de temps """ def __init__(self, parent=None): """ Initialisation parent : oscilloscope """ Frame.__init__(self) self.configure(bd=1, relief="sunken") self.parent = parent self.scale_time = Scale(self, length=100, orient="horizontal", label="Temps", showvalue=1, from_=1, to=10, tickinterval=1, command=self.update) self.scale_time.pack(expand="yes", fill="both") # choix d'afficher lissajoux ou pas self.check = Checkbutton(self,text="Afficher lissajou", selectcolor=self.parent.lissajoux.color_XY, command=self.parent.plot_all, variable=self.parent.drawXY, onvalue = 1, offvalue = 0) self.check.pack(side="top",expand="yes", fill="x") self.check.select() def get_time(self): """ recuperer la valeur courante de la base de temps """ return self.scale_time.get() def update(self, event): """mise a jour de la base de temps""" print("TimeBase.update_time_base()") print("Base de temps : ", self.scale_time.get()) if not isinstance(self.parent, Tk): self.parent.update_time(self.scale_time.get())
def addPage(self, name): page = ttk.Frame(self.panelControl) self.panelControl.add(page, text='signal ' + name) visible_checkbox = Checkbutton(page, text="Afficher") magnitude = Scale(page, length=250, orient="horizontal", label="Amplitude", sliderlength=20, showvalue=0, from_=0, to=5, tickinterval=1, name="magnitudeScale") frequency = Scale(page, length=250, orient="horizontal", label="Frequency", sliderlength=20, showvalue=0, from_=0, to=25, tickinterval=5, name="frequencyScale") phase = Scale(page, length=250, orient="horizontal", label="Phase", sliderlength=20, showvalue=0, from_=0, to=20, tickinterval=5, name="phaseScale") visible_checkbox.pack(fill="x", pady=6) magnitude.pack(expand=1, fill="both", pady=6) frequency.pack(expand=1, fill="both", pady=6) phase.pack(expand=1, fill="both", pady=6) self.panel_control_page.append({ 'visible': visible_checkbox, 'magnitude': magnitude, 'frequency': frequency, 'phase': phase })
return quotes # column vector def getVariances(self, profits): variances = numpy.zeros(shape=(len(self.companies),1)) for i,company in enumerate(self.companies): variances[i,:] = self.companies[company].getVariance() return variances if __name__ == "__main__": root = Tk.Tk() portfolioManager = PortfolioManager() scale = Scale(root, from_=0.0, to=1.0, resolution=.01, orient=Tk.HORIZONTAL) scale.pack(side=Tk.BOTTOM, expand=1, fill=Tk.BOTH) ''' companies = { "EXAS", "BBRY", "CYTK", "ISIS", "NPSP"}#, "AAPL", "PG", "COKE" } portfolioManager.addPortfolio(companies) ''' companies = { "AMZN", "GE", "AAPL", "PG", "COKE" } portfolioManager.addPortfolio(companies) companies = { "GOOG", "MSFT", "IRBT", "IBM", "WMT" } portfolioManager.addPortfolio(companies) companies = { "T", "F", "EBAY", "YHOO", "JPM"}
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from Tkinter import Tk, Label, Button, Scale, X, Y, HORIZONTAL def resize(ev): test.config(font=('Consolas', ev)) top = Tk() top.geometry('500x500') Label(top, text='Directory list view').pack() test = Label(top, text='test', fg='grey', font=('Consolas', 12)) test.pack() scale = Scale(from_=10, to=40, orient=HORIZONTAL, command=resize) scale.set(12) scale.pack(fill=X) Button(top, text='QUIT', bg='red', fg='blue', command=top.quit).pack(fill=X) top.mainloop()
class Example(Frame): ####################################################################### def __init__(self, parent): Frame.__init__(self, width=1000, height=1000, background="green") self.parent = parent self.pack(fill=BOTH, expand=True) self.initUI() def initUI(self): self.parent.title("Cravis_ver1") self.pack(fill=BOTH, expand=1) frame = Frame(self, width=1500, height=200, relief=RAISED, borderwidth=1) frame.pack(expand=False) #frame.config(bg="blue") self.pack(expand=False) ##### ##### frame2 = Frame(self, width=1500, height=300, relief=RAISED, borderwidth=1) frame2.pack(expand=False) self.pack(expand=False) self.var0 = BooleanVar() self.var1 = BooleanVar() self.var2 = BooleanVar() self.var3 = BooleanVar() self.var4 = BooleanVar() self.var5 = BooleanVar() self.content = IntVar() reset_Area_Button = Button(self, width=10, text="reset_Area", command=self.reset_Area) reset_Area_Button.place(x=610, y=400) set_Area_Button = Button(self, width=10, text="set_Area", command=self.set_Area) set_Area_Button.place(x=610, y=430) show_Area_Button = Button(self, width=10, text="show_Area", command=self.show_Area) show_Area_Button.place(x=610, y=460) quitButton = Button(self, text="Quit", command=self.off_video) quitButton.place(x=50, y=20) startButton = Button(self, text="Video", command=self.on_start) startButton.place(x=100, y=20) TakePicButton = Button(self, text="TakePic", command=self.Takepic) TakePicButton.place(x=150, y=20) LoadDataButton = Button(self, text="Load_Data", bg="green", command=self.confirm_LoadData) LoadDataButton.place(x=550, y=90) SaveDataButton = Button(self, text="Save_Data", bg="green", command=self.confirm_SaveData) SaveDataButton.place(x=550, y=120) ###### cb1 = Checkbutton(self, text="Binary", variable=self.var1, command=self.on_Binary) cb1.place(x=80, y=50) cb2 = Checkbutton(self, text="Partical", variable=self.var2, command=self.on_Partical) cb2.place(x=80, y=80) cb3 = Checkbutton(self, text="Sobel", variable=self.var3, command=self.on_Sobel) cb3.place(x=80, y=110) cb4 = Checkbutton(self, text="Median", variable=self.var4, command=self.on_Median) cb4.place(x=80, y=140) cb5 = Checkbutton(self, text="Level_Adjust", variable=self.var5, command=self.on_LevelAdjust) cb5.place(x=80, y=170) cb5 = Checkbutton(self, text="SaveImage", variable=self.var0) cb5.place(x=550, y=20) ##### ################################### AdjustBinaryButton = Button(self, text="Adjust_Binary", command=self.AdjustBinary) AdjustBinaryButton.place(x=340, y=50) AdjustExtractButton = Button(self, text="Adjust_Extract", command=self.AdjustExtract) AdjustExtractButton.place(x=340, y=80) AdjustBinaryButton = Button(self, text="Adjust_3", command=self.AdjustBinary) AdjustBinaryButton.place(x=340, y=110) AdjustExtractButton = Button(self, text="Adjust_4", command=self.AdjustExtract) AdjustExtractButton.place(x=340, y=140) AdjustExtractButton = Button(self, text="Adjust_5", command=self.AdjustExtract) AdjustExtractButton.place(x=340, y=170) ######## self.infor_Alg1 = Text(self, width=40, height=1) #self.infor_Alg1.pack(side=LEFT) self.infor_Alg1.place(x=130, y=250) #thongtin_Alg1="Binary : " #self.infor_Alg1.insert(END,thongtin_Alg1) self.label_Alg1 = Label(self, text="Binary: ") self.label_Alg1.place(x=50, y=250) ## self.infor_Alg2 = Text(self, width=40, height=1) #self.infor_Alg2.pack(side=LEFT) self.infor_Alg2.place(x=130, y=270) #thongtin_Alg2="Extract : " #self.infor_Alg2.insert(END,thongtin_Alg2) self.label_Alg2 = Label(self, text="Extract: ") self.label_Alg2.place(x=50, y=270) ## self.infor_Alg3 = Text(self, width=40, height=1) #self.infor_Alg3.pack() self.infor_Alg3.place(x=130, y=290) #thongtin_Alg3="Alg_3 : " #self.infor_Alg3.insert(END,thongtin_Alg3) self.label_Alg3 = Label(self, text="Alg3: ") self.label_Alg3.place(x=50, y=290) ## self.infor_Alg4 = Text(self, width=40, height=1) #self.infor_Alg4.pack(side=LEFT) self.infor_Alg4.place(x=130, y=310) #thongtin_Alg4="Alg_4 : " #self.infor_Alg4.insert(END,thongtin_Alg4) self.label_Alg4 = Label(self, text="Alg4: ") self.label_Alg4.place(x=50, y=310) ## self.infor_Alg5 = Text(self, width=40, height=1) #self.infor_Alg5.pack() self.infor_Alg5.place(x=130, y=330) #thongtin_Alg5="Alg_5 : " #self.infor_Alg5.insert(END,thongtin_Alg5) self.label_Alg5 = Label(self, text="Alg5: ") self.label_Alg5.place(x=50, y=330) ## self.infor_Area1 = Text(self, width=20, height=1) self.infor_Area1.place(x=100, y=400) #thongtin_Area1="Area1:" #self.infor_Area1.insert(END,thongtin_Area1) self.label_Area1 = Label(self, text="Area1: ") self.label_Area1.place(x=50, y=400) ## self.infor_Area2 = Text(self, width=20, height=1) self.infor_Area2.place(x=350, y=400) #thongtin_Area2="Area2:" #self.infor_Area2.insert(END,thongtin_Area2) self.label_Area2 = Label(self, text="Area2: ") self.label_Area2.place(x=300, y=400) ## self.infor_Area3 = Text(self, width=20, height=1) self.infor_Area3.place(x=100, y=450) #thongtin_Area3="Area3:" #self.infor_Area3.insert(END,thongtin_Area3) self.label_Area3 = Label(self, text="Area3: ") self.label_Area3.place(x=50, y=450) ## self.infor_Area4 = Text(self, width=20, height=1) self.infor_Area4.place(x=350, y=450) #thongtin_Area4="Area4:" #self.infor_Area4.insert(END,thongtin_Area4) self.label_Area4 = Label(self, text="Area4: ") self.label_Area4.place(x=300, y=450) ##### ################################ self.infor = Text(self, width=50, height=2) self.infor.pack() thongtin = "CHAO MUNG DEN VOI CHUONG TRINH CRAVIS_V1 \n DESIGN BY VISUAL GROUP" self.infor.insert(END, thongtin) ################################### menuBar = Menu(self.parent) self.parent.config(menu=menuBar) fileMenu1 = Menu(menuBar) fileMenu2 = Menu(menuBar) fileMenu3 = Menu(menuBar) fileMenu1.add_command(label="zoom", command=self.zoom) fileMenu1.add_command(label="password", command=self.zoom) fileMenu1.add_command(label="2", command=self.onExit) fileMenu1.add_command(label="3", command=self.onExit) fileMenu2.add_command(label="Exit", command=self.onExit) fileMenu2.add_command(label="1", command=self.onExit) fileMenu2.add_command(label="2", command=self.onExit) fileMenu2.add_command(label="3", command=self.onExit) fileMenu3.add_command(label="help", command=self.file_help) fileMenu3.add_command(label="1", command=self.onExit) fileMenu3.add_command(label="2", command=self.onExit) fileMenu3.add_command(label="3", command=self.onExit) menuBar.add_cascade(label="File", menu=fileMenu1) menuBar.add_cascade(label="Infor", menu=fileMenu2) menuBar.add_cascade(label="Help", menu=fileMenu3) ###### ####### ################################################ function for menu def onScale_H(self, val): v = int(float(val)) self.varHigh.set(v) print(v) #self.varHigh.set(v) def onScale_L(self, val): v = int(float(val)) self.varLow.set(v) print(v) ### def onScale_R_L(self, val): v = int(float(val)) self.varRed_L.set(v) print(v) def onScale_R_H(self, val): v = int(float(val)) self.varRed_H.set(v) print(v) def onScale_G_L(self, val): v = int(float(val)) self.varGreen_L.set(v) print(v) def onScale_G_H(self, val): v = int(float(val)) self.varGreen_H.set(v) print(v) def onScale_B_L(self, val): v = int(float(val)) self.varBlue_L.set(v) print(v) def onScale_B_H(self, val): v = int(float(val)) self.varBlue_H.set(v) print(v) ### def on_Select(self, val): sender = val.widget idx = sender.curselection() value = sender.get(idx) self.varSelect.set(value) def onExit(self): self.quit() def file_help(self): f = open('a.txt', 'w+') #line=f.readline() infor = "1111111111111\n 2222222222222222222\n333333333333333" f.write(infor) line = f.readline() for line in f: print(line) def zoom(self): root.geometry("1500x500") ###################################################### ############ Algorithm def on_Binary(self): if self.var1.get() == True: print("Binary") self.show_Binary() #show window else: print("No_Binary") if hasattr(self, 'ThExtract'): print "dsfsdfds" self.ThBinary.withdraw() else: print "dddddddd" #self.ThBinary.withdraw() def on_Partical(self): if self.var2.get() == True: print("Partical") self.show_Extract() else: print("No_Partical") self.ThExtract.withdraw() def on_Sobel(self): if self.var3.get() == True: print("Sobel") else: print("No_Sobel") def on_Median(self): if self.var4.get() == True: print("Median") else: print("No_Median") def on_LevelAdjust(self): if self.var5.get() == True: print("LevAd") else: print("No_LevAd") def showvideo(self): if camera.resolution == (400, 300): print("ok") cwgt.camera.start_preview() ############################################################################### button to analyse image def Takepic(self): ## take pic button src = Frame(cwgt, width=400, height=300, relief=RAISED, borderwidth=1) src = camera.capture('src.png') analysed = camera.capture('analysed.png') if self.var0.get() == 1: camera.capture("/home/pi/Desktop/New/{0:%Y%m%d-%H%M%S}.png".format( datetime.now())) #'{0:%Y%m%d-%H%M%S}: start.'.format(datetime.now()) #img_abc=PhotoImage(file="src.png") #h=img_abc.width() #w=img_abc.height() #print h,w #cv2.imwrite("src.png",src) #img_abc = cv2.imread("img.png",cv2.IMREAD_COLOR) #cv2.rectangle(img_abc,(50,50),(100,50),(255,0,0),15) #cv2.imwrite("out2.png",img_abc) img_origin = PhotoImage(file="src.png") cwgt2.img = img_origin cwgt2.create_image(200, 200, image=img_origin) h = img_origin.width() w = img_origin.height() #print h,w #px=img[55,55] #img_new=cv2.imread("out2.png") #pix=img_new[2,2] #pix0=img_new[2,2][0] #pix1=img_new[2,2][1] #pix2=img_new[2,2][2] #print pix,pix0,pix1,pix2 #for j in range (0,h): # for i in range (0,w): # if img_new[i,j] #img_new[i,i]=[255,255,255] #pix__=img_new[2,2][0] #print pix__ #cv2.imwrite("out3.png",img_new) #img_x=PhotoImage(file="out3.png") #cwgt2.img=img_x #cwgt2.create_image(200, 200, image=img_x) #if self.var1.get() == True: #src=cv2.imread("src.png") #res=cv2.Canny(src,self.varLow.get(), self.varHigh.get()) #retval,res = cv2.threshold(src, self.varLow.get(), self.varHigh.get(), cv2.THRESH_BINARY) #cv2.imwrite("analysed.png",res) if self.var2.get() == True: min_R = self.varRed_L.get() max_R = self.varRed_H.get() min_G = self.varGreen_L.get() max_G = self.varGreen_H.get() min_B = self.varBlue_L.get() max_B = self.varBlue_H.get() pro_2 = cv2.imread('analysed.png') #hsv = cv2.cvtColor(src,cv2.COLOR_BGR2HSV) lower = np.array([min_B, min_G, min_R], np.uint8) upper = np.array([max_B, max_G, max_R], np.uint8) mask = cv2.inRange(pro_2, lower, upper) analysed = cv2.bitwise_and(pro_2, pro_2, mask=mask) cv2.imwrite("analysed.png", analysed) #cv2.imshow('aaa',src) # #img2=PhotoImage(file="out.png") #cwgt.img2=img2 #cwgt.create_image(200, 200, image=img2) #cv2.imwrite("out3.png",img_new) img_show = PhotoImage(file="analysed.png") cwgt.img = img_show cwgt.create_image(200, 200, image=img_show) if self.var1.get() == True: src = cv2.imread("analysed.png") #analysed=cv2.Canny(src,self.varLow.get(), self.varHigh.get()) retval, res = cv2.threshold(src, self.varLow.get(), self.varHigh.get(), cv2.THRESH_BINARY) cv2.imwrite("analysed.png", res) if self.var5.get() == True: src = cv2.imread("analysed.png") number = 0 for j in range(self.x0_1, self.x1_1): for i in range(self.y0_1, self.y1_1): if src[i, j][0] > 0 and src[i, j][1] > 0 and src[i, j][2] > 0: src[i, j] = [255, 255, 255] number = number + 1 print number if number > 180: tkMessageBox.showinfo(title="OK", message="OK") else: tkMessageBox.showinfo(title="ng", message="ng") cv2.imwrite("analysed.png", src) img_show = PhotoImage(file="analysed.png") cwgt.img = img_show cwgt.create_image(200, 200, image=img_show) #img_show=PhotoImage(file="src.png") #cwgt.img=img_show #cwgt.create_image(200, 200, image=img_show) #retval, after_Binary = cv2.threshold(img, self.varLow.get(), self.varHigh.get(), cv2.THRESH_BINARY) #after_Blurr =cv2.blur(img,(5,5)) #after_MedianBlur=cv2.medianBlur(after_Blurr,5) #cv2.imwrite("out.png",res) #after_Binary=PhotoImage(file="out.png") #cwgt.img=res #cv2.imshow("show",res) #cwgt.create_image(0, 0, image=after_Binary) #cwgt.create_image(0, 0, image=mask) #after_Canny=cv2.Canny(after_MedianBlur,100,200) #findlabel=cv2.findContours(after_Blurr,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) #findlabel=cv2.findContours(after_Binary,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) #im = cv2.imread('new.png') #imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY) #ret,thresh = cv2.threshold(imgray,0,255,0) #image, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE) #img=cv2.drawContours(image,contours,-1,(0,255,0),1) #cv2.imwrite("out.png",after_Binary) #cv2.imwrite("blur.png",after_Blurr) #cv2.imwrite("median blur.png",after_MedianBlur) #cv2.imwrite("Canny.png",after_Canny) #after_Binary=PhotoImage(file="out.png") #cwgt.img=after_Binary #cwgt.create_image(0, 0, image=after_Binary) #else: #cwgt.create_image(0, 0, image=img_origin) #print("xsfd") #print img_origin[100,100][0] #www=img_origin.width() #print www # def on_start(self): print("xsfd") self.showvideo() def off_video(self): #cwgt.frame.destroy() camera.stop_preview() ######## ###################################################################################### show window def show_Binary(self): ## input Thresh_Binary if (hasattr(self, 'ThBinary')): #(self.varHigh.get()> self.varLow.get()) self.ThBinary.deiconify() else: self.ThBinary = Tk() self.ThBinary.geometry("350x100+350+350") self.ThBinary.title("Binary") self.scale_L = Scale(self.ThBinary, from_=255, to=0, command=self.onScale_L) self.scale_L.pack(side=LEFT, padx=10) self.varLow = IntVar() self.label1 = Label(self.ThBinary, text="LOW") self.label1.pack(side=LEFT, padx=0) self.scale_H = Scale(self.ThBinary, from_=255, to=0, command=self.onScale_H) self.scale_H.pack(side=LEFT, padx=20) self.varHigh = IntVar() self.label2 = Label(self.ThBinary, text="HIGH") self.label2.pack(side=LEFT, padx=1) binary = Button(self.ThBinary, text="OK", width=5, background="green", command=self.getdata_Binary) binary.pack(side=LEFT) #binary = Button(self.ThBinary, text="Get_Binary",background="green",command=self.getdata_Binary) #binary.pack() ######## def show_Extract(self): ## input Thresh_Extract if hasattr(self, 'ThExtract'): self.ThExtract.deiconify() else: self.ThExtract = Tk() self.ThExtract.geometry("750x100+350+350") self.ThExtract.title("Extract_Color") ### self.scale_R_L = Scale(self.ThExtract, from_=255, to=0, command=self.onScale_R_L) self.scale_R_L.pack(side=LEFT, padx=10) self.varRed_L = IntVar() self.label_R_L = Label(self.ThExtract, text="Red_L") self.label_R_L.pack(side=LEFT, padx=0) self.scale_R_H = Scale(self.ThExtract, from_=255, to=0, command=self.onScale_R_H) self.scale_R_H.pack(side=LEFT, padx=10) self.varRed_H = IntVar() self.label_R_H = Label(self.ThExtract, text="Red_H") self.label_R_H.pack(side=LEFT, padx=0) ### self.scale_G_L = Scale(self.ThExtract, from_=255, to=0, command=self.onScale_G_L) self.scale_G_L.pack(side=LEFT, padx=10) self.varGreen_L = IntVar() self.label_G_L = Label(self.ThExtract, text="Green_L") self.label_G_L.pack(side=LEFT, padx=0) self.scale_G_H = Scale(self.ThExtract, from_=255, to=0, command=self.onScale_G_H) self.scale_G_H.pack(side=LEFT, padx=10) self.varGreen_H = IntVar() self.label_G_H = Label(self.ThExtract, text="Green_H") self.label_G_H.pack(side=LEFT, padx=0) ### self.scale_B_L = Scale(self.ThExtract, from_=255, to=0, command=self.onScale_B_L) self.scale_B_L.pack(side=LEFT, padx=10) self.varBlue_L = IntVar() self.label_B_L = Label(self.ThExtract, text="Blue_L") self.label_B_L.pack(side=LEFT, padx=0) self.scale_B_H = Scale(self.ThExtract, from_=255, to=0, command=self.onScale_B_H) self.scale_B_H.pack(side=LEFT, padx=10) self.varBlue_H = IntVar() self.label_G_H = Label(self.ThExtract, text="Blue_H") self.label_G_H.pack(side=LEFT, padx=0) ### Extract = Button(self.ThExtract, text="OK", width=5, background="green", command=self.getdata_Extract) Extract.pack(side=LEFT) ########## def show_Partical(self): print("") #self.ThBinary=Tk() #self.ThBinary.geometry("200x70+350+350") #self.ThBinary.title("Binary") #self.scale_L = Scale(self.ThBinary, from_=0, to=255, command=self.onScale_L) #self.scale_L.pack(side=LEFT, padx=10) #self.varLow = IntVar() #self.label1 = Label(self.ThBinary,text="LOW") #self.label1.pack(side=LEFT,padx=0) #self.scale_H = Scale(self.ThBinary, from_=0, to=255, command=self.onScale_H) #self.scale_H.pack(side=LEFT, padx=20) #self.varHigh = IntVar() #self.label2 = Label(self.ThBinary, text="HIGH") #self.label2.pack(side=LEFT,padx=1) ######### def confirm_SaveData(self): ##input password self.master = Tk() self.master.title("pass") self.master.geometry("200x70+350+350") self.content = StringVar() self.entry = Entry(self.master, text="000", textvariable=self.content) self.entry.pack() b = Button(self.master, text="get", width=10, command=self.SaveData) b.pack() text123 = self.content.get() self.content.set(text123) print(self.content.get()) ############ def reset_Area(self): self.infor_Area1.delete('1.0', END) self.infor_Area2.delete('1.0', END) self.infor_Area3.delete('1.0', END) self.infor_Area4.delete('1.0', END) def set_Area(self): self.text1 = self.infor_Area1.get('1.0', END) self.x0_1 = int(self.text1[0] + self.text1[1] + self.text1[2]) self.y0_1 = int(self.text1[4] + self.text1[5] + self.text1[6]) self.x1_1 = int(self.text1[8] + self.text1[9] + self.text1[10]) self.y1_1 = int(self.text1[12] + self.text1[13] + self.text1[14]) ######### def show_Area(self): #text1=self.infor_Area1.get('1.0',END) #x0_1=int(text1[0]+text1[1]) #y0_1=int(text1[3]+text1[4]) #x1_1=int(text1[6]+text1[7]) #y1_1=int(text1[9]+text1[10]) #text2=self.infor_Area2.get('1.0',END) #x0_2=int(text2[0]+text2[1]) #y0_2=int(text2[3]+text2[4]) #x1_2=int(text2[6]+text2[7]) #y1_2=int(text2[9]+text2[10]) #text3=self.infor_Area3.get('1.0',END) #x0_3=int(text3[0]+text3[1]) #y0_3=int(text3[3]+text3[4]) #x1_3=int(text3[6]+text3[7]) #y1_3=int(text3[9]+text3[10]) #text4=self.infor_Area4.get('1.0',END) #x0_4=int(text4[0]+text4[1]) #y0_4=int(text4[3]+text4[4]) #x1_4=int(text4[6]+text4[7]) #y1_4=int(text4[9]+text4[10]) img = cv2.imread("src.png", cv2.IMREAD_COLOR) #print self.x0_1 cv2.rectangle(img, (self.x0_1, self.y0_1), (self.x1_1, self.y1_1), (255, 0, 0), 2) #cv2.rectangle(img,(x0_2,y0_2),(x1_2,y1_2),(0,255,0),2) #cv2.rectangle(img,(x0_3,y0_3),(x1_3,y1_3),(0,0,255),2) #cv2.rectangle(img,(x0_4,y0_4),(x1_4,y1_4),(255,255,0),2) img_show_Area = img #img_show_Area=cv2.rectangle(img,(x0_1,y0_1),(x1_1,y1_1),(255,0,0),2) cv2.imwrite("show_Area.png", img_show_Area) img_show = PhotoImage(file="show_Area.png") cwgt2.img = img_show cwgt2.create_image(200, 200, image=img_show) #cv2.rectangle(img,(50,250),(100,500),(255,0,0),15) def AdjustBinary(self): if self.var1.get() == True: self.ThBinary.withdraw() self.ThBinary.deiconify() def AdjustExtract(self): if self.var2.get() == True: self.ThExtract.withdraw() self.ThExtract.deiconify() ############################################################################################ get data def SaveData(self): ## get password button print(self.entry.get()) self.set_Area() if self.entry.get() == "1111": self.master.destroy() tkMessageBox.showinfo(title="Save", message="SaveData success !!") print "Save" self.inforData_binary = "Binary : (" + self.text_binary + ")" self.inforData_Extract = "Extract : " + self.text_Extract self.inforData_Area1 = "Area1 : " + self.text1 if self.var1.get() == 1: data1 = "1" else: data1 = "0" ## if self.var2.get() == 1: data2 = "1" else: data2 = "0" ## if self.var3.get() == 1: data3 = "1" else: data3 = "0" ## if self.var4.get() == 1: data4 = "1" else: data4 = "0" ## if self.var5.get() == 1: data5 = "1" else: data5 = "0" ## self.SumData = (data1 + data2 + data3 + data4 + data5) print self.SumData self.inforData = self.SumData + "\n" + self.inforData_binary + "\n" + self.inforData_Extract + "\n" + self.inforData_Area1 print self.inforData #if self.var1.get()==1 : f = open('a.txt', 'w+') f.write(self.inforData) else: tkMessageBox.showinfo(title="fail", message="again") #### def getdata_Binary(self): value_low = str(self.varLow.get()) value_high = str(self.varHigh.get()) if self.varLow.get() > 99: min_binary = str(value_low) else: if self.varLow.get() > 9: min_binary = str("0" + value_low) else: min_binary = str("00" + value_low) if self.varHigh.get() > 99: max_binary = str(value_high) else: if self.varHigh.get() > 9: max_binary = str("0" + value_high) else: max_binary = str("00" + value_high) self.text_binary = str(min_binary + "," + max_binary) #if hasattr(self,'infor'): # self.infor.destroy() #if hasattr(self,'infor_Alg1'): # self.infor_Alg1.destroy() if self.varHigh.get() > self.varLow.get(): self.infor_Alg1.delete('1.0', END) self.infor_Alg1.insert(END, self.text_binary) #self.ThBinary.destroy() self.ThBinary.withdraw() else: tkMessageBox.showinfo(title="fail", message="again") #### def getdata_Extract(self): value_R_L = str(self.varRed_L.get()) value_R_H = str(self.varRed_H.get()) value_G_L = str(self.varGreen_L.get()) value_G_H = str(self.varGreen_H.get()) value_B_L = str(self.varBlue_L.get()) value_B_H = str(self.varBlue_H.get()) ## if self.varRed_L.get() > 99: min_R = str(value_R_L) else: if self.varRed_L.get() > 9: min_R = str("0" + value_R_L) else: min_R = str("00" + value_R_L) ## if self.varRed_H.get() > 99: max_R = str(value_R_H) else: if self.varRed_H.get() > 9: max_R = str("0" + value_R_H) else: max_R = str("00" + value_R_H) ### if self.varGreen_L.get() > 99: min_G = str(value_G_L) else: if self.varGreen_L.get() > 9: min_G = str("0" + value_G_L) else: min_G = str("00" + value_G_L) ## if self.varGreen_H.get() > 99: max_G = str(value_G_H) else: if self.varGreen_H.get() > 9: max_G = str("0" + value_G_H) else: max_G = str("00" + value_G_H) ### if self.varBlue_L.get() > 99: min_B = str(value_B_L) else: if self.varBlue_L.get() > 9: min_B = str("0" + value_B_L) else: min_B = str("00" + value_B_L) ## if self.varBlue_H.get() > 99: max_B = str(value_B_H) else: if self.varBlue_H.get() > 9: max_B = str("0" + value_B_H) else: max_B = str("00" + value_B_H) ### self.text_Extract = str("R(" + min_R + "," + max_R + ")" + "G(" + min_G + "," + max_G + ")" + "B(" + min_B + "," + max_B + ")") #if hasattr(self,'infor'): # self.infor.destroy() if ((self.varRed_H.get() > self.varRed_L.get()) and (self.varGreen_H.get() > self.varGreen_L.get()) and (self.varBlue_H.get() > self.varBlue_L.get())): self.infor_Alg2.delete('1.0', END) self.infor_Alg2.insert(END, self.text_Extract) self.ThExtract.withdraw() else: tkMessageBox.showinfo(title="fail", message="again") def confirm_LoadData(self): self.master = Tk() self.master.title("pass") self.master.geometry("200x70+350+350") self.content = StringVar() self.entry = Entry(self.master, text="000", textvariable=self.content) self.entry.pack() b = Button(self.master, text="get", width=10, command=self.getdata_Load) b.pack() text123 = self.content.get() self.content.set(text123) def getdata_Load(self): if self.entry.get() == "1111": self.master.destroy() tkMessageBox.showinfo(title="Load", message="LoadData success !!") self.LoadData() else: tkMessageBox.showinfo(title="fail", message="again") def LoadData(self): print "Load" f = open('a.txt', 'r') self.SumData = f.readline() load_binary = f.readline() load_extract = f.readline() load_area1 = f.readline() #self.ThBinary.deiconify() text_binary = (load_binary[10] + load_binary[11] + load_binary[12] + load_binary[13] + load_binary[14] + load_binary[15] + load_binary[16]) text_extract = ( load_extract[10] + load_extract[11] + load_extract[12] + load_extract[13] + load_extract[14] + load_extract[15] + load_extract[16] + load_extract[17] + load_extract[18] + load_extract[19] + load_extract[20] + load_extract[21] + load_extract[22] + load_extract[23] + load_extract[24] + load_extract[25] + load_extract[26] + load_extract[27] + load_extract[28] + load_extract[29] + load_extract[30] + load_extract[31] + load_extract[32] + load_extract[33] + load_extract[34] + load_extract[35] + load_extract[36] + load_extract[37] + load_extract[38] + load_extract[39]) text_area1 = (load_area1[8] + load_area1[9] + load_area1[10] + load_area1[11] + load_area1[12] + load_area1[13] + load_area1[14] + load_area1[15] + load_area1[16] + load_area1[17] + load_area1[18] + load_area1[19] + load_area1[20] + load_area1[21] + load_area1[22]) value_low_binary = int(load_binary[10] + load_binary[11] + load_binary[12]) value_high_binary = int(load_binary[14] + load_binary[15] + load_binary[16]) #### value_low_red = int(load_extract[12] + load_extract[13] + load_extract[14]) value_high_red = int(load_extract[16] + load_extract[17] + load_extract[18]) value_low_green = int(load_extract[22] + load_extract[23] + load_extract[24]) value_high_green = int(load_extract[26] + load_extract[27] + load_extract[28]) value_low_blue = int(load_extract[32] + load_extract[33] + load_extract[34]) value_high_blue = int(load_extract[36] + load_extract[37] + load_extract[38]) #### value_area1_x0 = int(load_area1[8] + load_area1[9] + load_area1[10]) value_area1_y0 = int(load_area1[12] + load_area1[13] + load_area1[14]) value_area1_x1 = int(load_area1[16] + load_area1[17] + load_area1[18]) value_area1_y1 = int(load_area1[20] + load_area1[21] + load_area1[22]) ####### self.x0_1 = value_area1_x0 self.y0_1 = value_area1_y0 self.x1_1 = value_area1_x1 self.y1_1 = value_area1_y1 ####### self.varHigh = IntVar() self.varLow = IntVar() self.varRed_L = IntVar() self.varRed_H = IntVar() self.varGreen_L = IntVar() self.varGreen_H = IntVar() self.varBlue_L = IntVar() self.varBlue_H = IntVar() self.varLow.set(value_low_binary) self.varHigh.set(value_high_binary) self.varRed_L.set(value_low_red) self.varRed_H.set(value_high_red) self.varGreen_L.set(value_low_green) self.varGreen_H.set(value_high_green) self.varBlue_L.set(value_low_blue) self.varBlue_H.set(value_high_blue) self.text_binary = text_binary self.text_Extract = text_extract self.text_area1 = text_area1 self.infor_Alg1.delete('1.0', END) self.infor_Alg1.insert(END, self.text_binary) self.infor_Alg2.delete('1.0', END) self.infor_Alg2.insert(END, self.text_Extract) self.infor_Area1.delete('1.0', END) self.infor_Area1.insert(END, self.text_area1) if self.SumData[0] == "1": self.var1.set(1) else: self.var1.set(0) if self.SumData[1] == "1": self.var2.set(1) else: self.var2.set(0) if self.SumData[2] == "1": self.var3.set(1) else: self.var3.set(0) if self.SumData[3] == "1": self.var4.set(1) else: self.var4.set(0) if self.SumData[4] == "1": self.var5.set(1) else: self.var5.set(0) self.set_Area() #self.inforData_binary="Binary : (" + self.text_binary + ")" #self.inforData_Extract="Extract : " + self.text_Extract #self.inforData=self.inforData_binary + "\n" + self.inforData_Extract #print self.inforData def Area(self): print "asasas"
class EktaproGUI(Tk): """ Constructs the main program window and interfaces with the EktaproController and the TimerController to access the slide projectors. """ def __init__(self): self.controller = EktaproController() self.controller.initDevices() Tk.__init__(self) self.protocol("WM_DELETE_WINDOW", self.onQuit) self.wm_title("EktaproGUI") self.bind("<Prior>", self.priorPressed) self.bind("<Next>", self.nextPressed) self.brightness = 0 self.slide = 1 self.timerController = TimerController(self.controller, self) self.controlPanel = Frame(self) self.manualPanel = Frame(self) self.projektorList = Listbox(self, selectmode=SINGLE) for i in range(len(self.controller.devices)): self.projektorList.insert(END, "[" + str(i) + "] " + str(self.controller.devices[i])) if self.projektorList.size >= 1: self.projektorList.selection_set(0) self.projektorList.bind("<ButtonRelease>", self.projektorSelectionChanged) self.projektorList.config(width=50) self.initButton = Button(self.controlPanel, text="init", command=self.initButtonPressed) self.nextButton = Button(self.controlPanel, text="next slide", command=self.nextSlidePressed) self.nextButton.config(state=DISABLED) self.prevButton = Button(self.controlPanel, text="previous slide", command=self.prevSlidePressed) self.prevButton.config(state=DISABLED) self.startButton = Button(self.controlPanel, text="start timer", command=self.startTimer) self.startButton.config(state=DISABLED) self.pauseButton = Button(self.controlPanel, text="pause", command=self.pauseTimer) self.stopButton = Button(self.controlPanel, text="stop", command=self.stopTimer) self.stopButton.config(state=DISABLED) self.timerLabel = Label(self.controlPanel, text="delay:") self.timerInput = Entry(self.controlPanel, width=3) self.timerInput.insert(0, "5") self.timerInput.config(state=DISABLED) self.timerInput.bind("<KeyPress-Return>", self.inputValuesChanged) self.timerInput.bind("<ButtonRelease>", self.updateGUI) self.fadeLabel = Label(self.controlPanel, text="fade:") self.fadeInput = Entry(self.controlPanel, width=3) self.fadeInput.insert(0, "1") self.fadeInput.config(state=DISABLED) self.fadeInput.bind("<KeyPress-Return>", self.inputValuesChanged) self.fadeInput.bind("<ButtonRelease>", self.updateGUI) self.standbyButton = Button(self.controlPanel, text="standby", command=self.toggleStandby) self.standbyButton.config(state=DISABLED) self.syncButton = Button(self.controlPanel, text="sync", command=self.sync) self.syncButton.config(state=DISABLED) self.reconnectButton = Button(self.controlPanel, text="reconnect", command=self.reconnect) self.cycle = IntVar() self.cycleButton = Checkbutton( self.controlPanel, text="use all projectors", variable=self.cycle, command=self.cycleToggled ) self.brightnessScale = Scale(self.manualPanel, from_=0, to=100, resolution=1, label="brightness") self.brightnessScale.set(self.brightness) self.brightnessScale.bind("<ButtonRelease>", self.brightnessChanged) self.brightnessScale.config(state=DISABLED) self.brightnessScale.config(orient=HORIZONTAL) self.brightnessScale.config(length=400) self.gotoSlideScale = Scale(self.manualPanel, from_=0, to=self.controller.maxTray, label="goto slide") self.gotoSlideScale.set(1) self.gotoSlideScale.bind("<ButtonRelease>", self.gotoSlideChanged) self.gotoSlideScale.config(state=DISABLED) self.gotoSlideScale.config(orient=HORIZONTAL) self.gotoSlideScale.config(length=400) self.controlPanel.pack(side=BOTTOM, anchor=W, fill=X) self.projektorList.pack(side=LEFT, fill=BOTH) self.manualPanel.pack(side=RIGHT, expand=1, fill=BOTH) self.initButton.pack(side=LEFT, anchor=N, padx=4, pady=4) self.prevButton.pack(side=LEFT, anchor=N, padx=4, pady=4) self.nextButton.pack(side=LEFT, anchor=N, padx=4, pady=4) self.cycleButton.pack(side=LEFT, anchor=N, padx=4, pady=4) self.startButton.pack(side=LEFT, anchor=N, padx=4, pady=4) self.pauseButton.pack(side=LEFT, anchor=N, padx=4, pady=4) self.stopButton.pack(side=LEFT, anchor=N, padx=4, pady=4) self.timerLabel.pack(side=LEFT, anchor=N, padx=4, pady=4) self.timerInput.pack(side=LEFT, anchor=N, padx=4, pady=4) self.fadeLabel.pack(side=LEFT, anchor=N, padx=4, pady=4) self.fadeInput.pack(side=LEFT, anchor=N, padx=4, pady=4) self.syncButton.pack(side=RIGHT, anchor=N, padx=4, pady=4) self.standbyButton.pack(side=RIGHT, anchor=N, padx=4, pady=4) self.reconnectButton.pack(side=RIGHT, anchor=N, padx=4, pady=4) self.brightnessScale.pack(side=TOP, anchor=W, expand=1, fill=X) self.gotoSlideScale.pack(side=TOP, anchor=W, expand=1, fill=X) self.menubar = Menu(self) self.toolsmenu = Menu(self.menubar) self.helpmenu = Menu(self.menubar) self.filemenu = Menu(self.menubar) self.toolsmenu.add_command(label="Interpret HEX Sequence", command=self.interpretHEXDialog) self.helpmenu.add_command( label="About EktaproGUI", command=lambda: tkMessageBox.showinfo("About EktaproGUI", "EktaproGUI 1.0 (C)opyright Julian Hoch 2010"), ) self.filemenu.add_command(label="Exit", command=self.onQuit) self.menubar.add_cascade(label="File", menu=self.filemenu) self.menubar.add_cascade(label="Tools", menu=self.toolsmenu) self.menubar.add_cascade(label="Help", menu=self.helpmenu) self.configure(menu=self.menubar) def initButtonPressed(self): self.controller.resetDevices() self.updateGUI() self.brightnessScale.config(state=NORMAL) self.gotoSlideScale.config(state=NORMAL) self.nextButton.config(state=NORMAL) self.prevButton.config(state=NORMAL) self.startButton.config(state=NORMAL) self.timerInput.config(state=NORMAL) self.fadeInput.config(state=NORMAL) self.syncButton.config(state=NORMAL) self.standbyButton.config(state=NORMAL) def inputValuesChanged(self, event): try: fadeDelay = int(self.fadeInput.get()) slideshowDelay = int(self.timerInput.get()) if fadeDelay in range(0, 60): self.timerController.fadeDelay = fadeDelay if slideshowDelay in range(1, 60): self.timerController.slideshowDelay = slideshowDelay except Exception: pass self.updateGUI() def sync(self): self.controller.syncDevices() self.updateGUI() def reconnect(self): self.controller.cleanUp() self.controller.initDevices() self.updateGUI() self.projektorList.delete(0, END) for i in range(len(self.controller.devices)): self.projektorList.insert(END, "[" + str(i) + "] " + str(self.controller.devices[i])) if self.projektorList.size >= 1: self.projektorList.selection_set(0) def projektorSelectionChanged(self, event): items = map(int, self.projektorList.curselection()) if self.controller.setActiveDevice(items): self.updateGUI() def updateGUI(self, event=None): if self.controller.activeDevice == None: return self.brightness = self.controller.activeDevice.brightness self.brightnessScale.set(self.brightness) self.slide = self.controller.activeDevice.slide self.gotoSlideScale.set(self.slide) for i in range(self.projektorList.size()): if i == self.controller.activeIndex: self.projektorList.selection_set(i) else: self.projektorList.selection_clear(i) def brightnessChanged(self, event): newBrightness = self.brightnessScale.get() if not self.brightness == newBrightness and not self.controller.activeDevice == None: self.controller.activeDevice.setBrightness(newBrightness) self.brightness = self.brightnessScale.get() def gotoSlideChanged(self, event): if self.controller.activeDevice is None: return newSlide = self.gotoSlideScale.get() if not self.slide == newSlide: self.controller.activeDevice.gotoSlide(newSlide) self.slide = newSlide def nextSlidePressed(self): if self.controller.activeDevice is None: return self.timerController.fadePaused = False self.timerController.nextSlide() self.updateGUI() def prevSlidePressed(self): if self.controller.activeDevice is None: return self.timerController.fadePaused = False self.timerController.previousSlide() self.updateGUI() def startTimer(self): self.stopButton.config(state=NORMAL) self.startButton.config(state=DISABLED) self.timerController.startSlideshow() def pauseTimer(self): if self.timerController.fadePaused or self.timerController.slideshowPaused: self.pauseButton.config(text="pause") self.timerController.resume() self.updateGUI() else: self.pauseButton.config(text="resume") self.timerController.pause() self.updateGUI() def stopTimer(self): self.pauseButton.config(text="pause") self.stopButton.config(state=DISABLED) self.startButton.config(state=NORMAL) self.timerController.stopSlideshow() self.updateGUI() def cycleToggled(self): self.timerController.cycle = True if self.cycle.get() == 1 else False def interpretHEXDialog(self): interpretDialog = InterpretHEXDialog(self) # @UnusedVariable def toggleStandby(self): if self.pauseButton.config()["text"][4] == "pause" and self.pauseButton.config()["state"][4] == "normal": self.pauseTimer() self.controller.toggleStandby() def nextPressed(self, event): if self.startButton.config()["state"][4] == "disabled": self.pauseTimer() else: self.nextSlidePressed() def priorPressed(self, event): if self.startButton.config()["state"][4] == "disabled": self.toggleStandby() else: self.prevSlidePressed() def onQuit(self): self.controller.cleanUp() self.destroy()
orient=HORIZONTAL, label="Decay", relief=FLAT) #Sets initial FDL constant values timeInput.set(100) springInput.set(250) coulombInput.set(500) decayInput.set(90) #Initializes the canvas for animation canvas = Canvas(width=width, height=height, bg="#f0f0f0") canvas.pack(fill="both", expand=1, padx=50) #Adds teh sliders to the tkinter frame after the canvas for positioning timeInput.pack(side=LEFT, padx=50, pady=10) springInput.pack(side=LEFT, padx=50, pady=10) coulombInput.pack(side=LEFT, padx=50, pady=10) decayInput.pack(side=LEFT, padx=50, pady=10) #Smallest node size in pixels RADIUS = 5 #Calculates the euclidean distance between an oval and a point def distance(x, y, coords): x0, y0, x1, y1 = coords # tuple (x0,y0,x1,y1) x2 = (x0 + x1) / 2.0 y2 = (y0 + y1) / 2.0 return ((x - x2)**2 + (y - y2)**2)**0.5
def send_values(_): vr, vg, vb = r.get(), g.get(), b.get() res = "{},{},{}".format(vr, vg*212.0/255.0, vb*164.0/255.0) print res ser.write(res+'\n') ard = ser.readline() print ard ard = ser.readline() print ard master = Tk() r = Scale(master, from_=0, to=255, length=250, orient=HORIZONTAL, label="red", command=send_values) r.pack() g = Scale(master, from_=0, to=255, length=250, orient=HORIZONTAL, label="green", command=send_values) g.pack() b = Scale(master, from_=0, to=255, length=250, orient=HORIZONTAL, label="blue", command=send_values) b.pack() master.geometry('{}x{}'.format(300, 200)) print r.get() mainloop()
class WindowExample(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.result = 0 self.master.title("This is a test") self.master.minsize(width = 600, height = 800) #self.master. self.prompt = Label(self, text = "Enter a number:", anchor = "w", fg = "#984301") self.entry = Entry(self, width = 50, highlightcolor = "red") self.submit = Button(self, text = "Submit", command = self.calculate) self.exit = Button(self, text = "Exit", command = parent.destroy, fg = "red") self.output = Label(self, text = "") self.menu = Menu(self, title = "Menu test", bg = "black") self.canvas = Canvas(self, cursor = "circle", highlightcolor = "blue", bg = "#019bf0") self.button1 = Button(self, text = "tast antum", bg = "red", fg = "green", command = self.newWindow, \ activebackground = "red", activeforeground = "blue", relief = "sunken", cursor = "dot") self.newFrame = Frame(self, bg = "green", highlightcolor = "blue") self.button2 = Button(self.newFrame, text = "This is a tast") self.button2.grid() self.scale = Scale(self, from_ = 50, to_ = 60, orient = "horizontal", digits = 3, resolution = 0.25, highlightcolor = "red", command = self.calculate) self.scale.pack() self.open_file_button = Button(self, text = "Open File", command = self.openFile) self.prompt.pack(side = "top", fill = "x") self.entry.pack(side = "top", fill = "x") self.output.pack(side = "top", fill = "x", expand = True) self.submit.pack(side = "right") self.exit.pack(side = "left") self.button1.pack(fill="x") self.newFrame.pack(side="bottom", fill = "x", expand = True) self.button2.grid() self.canvas.pack() self.open_file_button.pack() #self.slider.pack() #self.tk = Tkinter.Tk() #self.tk.withdrow() #self.file_path = Tkinter.filedialog.askopenfilename() #print("test") self.entry.insert(string = "3", index = 0) #self.entry.insert(string = "blahblah", index = 3) def calculate(self, integer): integer = float(integer) #try: # i = int(self.entry.get()) # self.result = "%s*2=%s" % (i, i*2) #except ValueError: # self.result = "Please enter numbers only" self.entry.delete(0, len(self.entry.get())) self.result = "%s*2=%s" % (integer, integer*2) self.entry.insert(0, integer) self.output.configure(text=self.result) def newWindow(self): try: r2 = Tk() r2.mainloop() except ValueError: return None def openFile(self): file_in = tkFileDialog.askopenfilename() self.output.configure(text = file_in)
root.bind("<Key-plus>", lambda ev: changescale(0.15)) root.bind("<Key-minus>", lambda ev: changescale(-0.15)) amountvars = {} # each light name maps to a Tkinter.DoubleVar object which the Scale adjusts def redraw(*args): global l, amountvars, update # read the value out of each Scale amounts = dict([(k, v.get()) for k, v in amountvars.items()]) mix.setamounts(amounts) for x in mix.lightnames(): # the Scale sets this; the redraw() callback reads it amountvars[x] = DoubleVar() # a new frame for each slider row f = Frame(root, bd=1, relief="groove") f.pack(fill="x", expand=1) # title Label(f, text=x, width=10, anchor="e").pack(side="left") # slider s = Scale(f, from_=0, to=1, res=0.01, orient="horiz", variable=amountvars[x], command=redraw) s.pack(side="left", fill="x", expand=1) if x == "ambient": # the 'ambient' level (if present) starts at 1 s.set(1) root.mainloop()
#!/usr/bin/env python #coding=utf-8 from Tkinter import (Tk, Scale, Button, Label, Y, HORIZONTAL, X, mainloop) from time import ctime # def resize(ev=None): label.config(font='Helvetica -%d bold' % scale.get()) top = Tk() # top.geometry('250 X 150') txt = ctime() label = Label(top, text=txt, font='Consolas -12 bold') label.pack(fill=Y, expand=1) scale = Scale(top, from_=10, to=40, orient=HORIZONTAL, command=resize) scale.set(12) scale.pack(fill=X, expand=1) quit=Button(top, text='QUIT', command=top.quit, activeforeground='white', activebackground='red') quit.pack() mainloop()
class Screen(Observer): def __init__(self, parent, bg="white"): self.canvas = Canvas(parent, bg=bg) self.canvas.bind("<Configure>", self.resize) self.width = int(self.canvas.cget("width")) self.height = int(self.canvas.cget("height")) print("parent", parent.cget("width"), parent.cget("height")) self.magnitude = Scale(parent, length=250, orient="horizontal", label="Magnitude", sliderlength=20, showvalue=0, from_=0, to=10, tickinterval=1, relief="sunken") self.frequency = Scale(parent, length=250, orient="horizontal", label="Frequency", sliderlength=20, showvalue=0, from_=0, to=10, tickinterval=1, relief="sunken") self.phase = Scale(parent, length=250, orient="horizontal", label="Phase", sliderlength=20, showvalue=0, from_=0, to=10, tickinterval=1, relief="sunken") def update(self, model): print("View update") signal = model.get_signal() self.plot_signal(signal) def get_magnitude(self): return self.magnitude def get_frequency(self): return self.frequency def get_phase(self): return self.phase def plot_signal(self, signal, color="red"): w, h = self.canvas.winfo_width(), self.canvas.winfo_height() width, height = int(w), int(h) print(self.canvas.find_withtag("signal")) if self.canvas.find_withtag("signal"): self.canvas.delete("signal") if signal and len(signal) > 1: plot = [(x * width, height / 2.0 * (y + 1)) for (x, y) in signal] signal_id = self.canvas.create_line(plot, fill=color, smooth=1, width=3, tags="signal") return def grid(self, steps): w, h = self.canvas.cget("width"), self.canvas.cget("height") width, height = int(w), int(h) # self.canvas.create_line(10,height/2,width,height/2,arrow="last") # self.canvas.create_line(10,height-5,10,5,arrow="last") step = (width - 10) / steps * 1. for t in range(1, steps + 2): x = t * step self.canvas.create_line(x, 0, x, height) self.canvas.create_line(0, x, width, x) def packing(self): self.canvas.pack() self.magnitude.pack() self.frequency.pack() self.phase.pack() self.canvas.pack(expand=1, fill="both", padx=6) self.magnitude.pack(expand=1, fill="x", padx=2) self.frequency.pack(expand=1, fill="x", padx=2) self.phase.pack(expand=1, fill="x", padx=2) def resize(self, event): wscale = float(event.width) / self.width hscale = float(event.height) / self.height self.width = event.width self.height = event.height print("resize", wscale, hscale) # resize the canvas #self.config(width=self.width, height=self.height) scale_xy = self.width * 1.0 / self.height # rescale all the objects tagged with the "all" tag self.canvas.scale("all", 0, 0, wscale, hscale)
class GUI: def __init__(self, model, title='PyCX Simulator', interval=0, stepSize=1, param_gui_names=None): self.model = model self.titleText = title self.timeInterval = interval self.stepSize = stepSize self.param_gui_names = param_gui_names if param_gui_names is None: self.param_gui_names = {} self.param_entries = {} self.statusStr = "" self.running = False self.modelFigure = None self.currentStep = 0 self.initGUI() def initGUI(self): #create root window self.rootWindow = Tk() self.statusText = StringVar(value=self.statusStr) self.setStatusStr("Simulation not yet started") self.rootWindow.wm_title(self.titleText) self.rootWindow.protocol('WM_DELETE_WINDOW', self.quitGUI) self.rootWindow.geometry('550x700') self.rootWindow.columnconfigure(0, weight=1) self.rootWindow.rowconfigure(0, weight=1) self.frameSim = Frame(self.rootWindow) self.frameSim.pack(expand=YES, fill=BOTH, padx=5, pady=5, side=TOP) self.status = Label(self.rootWindow, width=40, height=3, relief=SUNKEN, bd=1, textvariable=self.statusText) self.status.pack(side=TOP, fill=X, padx=1, pady=1, expand=NO) self.runPauseString = StringVar() self.runPauseString.set("Run") self.buttonRun = Button(self.frameSim, width=30, height=2, textvariable=self.runPauseString, command=self.runEvent) self.buttonRun.pack(side=TOP, padx=5, pady=5) self.showHelp( self.buttonRun, "Runs the simulation (or pauses the running simulation)") self.buttonStep = Button(self.frameSim, width=30, height=2, text="Step Once", command=self.stepOnce) self.buttonStep.pack(side=TOP, padx=5, pady=5) self.showHelp(self.buttonStep, "Steps the simulation only once") self.buttonReset = Button(self.frameSim, width=30, height=2, text="Reset", command=self.resetModel) self.buttonReset.pack(side=TOP, padx=5, pady=5) self.showHelp(self.buttonReset, "Resets the simulation") for param in self.model.params: var_text = self.param_gui_names.get(param, param) can = Canvas(self.frameSim) lab = Label(can, width=25, height=1 + var_text.count('\n'), text=var_text, anchor=W, takefocus=0) lab.pack(side='left') ent = Entry(can, width=11) val = getattr(self.model, param) if isinstance(val, bool): val = int(val) # Show 0/1 which can convert back to bool ent.insert(0, str(val)) ent.pack(side='left') can.pack(side='top') self.param_entries[param] = ent if self.param_entries: self.buttonSaveParameters = Button( self.frameSim, width=50, height=1, command=self.saveParametersCmd, text="Save parameters to the running model", state=DISABLED) self.showHelp( self.buttonSaveParameters, "Saves the parameter values.\n" + "Not all values may take effect on a running model\n" + "A model reset might be required.") self.buttonSaveParameters.pack(side='top', padx=5, pady=5) self.buttonSaveParametersAndReset = Button( self.frameSim, width=50, height=1, command=self.saveParametersAndResetCmd, text="Save parameters to the model and reset the model") self.showHelp( self.buttonSaveParametersAndReset, "Saves the given parameter values and resets the model") self.buttonSaveParametersAndReset.pack(side='top', padx=5, pady=5) can = Canvas(self.frameSim) lab = Label(can, width=25, height=1, text="Step size ", justify=LEFT, anchor=W, takefocus=0) lab.pack(side='left') self.stepScale = Scale(can, from_=1, to=500, resolution=1, command=self.changeStepSize, orient=HORIZONTAL, width=25, length=150) self.stepScale.set(self.stepSize) self.showHelp( self.stepScale, "Skips model redraw during every [n] simulation steps\n" + "Results in a faster model run.") self.stepScale.pack(side='left') can.pack(side='top') can = Canvas(self.frameSim) lab = Label(can, width=25, height=1, text="Step visualization delay in ms ", justify=LEFT, anchor=W, takefocus=0) lab.pack(side='left') self.stepDelay = Scale(can, from_=0, to=max(2000, self.timeInterval), resolution=10, command=self.changeStepDelay, orient=HORIZONTAL, width=25, length=150) self.stepDelay.set(self.timeInterval) self.showHelp( self.stepDelay, "The visualization of each step is " + "delays by the given number of " + "milliseconds.") self.stepDelay.pack(side='left') can.pack(side='top') def setStatusStr(self, newStatus): self.statusStr = newStatus self.statusText.set(self.statusStr) #model control functions def changeStepSize(self, val): self.stepSize = int(val) def changeStepDelay(self, val): self.timeInterval = int(val) def saveParametersCmd(self): for param, entry in self.param_entries.items(): val = entry.get() if isinstance(getattr(self.model, param), bool): val = bool(int(val)) setattr(self.model, param, val) # See if the model changed the value (e.g. clipping) new_val = getattr(self.model, param) if isinstance(new_val, bool): new_val = int(new_val) entry.delete(0, END) entry.insert(0, str(new_val)) self.setStatusStr("New parameter values have been set") def saveParametersAndResetCmd(self): self.saveParametersCmd() self.resetModel() def runEvent(self): if not self.running: self.running = True self.rootWindow.after(self.timeInterval, self.stepModel) self.runPauseString.set("Pause") self.buttonStep.configure(state=DISABLED) if self.param_entries: self.buttonSaveParameters.configure(state=NORMAL) self.buttonSaveParametersAndReset.configure(state=DISABLED) else: self.stopRunning() def stopRunning(self): self.running = False self.runPauseString.set("Continue Run") self.buttonStep.configure(state=NORMAL) self.drawModel() if self.param_entries: self.buttonSaveParameters.configure(state=NORMAL) self.buttonSaveParametersAndReset.configure(state=NORMAL) def stepModel(self): if self.running: if self.model.step() is True: self.stopRunning() self.currentStep += 1 self.setStatusStr("Step " + str(self.currentStep)) self.status.configure(foreground='black') if (self.currentStep) % self.stepSize == 0: self.drawModel() self.rootWindow.after(int(self.timeInterval * 1.0 / self.stepSize), self.stepModel) def stepOnce(self): self.running = False self.runPauseString.set("Continue Run") self.model.step() self.currentStep += 1 self.setStatusStr("Step " + str(self.currentStep)) self.drawModel() if self.param_entries: self.buttonSaveParameters.configure(state=NORMAL) def resetModel(self): self.running = False self.runPauseString.set("Run") self.model.reset() self.currentStep = 0 self.setStatusStr("Model has been reset") self.drawModel() def drawModel(self): if self.modelFigure is None: self.modelFigure = plt.figure() plt.ion() # plt.show() will cause the plot to be actually displayed plt.show() self.model.draw() # Tell matplotlib to redraw too. The darwin-version works with more # types of matplotlib backends, but seems to fail on some Linux # machines. Hence we use the TkAgg specific method when available. if sys.platform == 'darwin': self.modelFigure.canvas.manager.show() else: self.modelFigure.canvas.manager.window.update() def start(self): if self.model.step.__doc__: self.showHelp(self.buttonStep, self.model.step.__doc__.strip()) self.model.reset() self.drawModel() self.rootWindow.mainloop() def quitGUI(self): plt.close('all') self.rootWindow.quit() self.rootWindow.destroy() def showHelp(self, widget, text): def setText(self): self.statusText.set(text) self.status.configure(foreground='blue') def showHelpLeave(self): self.statusText.set(self.statusStr) self.status.configure(foreground='black') widget.bind("<Enter>", lambda e: setText(self)) widget.bind("<Leave>", lambda e: showHelpLeave(self))
print "If Wekinator is not already listening for OSC, we will get an error." print "*******" send_address = '127.0.0.1', 6448 # OSC basic client c = OSC.OSCClient() c.connect(send_address) # set the address for all following messages def showValues(): label1.config(text=str(w1.get())) label1.after(100, showValues) oscmsg = OSC.OSCMessage() oscmsg.setAddress("/wek/inputs") oscmsg.append(float(w1.get())) c.send(oscmsg) master = Tk() w1 = Scale(master, from_=100, to=0, length=400, tickinterval=10) w1.set(0) w1.pack() label1 = Label(master, fg="green") label1.pack() showValues() master.mainloop()
selection = "V = " + str(v_var.get()) v_label.config(text = selection) updateRGB() tk = Tk() tk.wm_title("Colour Demo") canvas = Canvas(width=400, height=300, bg="#%02x%02x%02x" % (0, 0, 0)) canvas.pack() rgbFrame = LabelFrame(tk, text="RGB") rgbFrame.pack(fill="both", expand="yes") r_var = IntVar() r_scale = Scale(rgbFrame, variable = r_var, from_=0, to=255, showvalue=0, orient=HORIZONTAL, command=r_sel) r_scale.pack() r_label = Label(rgbFrame) r_label.pack() g_var = IntVar() g_scale = Scale(rgbFrame, variable = g_var, from_=0, to=255, showvalue=0, orient=HORIZONTAL, command=g_sel) g_scale.pack() g_label = Label(rgbFrame) g_label.pack() b_var = IntVar() b_scale = Scale(rgbFrame, variable = b_var, from_=0, to=255, showvalue=0, orient=HORIZONTAL, command=b_sel) b_scale.pack() b_label = Label(rgbFrame) b_label.pack()
class App(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.pack() self.vcmd = self.register(self.validate) self.hue_group = Frame(master) self.hue_group.pack() self.saturation_group = Frame(master) self.saturation_group.pack() self.value_group = Frame(master) self.value_group.pack() self.red_group = Frame(master) self.red_group.pack() self.green_group = Frame(master) self.green_group.pack() self.blue_group = Frame(master) self.blue_group.pack() self.hue = StringVar(master, 0) # range 0 360 self.hue_max = 360 self.saturation = StringVar(master, 100) # range 0 100 self.saturation_max = 100 self.value = StringVar(master, 100) # range 0 100 self.value_max = 100 self.color_max = 255 self.red = StringVar(master, 255) # range 0 255 self.green = StringVar(master, 0) # range 0 255 self.blue = StringVar(master, 0) # range 0 255 self.create_sliders(master) self.create_entries(master) def create_sliders(self, master=None): """Create the Color Sliders.""" self.hue_scale = Scale(self.hue_group, orient="horizontal", showvalue="false", variable=self.hue) self.hue_scale["from"] = 0 self.hue_scale["to"] = 360 self.hue_scale.pack(side=LEFT) self.saturation_scale = Scale(self.saturation_group, orient="horizontal", showvalue="false", variable=self.saturation) self.saturation_scale["from"] = 0 self.saturation_scale["to"] = 100 self.saturation_scale.pack(side=LEFT) self.value_scale = Scale(self.value_group, orient="horizontal", showvalue="false", variable=self.value) self.value_scale["from"] = 0 self.value_scale["to"] = 100 self.value_scale.pack(side=LEFT) self.red_scale = Scale(self.red_group, orient="horizontal", showvalue="false", variable=self.red) self.red_scale["from"] = 0 self.red_scale["to"] = 255 self.red_scale.pack(side=LEFT) self.green_scale = Scale(self.green_group, orient="horizontal", showvalue="false", variable=self.green) self.green_scale["from"] = 0 self.green_scale["to"] = 255 self.green_scale.pack(side=LEFT) self.blue_scale = Scale(self.blue_group, orient="horizontal", showvalue="false", variable=self.blue) self.blue_scale["from"] = 0 self.blue_scale["to"] = 255 self.blue_scale.pack(side=LEFT) def create_entries(self, master=None): """Create the Color Entries.""" # the number of characters wide entry fields are entry_width = 3 # Very little documentation on validation # various substitution codes # http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/entry-validation.html # useful tutorial # http://stupidpythonideas.blogspot.com/2013/12/tkinter-validation.html # man pages # http://www.tcl.tk/man/tcl8.5/TkCmd/entry.htm#M-validate self.hue_entry = Entry(self.hue_group, textvariable=self.hue, width=entry_width, validate="all", validatecommand=(self.vcmd, "%P")) self.hue_entry.pack(side=LEFT) self.saturation_entry = Entry(self.saturation_group, textvariable=self.saturation, width=entry_width, validate="all", validatecommand=(self.vcmd, "%P")) self.saturation_entry.pack(side=LEFT) self.value_entry = Entry(self.value_group, textvariable=self.value, width=entry_width, validate="all", validatecommand=(self.vcmd, "%P")) self.value_entry.pack(side=LEFT) self.red_entry = Entry(self.red_group, textvariable=self.red, width=entry_width, validate="all", validatecommand=(self.vcmd, "%P")) self.red_entry.pack(side=LEFT) self.green_entry = Entry(self.green_group, textvariable=self.green, width=entry_width, validate="all", validatecommand=(self.vcmd, "%P")) self.green_entry.pack(side=LEFT) self.blue_entry = Entry(self.blue_group, textvariable=self.blue, width=entry_width, validate="all", validatecommand=(self.vcmd, "%P")) self.blue_entry.pack(side=LEFT) def validate(self, new_value): """This argument checks to see if the new value being entered is a number.""" # checks if the string is an integer try: int(new_value) except ValueError: if new_value != "": return False return True
def add_scale(root, min_val=0, max_val=255, orientation=HORIZONTAL): if root is None: root = Tk() scale = Scale(root, from_=min_val, to=max_val, orient=orientation) scale.pack() return scale
class Example(Frame): def __init__(self, parent): Frame.__init__(self, width=1000, height=1000, background="black") self.parent = parent self.initUI() def initUI(self): self.parent.title("Cravis_ver1") self.pack(fill=BOTH, expand=1) frame = Frame(self, width=750, height=200, relief=RAISED, borderwidth=1) frame.pack(expand=True) #frame.config(bg="blue") self.pack(expand=False) ##### ##### frame2 = Frame(self, width=750, height=200, relief=RAISED, borderwidth=1) frame2.pack(expand=False) self.pack(expand=False) self.var1 = BooleanVar() self.var2 = BooleanVar() self.var3 = BooleanVar() self.var4 = BooleanVar() self.var5 = BooleanVar() self.content = IntVar() closeButton = Button(self, text="Close", background="green", command=self.error) closeButton.pack(side=RIGHT, padx=5, pady=5) okButton = Button(self, text="OK", background="green") okButton.pack(side=RIGHT) quitButton = Button(self, text="Quit", command=self.off_video) quitButton.place(x=50, y=20) startButton = Button(self, text="Start", command=self.on_start) startButton.place(x=100, y=20) TakePicButton = Button(self, text="TakePic", command=self.Takepic) TakePicButton.place(x=150, y=20) ###### cb1 = Checkbutton(self, text="Binary", variable=self.var1, command=self.on_Binary) cb1.place(x=80, y=60) cb2 = Checkbutton(self, text="Partical", variable=self.var2, command=self.on_Partical) cb2.place(x=80, y=80) cb3 = Checkbutton(self, text="Sobel", variable=self.var3, command=self.on_Sobel) cb3.place(x=80, y=100) cb4 = Checkbutton(self, text="Median", variable=self.var4, command=self.on_Median) cb4.place(x=80, y=120) cb5 = Checkbutton(self, text="Level_Adjust", variable=self.var5, command=self.on_LevelAdjust) cb5.place(x=80, y=140) ##### ################################### #infor=Text(self,state="disable",width=50,height=10,wrap='none') self.infor = Text(self, width=50, height=2) self.infor.pack() thongtin = "CHAO MUNG DEN VOI CHUONG TRINH CRAVIS_V1 DESIGN BY VISUAL GROUP" self.infor.insert(END, thongtin) ################################ menuBar = Menu(self.parent) self.parent.config(menu=menuBar) fileMenu1 = Menu(menuBar) fileMenu2 = Menu(menuBar) fileMenu3 = Menu(menuBar) fileMenu1.add_command(label="zoom", command=self.zoom) fileMenu1.add_command(label="password", command=self.password) fileMenu1.add_command(label="2", command=self.onExit) fileMenu1.add_command(label="3", command=self.onExit) fileMenu2.add_command(label="Exit", command=self.onExit) fileMenu2.add_command(label="1", command=self.onExit) fileMenu2.add_command(label="2", command=self.onExit) fileMenu2.add_command(label="3", command=self.onExit) fileMenu3.add_command(label="help", command=self.file_help) fileMenu3.add_command(label="1", command=self.onExit) fileMenu3.add_command(label="2", command=self.onExit) fileMenu3.add_command(label="3", command=self.onExit) menuBar.add_cascade(label="File", menu=fileMenu1) menuBar.add_cascade(label="Infor", menu=fileMenu2) menuBar.add_cascade(label="Help", menu=fileMenu3) ###### ####### ################################################ function for menu def onScale_H(self, val): v = int(float(val)) self.varHigh.set(v) print(v) #self.varHigh.set(v) def onScale_L(self, val): v = int(float(val)) self.varLow.set(v) print(v) ### def onScale_R_L(self, val): v = int(float(val)) self.varRed_L.set(v) print(v) def onScale_R_H(self, val): v = int(float(val)) self.varRed_H.set(v) print(v) def onScale_G_L(self, val): v = int(float(val)) self.varGreen_L.set(v) print(v) def onScale_G_H(self, val): v = int(float(val)) self.varGreen_H.set(v) print(v) def onScale_B_L(self, val): v = int(float(val)) self.varBlue_L.set(v) print(v) def onScale_B_H(self, val): v = int(float(val)) self.varBlue_H.set(v) print(v) ### def on_Select(self, val): sender = val.widget idx = sender.curselection() value = sender.get(idx) self.varSelect.set(value) def onExit(self): self.quit() def file_help(self): f = open('a.txt', 'r') line = f.readline() for line in f: print(line) def zoom(self): root.geometry("1500x500") ###################################################### ############ Algorithm def on_Binary(self): if self.var1.get() == True: print("Binary") self.show_Binary() #show window else: print("No_Binary") self.ThBinary.destroy() def on_Partical(self): if self.var2.get() == True: print("Partical") self.show_Extract() else: self.ThExtract.destroy() print("No_Partical") def on_Sobel(self): if self.var3.get() == True: print("Sobel") else: print("No_Sobel") def on_Median(self): if self.var4.get() == True: print("Median") else: print("No_Median") def on_LevelAdjust(self): if self.var5.get() == True: print("LevAd") else: print("No_LevAd") def showvideo(self): a = 0 while (cap.isOpened()): frame = Frame(cwgt, width=300, height=200, relief=RAISED, borderwidth=1) cwgt.pack(fill=BOTH, expand=True) self._camera.start_preview(fullscreen=False, window=(30, 30) + self._camera.resolution) stream = picamera.array.PiRGBArray(self._camera) #ret, frame = cap.read() #self._camera.capture(stream, format='bgr', use_video_port=True) #frame = stream.array if ret == True: #frame = cv2.flip(frame,0) #out.write(frame) cv2.imshow('frame', frame) cv2.waitKey(200) a = a + 1 print(a) #if (a==20): # cap.release() # cv2.destroyAllWindows() # ############################################################################### button to analyse image def Takepic(self): ## take pic button #ret, frame = cap.read() img = Frame(cwgt, width=300, height=200, relief=RAISED, borderwidth=1) ret, img = cap.read() #img=PhotoImage(file="img.png") cv2.imshow('yhhhhhh', img) #cv2.imshow('ugho',frame) cv2.waitKey(500) #cv2.imshow('img',img) #img_origin=PhotoImage(file="new.png") #cwgt2.img=img_origin #cwgt2.create_image(0, 0, image=img_origin) #cwgt2.create_image(0, 0, image=img) #img = cv2.imread('new.png') if self.var1.get() == True: #retval, after_Binary = cv2.threshold(img, self.varLow.get(), self.varHigh.get(), cv2.THRESH_BINARY) #cv2.imwrite("out.png",after_Binary) #after_Binary=PhotoImage(file="out.png") #cwgt.img=after_Binary #cwgt.create_image(0, 0, image=after_Binary) retval, after_Binary = cv2.threshold(img, self.varLow.get(), self.varHigh.get(), cv2.THRESH_BINARY) #after_Blurr =cv2.blur(img,(5,5)) #after_MedianBlur=cv2.medianBlur(after_Blurr,5) #cv2.imwrite("out.png",res) #after_Binary=PhotoImage(file="out.png") #cwgt.img=res #cv2.imshow("show",res) cwgt.create_image(0, 0, image=after_Binary) #cwgt.create_image(0, 0, image=mask) #after_Canny=cv2.Canny(after_MedianBlur,100,200) #findlabel=cv2.findContours(after_Blurr,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) #findlabel=cv2.findContours(after_Binary,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) #im = cv2.imread('new.png') #imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY) #ret,thresh = cv2.threshold(imgray,0,255,0) #image, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE) #img=cv2.drawContours(image,contours,-1,(0,255,0),1) #cv2.imwrite("out.png",after_Binary) #cv2.imwrite("blur.png",after_Blurr) #cv2.imwrite("median blur.png",after_MedianBlur) #cv2.imwrite("Canny.png",after_Canny) #after_Binary=PhotoImage(file="out.png") #cwgt.img=after_Binary #cwgt.create_image(0, 0, image=after_Binary) else: #cwgt.create_image(0, 0, image=img_origin) print("xsfd") #print img_origin[100,100][0] #www=img_origin.width() #print www # def on_start(self): print("xsfd") self.showvideo() def off_video(self): cwgt.frame.destroy() ######## ###################################################################################### show window def show_Binary(self): ## input Thresh_Binary self.ThBinary = Tk() self.ThBinary.geometry("350x100+350+350") self.ThBinary.title("Binary") self.scale_L = Scale(self.ThBinary, from_=255, to=0, command=self.onScale_L) self.scale_L.pack(side=LEFT, padx=10) self.varLow = IntVar() self.label1 = Label(self.ThBinary, text="LOW") self.label1.pack(side=LEFT, padx=0) self.scale_H = Scale(self.ThBinary, from_=255, to=0, command=self.onScale_H) self.scale_H.pack(side=LEFT, padx=20) self.varHigh = IntVar() self.label2 = Label(self.ThBinary, text="HIGH") self.label2.pack(side=LEFT, padx=1) binary = Button(self.ThBinary, text="OK", width=5, background="green", command=self.getdata_Binary) binary.pack(side=LEFT) #binary = Button(self.ThBinary, text="Get_Binary",background="green",command=self.getdata_Binary) #binary.pack() ######## def show_Extract(self): ## input Thresh_Extract self.ThExtract = Tk() self.ThExtract.geometry("750x100+350+350") self.ThExtract.title("Extract_Color") ### self.scale_R_L = Scale(self.ThExtract, from_=255, to=0, command=self.onScale_R_L) self.scale_R_L.pack(side=LEFT, padx=10) self.varRed_L = IntVar() self.label_R_L = Label(self.ThExtract, text="Red_L") self.label_R_L.pack(side=LEFT, padx=0) self.scale_R_H = Scale(self.ThExtract, from_=255, to=0, command=self.onScale_R_H) self.scale_R_H.pack(side=LEFT, padx=10) self.varRed_H = IntVar() self.label_R_H = Label(self.ThExtract, text="Red_H") self.label_R_H.pack(side=LEFT, padx=0) ### self.scale_G_L = Scale(self.ThExtract, from_=255, to=0, command=self.onScale_G_L) self.scale_G_L.pack(side=LEFT, padx=10) self.varGreen_L = IntVar() self.label_G_L = Label(self.ThExtract, text="Green_L") self.label_G_L.pack(side=LEFT, padx=0) self.scale_G_H = Scale(self.ThExtract, from_=255, to=0, command=self.onScale_G_H) self.scale_G_H.pack(side=LEFT, padx=10) self.varGreen_H = IntVar() self.label_G_H = Label(self.ThExtract, text="Green_H") self.label_G_H.pack(side=LEFT, padx=0) ### self.scale_B_L = Scale(self.ThExtract, from_=255, to=0, command=self.onScale_B_L) self.scale_B_L.pack(side=LEFT, padx=10) self.varBlue_L = IntVar() self.label_B_L = Label(self.ThExtract, text="Blue_L") self.label_B_L.pack(side=LEFT, padx=0) self.scale_B_H = Scale(self.ThExtract, from_=255, to=0, command=self.onScale_B_H) self.scale_B_H.pack(side=LEFT, padx=10) self.varBlue_H = IntVar() self.label_G_H = Label(self.ThExtract, text="Blue_H") self.label_G_H.pack(side=LEFT, padx=0) ### Extract = Button(self.ThExtract, text="OK", width=5, background="green", command=self.getdata_Extract) Extract.pack(side=LEFT) ########## def show_Partical(self): print("") #self.ThBinary=Tk() #self.ThBinary.geometry("200x70+350+350") #self.ThBinary.title("Binary") #self.scale_L = Scale(self.ThBinary, from_=0, to=255, command=self.onScale_L) #self.scale_L.pack(side=LEFT, padx=10) #self.varLow = IntVar() #self.label1 = Label(self.ThBinary,text="LOW") #self.label1.pack(side=LEFT,padx=0) #self.scale_H = Scale(self.ThBinary, from_=0, to=255, command=self.onScale_H) #self.scale_H.pack(side=LEFT, padx=20) #self.varHigh = IntVar() #self.label2 = Label(self.ThBinary, text="HIGH") #self.label2.pack(side=LEFT,padx=1) ######### def password(self): ##input password self.master = Tk() self.master.title("pass") self.master.geometry("200x70+350+350") self.content = StringVar() self.entry = Entry(self.master, text="000", textvariable=self.content) self.entry.pack() b = Button(self.master, text="get", width=10, command=self.getdata) b.pack() text123 = self.content.get() self.content.set(text123) print(self.content.get()) ############ def error(self): mbox.showerror("dh", "dsfsdf") mbox.showwarning("fdf", "fsdfs") ############################################################################################ get data def getdata(self): ## get password button print(self.entry.get()) if self.entry.get() == "1111": self.master.destroy() else: tkMessageBox.showinfo(title="fail", message="again") #### def getdata_Binary(self): min_binary = str(self.varLow.get()) max_binary = str(self.varHigh.get()) text_binary = str("Binary : " + min_binary + "," + max_binary) #print(text_binary) #if (self.infor) in globals(): # print "fijdkjkhkkkkkkkkkkkkkkkkkkkkkkkkk" if hasattr(self, 'infor'): self.infor.destroy() if hasattr(self, 'infor_Binary'): self.infor_Binary.destroy() #self.infor_Binary.destroy() if self.varHigh.get() > self.varLow.get(): self.infor_Binary = Text(self, width=50, height=1) self.infor_Binary.pack() self.infor_Binary.insert(END, text_binary) self.ThBinary.destroy() else: tkMessageBox.showinfo(title="fail", message="again") #### def getdata_Extract(self): min_R = str(self.varRed_L.get()) max_R = str(self.varRed_H.get()) min_G = str(self.varGreen_L.get()) max_G = str(self.varGreen_H.get()) min_B = str(self.varBlue_L.get()) max_B = str(self.varBlue_H.get()) text_Extract = str("Extract : " + "R(" + min_R + "," + max_R + ")" + "G(" + min_G + "," + max_G + ")" + "B(" + min_B + "," + max_B + ")") if hasattr(self, 'infor'): self.infor.destroy() if hasattr(self, 'infor_Extract'): self.infor_Extract.destroy() #self.infor.destroy() #self.infor_Extract.destroy() self.infor_Extract = Text(self, width=50, height=1) self.infor_Extract.pack() self.infor_Extract.insert(END, text_Extract) self.ThExtract.destroy()
def gui(self): from Tkinter import Tk, Scale, HORIZONTAL root = Tk() x = Scale(root, from_=0, to=self.HUMERUS + self.ULNA + 2, resolution=0.1, orient = HORIZONTAL, length = 400, command=lambda i: self.dump_target_position( float(i), y.get(), z.get(), g.get(), wa.get(), wr.get()) ) x.pack() x.set(8) y = Scale(root, from_=0, to=self.HUMERUS + self.ULNA + 2, resolution=0.1, orient = HORIZONTAL, length = 400, command=lambda i: self.dump_target_position( x.get(), float(i), z.get(), g.get(), wa.get(), wr.get()) ) y.pack() y.set(6) z = Scale(root, from_=0, to=175, orient = HORIZONTAL, length = 400, command=lambda i: self.dump_target_position( x.get(), y.get(), float(i), g.get(), wa.get(), wr.get()) ) z.pack() z.set(90) g = Scale(root, from_=0, to=175, orient = HORIZONTAL, length = 400, command=lambda i: self.dump_target_position( x.get(), y.get(), z.get(), float(i), wa.get(), wr.get()) ) g.pack() g.set(90) wa = Scale(root, from_=-85, to=85, orient = HORIZONTAL, length = 400, command=lambda i: self.dump_target_position( x.get(), y.get(), z.get(), g.get(), float(i), wr.get()) ) wa.pack() wa.set(0) wr = Scale(root, from_=0, to=175, orient = HORIZONTAL, length = 400, command=lambda i: self.dump_target_position( x.get(), y.get(), z.get(), g.get(), wa.get(), float(i)) ) wr.pack() wr.set(90) root.mainloop()
class Vibration(Frame): def __init__(self, parent, name="X", color="red"): """ Description : Calcul d'une vibration harmonique du type : e=a*sin(2*pi*f*t+p) Proprietes : - un parent (classe Oscilloscope) - controleurs d'amplitude, frequence, phase (classe Scale) Methodes : - update_vibration(self, event) : callback si modification de controleurs - compute(self,a,f,p) : calcul de vibration harmonique """ Frame.__init__(self) self.configure(bd=1, relief="sunken") self.parent = parent self.name = name self.scale_A = Scale(self, length=300, orient="horizontal", label=name + " Amplitude", showvalue=1, from_=0, to=10, tickinterval=1, command=self.update_vibration) self.scale_P = Scale(self, length=300, orient="horizontal", label=name + " Phase", showvalue=1, from_=0, to=90, tickinterval=20, command=self.update_vibration) self.scale_F = Scale(self, length=300, orient="horizontal", label=name + " Fréquence", showvalue=1, from_=0, to=100, tickinterval=10, command=self.update_vibration) self.scale_A.pack(expand="yes", fill="both") self.scale_P.pack(expand="yes", fill="both") self.scale_F.pack(expand="yes", fill="both") def update_vibration(self, event): """ mise a jour de courbe si modifications (amplitude, frequence, phase) """ print("Vibration.update_vibration()") print("Amplitude :", self.scale_A.get()) curve = self.compute(self.scale_A.get(), self.scale_F.get(),self.scale_P.get(), self.parent.get_time()) if not isinstance(self.parent, Tk): self.parent.draw_curve(self.name, curve) def compute(self, a=0, f=0, p=0, timeBase=1): """ Calcul de l'elongation en fonction de base de temps, amplitude, frequence, phase """ curve = [] print("Vibration.compute()") if not isinstance(self.parent, Tk): print("Base de Temps :", timeBase) #t = self.parent.get_time() #curve.append((self.scale_A.get() + 10*t, self.scale_A.get() + 10*t)) #curve.append((self.scale_A.get() + 20*t, self.scale_A.get() + 20*t)) # calcul des points de la courbe en fct de la base de temps (cf poly) for t in range(0, 1001, 5): e = a*sin(2*pi*f*t/1000*timeBase-p) x = t y = e curve.append((x,y)) return curve
springInput = Scale(root, from_=1, to=1000,orient=HORIZONTAL,label="Spring",relief = FLAT) coulombInput = Scale(root, from_=1, to=1000,orient=HORIZONTAL,label="Coulomb",relief = FLAT) decayInput = Scale(root, from_=0, to=100,orient=HORIZONTAL,label="Decay",relief = FLAT) #Sets initial FDL constant values timeInput.set(100) springInput.set(250) coulombInput.set(500) decayInput.set(90) #Initializes the canvas for animation canvas = Canvas(width=width, height=height, bg="#f0f0f0") canvas.pack(fill = "both", expand = 1, padx=50) #Adds teh sliders to the tkinter frame after the canvas for positioning timeInput.pack(side=LEFT, padx=50, pady=10) springInput.pack(side=LEFT, padx=50, pady=10) coulombInput.pack(side=LEFT, padx=50, pady=10) decayInput.pack(side=LEFT, padx=50, pady=10) #Smallest node size in pixels RADIUS = 5 #Calculates the euclidean distance between an oval and a point def distance(x,y, coords): x0, y0, x1, y1 = coords # tuple (x0,y0,x1,y1) x2 = (x0 + x1) / 2.0 y2 = (y0 + y1) / 2.0 return ( (x - x2)**2 + (y - y2)**2 ) ** 0.5
class Controller(Observer): def __init__(self,parent,view,lissajou,subjectSig,subjects): self.cursorFrame = Frame(parent) self.selectionFrame = Frame(self.cursorFrame) self.view = view self.lissajou = lissajou self.subjects = subjects self.subjectSig=subjectSig self.amp=IntVar() self.scale_amp=Scale(self.cursorFrame,variable=self.amp, label="Amplitude", orient="horizontal",length=250,from_=0,to=10, sliderlength=50,tickinterval=1,showvalue=0, command=self.update) self.freq=IntVar() self.scale_freq=Scale(self.cursorFrame,variable=self.freq, label="Frequence", orient="horizontal",length=250,from_=0,to=10, sliderlength=50,tickinterval=0,showvalue=0, command=self.update) self.offset=DoubleVar() self.scale_offset=Scale(self.cursorFrame,variable=self.offset, label="Offset", orient="horizontal",length=250,from_=-10.0,to=10.0, sliderlength=50,tickinterval=5,showvalue=0, command=self.update) self.phase=IntVar() self.scale_phase=Scale(self.cursorFrame,variable=self.phase, label="Phase", orient="horizontal",length=250,from_=-90,to=90, sliderlength=10,tickinterval=45,showvalue=0, command=self.update) self.voltVar = DoubleVar() self.voltVar.set(1) self.button1 = Radiobutton(self.selectionFrame, text="1V", variable=self.voltVar, value=1.0*5.0,command =lambda:self.update(None)) self.button1.select() self.button2 = Radiobutton(self.selectionFrame, text="2V", variable=self.voltVar, value=2.0*5.0, command =lambda:self.update(None)) self.button5 = Radiobutton(self.selectionFrame, text="5V", variable=self.voltVar, value=5.0*5.0, command =lambda:self.update(None)) self.isOffsetVar= IntVar() self.isOffset = Checkbutton(self.selectionFrame,text = "Offset",variable = self.isOffsetVar, command =lambda:self.update(None)) def update(self,event): self.update_amplitude(event) self.update_offset(event) self.update_frequency(event) self.update_phase(event) self.view.update() if self.lissajou!=None: self.lissajou.update() def update_amplitude(self,event): print("update_amplitude(self,event)",self.amp.get()) self.subjectSig.set_magnitude(self.amp.get()/self.voltVar.get()) self.subjects.generate_XYCurve() def update_frequency(self,event): print("update_frequency(self,event)",self.freq.get()) self.subjectSig.set_frequency(self.freq.get()) self.subjects.generate_XYCurve() def update_phase(self,event): print("update_phase(self,event)",self.phase.get()) self.subjectSig.set_phase(self.phase.get()) self.subjects.generate_XYCurve() def update_offset(self,event): if self.isOffsetVar.get(): print("update_offset(self,event)",self.isOffsetVar.get()) self.subjectSig.set_offset(self.offset.get()/self.voltVar.get()) self.subjects.generate_XYCurve() else: self.subjectSig.set_offset(0.0) self.subjects.generate_XYCurve() def setLissajou(self,lissajou): self.lissajou = lissajou def packing(self) : self.selectionFrame.pack(side='top') self.button1.pack(side='left') self.button2.pack(side='left') self.button5.pack(side='left') self.isOffset.pack(side='left') self.cursorFrame.pack(side='left',expand=1, fill='both') self.scale_amp.pack() self.scale_freq.pack() self.scale_offset.pack() self.scale_phase.pack()
class Generator(Frame): """ Vibration harmonique du type : e=a*sin(2*pi*f*t+p) scale_A : controleur d'Amplitude scale_F : controleur de Frequence scale_P : controleur de Phase """ def __init__(self, parent, name="X"): """ Initialisation parent : un oscilloscope name : nom du signal """ Frame.__init__(self) self.configure(bd=1, relief="sunken") self.parent = parent self.name = name self.drawVar = IntVar() self.signal = None self.draw = Checkbutton(self,text="Afficher "+self.name, selectcolor=eval('self.parent.view.color_'+name), variable=self.drawVar, onvalue = 1, offvalue = 0, command=self.parent.plot_all) self.draw.pack() self.draw.select() self.scale_A = Scale(self, length=100, orient="horizontal", label=name + " Amplitude", showvalue=1, from_=0, to=10, tickinterval=1, command=self.update_signal) self.scale_A.pack(expand="yes", fill="both") self.scale_F = Scale(self, length=100, orient="horizontal", label=name + " Fréquence", showvalue=1, from_=1, to=10, tickinterval=1, command=self.update_signal) self.scale_F.pack(expand="yes", fill="both") self.scale_P = Scale(self, length=100, orient="horizontal", label=name + " Phase", showvalue=1, from_=0, to=10, tickinterval=1, command=self.update_signal) self.scale_P.pack(expand="yes", fill="both") self.bind("<Configure>",self.update_signal) def update_signal(self, event): """ Mise a jour de signal si modifications (amplitude, frequence, phase) """ print("Vibration.update_signal()") print("Amplitude :", self.scale_A.get()) scaling=0.05 amp = scaling*self.scale_A.get() signal = self.generate_signal(a=amp,f=self.scale_F.get(), p=self.scale_P.get()) self.signal = signal if not isinstance(self.parent, Tk): self.parent.update_view(self.name, signal) self.parent.plot_all() return signal def generate_signal(self, a=1.0, f=2.0, p=0): """ Calcul de l'elongation : e=a*sin(2*pi*f*t+p) sur une periode a : amplitude f : frequence p : phase """ signal = [] samples = 1000 for t in range(0, samples): samples = float(samples) e = a * sin((2*pi*f*(t/samples)) - p) signal.append((t/samples,e)) return signal
class Generator(Frame): """ Vibration harmonique du type : e=a*sin(2*pi*f*t+p) scale_A : controleur d'Amplitude scale_F : controleur de Frequence scale_P : controleur de Phase """ def __init__(self, parent, name="X"): """ Initialisation parent : un oscilloscope name : nom du signal """ Frame.__init__(self) self.configure(bd=1, relief="sunken") self.parent = parent self.name = name self.drawVar = IntVar() self.signal = None self.draw = Checkbutton(self, text="Afficher " + self.name, selectcolor=eval('self.parent.view.color_' + name), variable=self.drawVar, onvalue=1, offvalue=0, command=self.parent.plot_all) self.draw.pack() self.draw.select() self.scale_A = Scale(self, length=100, orient="horizontal", label=name + " Amplitude", showvalue=1, from_=0, to=10, tickinterval=1, command=self.update_signal) self.scale_A.pack(expand="yes", fill="both") self.scale_F = Scale(self, length=100, orient="horizontal", label=name + " Fréquence", showvalue=1, from_=1, to=10, tickinterval=1, command=self.update_signal) self.scale_F.pack(expand="yes", fill="both") self.scale_P = Scale(self, length=100, orient="horizontal", label=name + " Phase", showvalue=1, from_=0, to=10, tickinterval=1, command=self.update_signal) self.scale_P.pack(expand="yes", fill="both") self.bind("<Configure>", self.update_signal) def update_signal(self, event): """ Mise a jour de signal si modifications (amplitude, frequence, phase) """ print("Vibration.update_signal()") print("Amplitude :", self.scale_A.get()) scaling = 0.05 amp = scaling * self.scale_A.get() signal = self.generate_signal(a=amp, f=self.scale_F.get(), p=self.scale_P.get()) self.signal = signal if not isinstance(self.parent, Tk): self.parent.update_view(self.name, signal) self.parent.plot_all() return signal def generate_signal(self, a=1.0, f=2.0, p=0): """ Calcul de l'elongation : e=a*sin(2*pi*f*t+p) sur une periode a : amplitude f : frequence p : phase """ signal = [] samples = 1000 for t in range(0, samples): samples = float(samples) e = a * sin((2 * pi * f * (t / samples)) - p) signal.append((t / samples, e)) return signal
#!/usr/bin/python import commands from Tkinter import Tk, IntVar, Scale def adjustVol(vol): commands.getoutput("/usr/sbin/mixer vol " + vol) return root = Tk() root.geometry('50x100+80+620') vol = IntVar() scale = Scale(root, variable=vol, from_=100, to=0, command=adjustVol) scale.set(commands.getoutput('/usr/sbin/mixer -S').split(':')[1]) scale.pack() root.mainloop()
class EktaproGUI(Tk): """ Constructs the main program window and interfaces with the EktaproController and the TimerController to access the slide projectors. """ def __init__(self): self.controller = EktaproController() self.controller.initDevices() Tk.__init__(self) self.protocol('WM_DELETE_WINDOW', self.onQuit) self.wm_title("EktaproGUI") self.bind("<Prior>", self.priorPressed) self.bind("<Next>", self.nextPressed) self.brightness = 0 self.slide = 1 self.timerController = TimerController(self.controller, self) self.controlPanel = Frame(self) self.manualPanel = Frame(self) self.projektorList = Listbox(self, selectmode=SINGLE) for i in range(len(self.controller.devices)): self.projektorList.insert(END, \ "[" + str(i) + "] " + str(self.controller.devices[i])) if self.projektorList.size >= 1: self.projektorList.selection_set(0) self.projektorList.bind("<ButtonRelease>", \ self.projektorSelectionChanged) self.projektorList.config(width=50) self.initButton = Button(self.controlPanel, \ text="init", \ command=self.initButtonPressed) self.nextButton = Button(self.controlPanel, \ text="next slide", \ command=self.nextSlidePressed) self.nextButton.config(state=DISABLED) self.prevButton = Button(self.controlPanel, \ text="previous slide", \ command=self.prevSlidePressed) self.prevButton.config(state=DISABLED) self.startButton = Button(self.controlPanel, \ text="start timer", \ command=self.startTimer) self.startButton.config(state=DISABLED) self.pauseButton = Button(self.controlPanel, \ text="pause", \ command=self.pauseTimer) self.stopButton = Button(self.controlPanel, \ text="stop", \ command=self.stopTimer) self.stopButton.config(state=DISABLED) self.timerLabel = Label(self.controlPanel, \ text="delay:") self.timerInput = Entry(self.controlPanel, \ width=3) self.timerInput.insert(0, "5") self.timerInput.config(state=DISABLED) self.timerInput.bind("<KeyPress-Return>", self.inputValuesChanged) self.timerInput.bind("<ButtonRelease>", self.updateGUI) self.fadeLabel = Label(self.controlPanel, \ text="fade:") self.fadeInput = Entry(self.controlPanel, \ width=3) self.fadeInput.insert(0, "1") self.fadeInput.config(state=DISABLED) self.fadeInput.bind("<KeyPress-Return>", self.inputValuesChanged) self.fadeInput.bind("<ButtonRelease>", self.updateGUI) self.standbyButton = Button(self.controlPanel, \ text="standby", \ command=self.toggleStandby) self.standbyButton.config(state=DISABLED) self.syncButton = Button(self.controlPanel, \ text="sync", \ command=self.sync) self.syncButton.config(state=DISABLED) self.reconnectButton = Button(self.controlPanel, \ text="reconnect", \ command=self.reconnect) self.cycle = IntVar() self.cycleButton = Checkbutton(self.controlPanel, \ text="use all projectors", \ variable=self.cycle, \ command=self.cycleToggled) self.brightnessScale = Scale(self.manualPanel, from_=0, to=100, resolution=1, \ label="brightness") self.brightnessScale.set(self.brightness) self.brightnessScale.bind("<ButtonRelease>", self.brightnessChanged) self.brightnessScale.config(state=DISABLED) self.brightnessScale.config(orient=HORIZONTAL) self.brightnessScale.config(length=400) self.gotoSlideScale = Scale(self.manualPanel, \ from_=0, to=self.controller.maxTray, \ label="goto slide") self.gotoSlideScale.set(1) self.gotoSlideScale.bind("<ButtonRelease>", self.gotoSlideChanged) self.gotoSlideScale.config(state=DISABLED) self.gotoSlideScale.config(orient=HORIZONTAL) self.gotoSlideScale.config(length=400) self.controlPanel.pack(side=BOTTOM, anchor=W, fill=X) self.projektorList.pack(side=LEFT, fill=BOTH) self.manualPanel.pack(side=RIGHT, expand=1, fill=BOTH) self.initButton.pack(side=LEFT, anchor=N, padx=4, pady=4) self.prevButton.pack(side=LEFT, anchor=N, padx=4, pady=4) self.nextButton.pack(side=LEFT, anchor=N, padx=4, pady=4) self.cycleButton.pack(side=LEFT, anchor=N, padx=4, pady=4) self.startButton.pack(side=LEFT, anchor=N, padx=4, pady=4) self.pauseButton.pack(side=LEFT, anchor=N, padx=4, pady=4) self.stopButton.pack(side=LEFT, anchor=N, padx=4, pady=4) self.timerLabel.pack(side=LEFT, anchor=N, padx=4, pady=4) self.timerInput.pack(side=LEFT, anchor=N, padx=4, pady=4) self.fadeLabel.pack(side=LEFT, anchor=N, padx=4, pady=4) self.fadeInput.pack(side=LEFT, anchor=N, padx=4, pady=4) self.syncButton.pack(side=RIGHT, anchor=N, padx=4, pady=4) self.standbyButton.pack(side=RIGHT, anchor=N, padx=4, pady=4) self.reconnectButton.pack(side=RIGHT, anchor=N, padx=4, pady=4) self.brightnessScale.pack(side=TOP, anchor=W, expand=1, fill=X) self.gotoSlideScale.pack(side=TOP, anchor=W , expand=1, fill=X) self.menubar = Menu(self) self.toolsmenu = Menu(self.menubar) self.helpmenu = Menu(self.menubar) self.filemenu = Menu(self.menubar) self.toolsmenu.add_command(label="Interpret HEX Sequence", \ command=self.interpretHEXDialog) self.helpmenu.add_command(label="About EktaproGUI", \ command=lambda:tkMessageBox.showinfo("About EktaproGUI", \ "EktaproGUI 1.0 (C)opyright Julian Hoch 2010")) self.filemenu.add_command(label="Exit", command=self.onQuit) self.menubar.add_cascade(label="File", menu=self.filemenu) self.menubar.add_cascade(label="Tools", menu=self.toolsmenu) self.menubar.add_cascade(label="Help", menu=self.helpmenu) self.configure(menu=self.menubar) def initButtonPressed(self): self.controller.resetDevices() self.updateGUI() self.brightnessScale.config(state=NORMAL) self.gotoSlideScale.config(state=NORMAL) self.nextButton.config(state=NORMAL) self.prevButton.config(state=NORMAL) self.startButton.config(state=NORMAL) self.timerInput.config(state=NORMAL) self.fadeInput.config(state=NORMAL) self.syncButton.config(state=NORMAL) self.standbyButton.config(state=NORMAL) def inputValuesChanged(self, event): try: fadeDelay = int(self.fadeInput.get()) slideshowDelay = int(self.timerInput.get()) if fadeDelay in range(0, 60): self.timerController.fadeDelay = fadeDelay if slideshowDelay in range(1, 60): self.timerController.slideshowDelay = slideshowDelay except Exception: pass self.updateGUI() def sync(self): self.controller.syncDevices() self.updateGUI() def reconnect(self): self.controller.cleanUp() self.controller.initDevices() self.updateGUI() self.projektorList.delete(0, END) for i in range(len(self.controller.devices)): self.projektorList.insert(END, \ "[" + str(i) + "] " + str(self.controller.devices[i])) if self.projektorList.size >= 1: self.projektorList.selection_set(0) def projektorSelectionChanged(self, event): items = map(int, self.projektorList.curselection()) if self.controller.setActiveDevice(items): self.updateGUI() def updateGUI(self, event=None): if self.controller.activeDevice == None: return self.brightness = self.controller.activeDevice.brightness self.brightnessScale.set(self.brightness) self.slide = self.controller.activeDevice.slide self.gotoSlideScale.set(self.slide) for i in range(self.projektorList.size()): if i == self.controller.activeIndex: self.projektorList.selection_set(i) else: self.projektorList.selection_clear(i) def brightnessChanged(self, event): newBrightness = self.brightnessScale.get() if not self.brightness == newBrightness \ and not self.controller.activeDevice == None: self.controller.activeDevice.setBrightness(newBrightness) self.brightness = self.brightnessScale.get() def gotoSlideChanged(self, event): if self.controller.activeDevice is None: return newSlide = self.gotoSlideScale.get() if not self.slide == newSlide: self.controller.activeDevice.gotoSlide(newSlide) self.slide = newSlide def nextSlidePressed(self): if self.controller.activeDevice is None: return self.timerController.fadePaused = False self.timerController.nextSlide() self.updateGUI() def prevSlidePressed(self): if self.controller.activeDevice is None: return self.timerController.fadePaused = False self.timerController.previousSlide() self.updateGUI() def startTimer(self): self.stopButton.config(state=NORMAL) self.startButton.config(state=DISABLED) self.timerController.startSlideshow() def pauseTimer(self): if self.timerController.fadePaused or self.timerController.slideshowPaused: self.pauseButton.config(text="pause") self.timerController.resume() self.updateGUI() else: self.pauseButton.config(text="resume") self.timerController.pause() self.updateGUI() def stopTimer(self): self.pauseButton.config(text="pause") self.stopButton.config(state=DISABLED) self.startButton.config(state=NORMAL) self.timerController.stopSlideshow() self.updateGUI() def cycleToggled(self): self.timerController.cycle = True if self.cycle.get() == 1 else False def interpretHEXDialog(self): interpretDialog = InterpretHEXDialog(self) #@UnusedVariable def toggleStandby(self): if self.pauseButton.config()["text"][4] == "pause" \ and self.pauseButton.config()["state"][4] == "normal": self.pauseTimer() self.controller.toggleStandby() def nextPressed(self, event): if self.startButton.config()["state"][4] == "disabled": self.pauseTimer() else: self.nextSlidePressed() def priorPressed(self, event): if self.startButton.config()["state"][4] == "disabled": self.toggleStandby() else: self.prevSlidePressed() def onQuit(self): self.controller.cleanUp() self.destroy()
class TelloUI: """Wrapper class to enable the GUI.""" def __init__(self, tello, outputpath): """ Initial all the element of the GUI,support by Tkinter :param tello: class interacts with the Tello drone. Raises: RuntimeError: If the Tello rejects the attempt to enter command mode. """ self.tello = tello # videostream device self.outputPath = outputpath # the path that save pictures created by clicking the takeSnapshot button self.frame = None # frame read from h264decoder and used for pose recognition self.thread = None # thread of the Tkinter mainloop self.stopEvent = None # control variables self.distance = 0.1 # default distance for 'move' cmd self.degree = 10 # default degree for 'cw' or 'ccw' cmd # if the pose recognition mode is opened self.pose_mode = False # if the flag is TRUE,the auto-takeoff thread will stop waiting for the response from tello self.quit_waiting_flag = False # if the flag is TRUE,the pose recognition skeleton will be drawn on the GUI picture self.draw_skeleton_flag = False # pose recognition self.my_tello_pose = Tello_Pose() # record the coordinates of the nodes in the pose recognition skeleton self.points = [] # list of all the possible connections between skeleton nodes self.POSE_PAIRS = [[0, 1], [1, 2], [2, 3], [3, 4], [1, 5], [5, 6], [6, 7], [1, 14], [14, 8], [8, 9], [9, 10], [14, 11], [11, 12], [12, 13]] # initialize the root window and image panel self.root = tki.Tk() self.panel = None # self.panel_for_pose_handle_show = None # create buttons self.btn_snapshot = tki.Button(self.root, text="Snapshot!", command=self.takeSnapshot) self.btn_snapshot.pack(side="bottom", fill="both", expand="yes", padx=10, pady=5) self.btn_pose = tki.Button(self.root, text="Pose Recognition Status: Off", command=self.setPoseMode) self.btn_pose.pack(side="bottom", fill="both", expand="yes", padx=10, pady=5) self.btn_pause = tki.Button(self.root, text="Pause", relief="raised", command=self.pauseVideo) self.btn_pause.pack(side="bottom", fill="both", expand="yes", padx=10, pady=5) self.btn_landing = tki.Button(self.root, text="Open Command Panel", relief="raised", command=self.openCmdWindow) self.btn_landing.pack(side="bottom", fill="both", expand="yes", padx=10, pady=5) # start a thread that constantly pools the video sensor for # the most recently read frame self.stopEvent = threading.Event() self.thread = threading.Thread(target=self.videoLoop, args=()) self.thread.start() # set a callback to handle when the window is closed self.root.wm_title("TELLO Controller") self.root.wm_protocol("WM_DELETE_WINDOW", self.onClose) # the auto-takeoff thread will start if the 'takeoff' button on command window is clicked self.auto_takeoff_thread = threading.Thread(target=self._autoTakeoff) # the sending_command will send command to tello every 5 seconds self.sending_command_thread = threading.Thread( target=self._sendingCommand) self.get_GUI_Image_thread = threading.Thread(target=self._getGUIImage) def videoLoop(self): """ The mainloop thread of Tkinter Raises: RuntimeError: To get around a RunTime error that Tkinter throws due to threading. """ try: # start the thread that get GUI image and drwa skeleton # todo adjust 1: 采集图像时间间隔为2s (识别时间平均0.05s) time.sleep(2) self.get_GUI_Image_thread.start() while not self.stopEvent.is_set(): # read the frame for pose recognition self.frame = self.tello.read() if self.frame is None or self.frame.size == 0: continue # smoothing filter---nparray self.frame = cv2.bilateralFilter(self.frame, 5, 50, 100) # PIL image # self.frame=Image.fromarray(self.frame) # img.show() # cv2 image # self.frame = cv2.cvtColor(np.asarray(self.frame), cv2.COLOR_RGB2BGR) # every 2 second # time.sleep(2) cmd = '' self.points.append(None) # process pose-recognition if self.pose_mode: # cmd, self.draw_skeleton_flag, self.points = self.my_tello_pose.detect(self.frame) cmd = self.my_tello_pose.detect_v1(self.frame) # todo adjust 2: 根据返回的识别结果发送相应的指令 # 移动距离 dis = 0.4 # 间隔时间 slp = 5 # 老虎 if cmd == 'tiger' or cmd == 'tabby': self.takeSnapshot() time.sleep(slp) self.telloMoveLeft(dis) # 豹 elif cmd == 'leopard': self.takeSnapshot() time.sleep(slp) self.telloMoveLeft(dis) # 小熊猫 elif cmd == 'lesser panda' or cmd == 'West Highland white terrier' or cmd == 'polecat': self.takeSnapshot() time.sleep(slp) self.telloMoveLeft(dis) # 非洲大鳄鱼 elif cmd == 'African crocodile' or cmd == 'American alligator': # self.takeSnapshot() time.sleep(slp) self.telloMoveLeft(dis) # 蝎子 elif cmd == 'scorpion': # self.takeSnapshot() time.sleep(slp) self.telloMoveLeft(dis) # 蛇 elif cmd == 'green snake' or cmd == 'green mamba' or cmd == 'eel' or cmd == 'cucumber': # self.takeSnapshot() time.sleep(slp) self.telloFlip_b() time.sleep(slp) self.telloLanding() elif cmd=='nematode' or cmd == 'envelope' or cmd=='binder' or cmd =='book jacket' or cmd=='window screen'\ or cmd=='paper towel': time.sleep(slp) self.telloMoveLeft(0.2) # time.sleep(slp) # if cmd=='show time':#检测到时机向后飞 0.3m,然后降落 # self.telloMoveBackward(0.3) # time.sleep(3) # self.telloLanding() # elif cmd=='bucket': # self.telloMoveForward(1.0) # time.sleep(3) # self.telloLanding() # process command - map your motion to whatever Tello movement you want! # if cmd == 'moveback': # self.telloMoveBackward(0.30) # elif cmd == 'moveforward': # self.telloMoveForward(0.30) # elif cmd == 'land': # self.telloLanding() except RuntimeError: print("[INFO] caught a RuntimeError") def _getGUIImage(self): """ Main operation to read frames from h264decoder and draw skeleton on frames if the pose mode is opened """ # read the system of your computer system = platform.system() while not self.stopEvent.is_set(): # read the frame for GUI show frame = self.tello.read() if frame is None or frame.size == 0: continue if self.pose_mode: # Draw the detected skeleton points for i in range(15): if self.draw_skeleton_flag == True: cv2.circle(frame, self.points[i], 8, (0, 255, 255), thickness=-1, lineType=cv2.FILLED) cv2.putText(frame, "{}".format(i), self.points[i], cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2, lineType=cv2.LINE_AA) # Draw Skeleton # for pair in self.POSE_PAIRS: # partA = pair[0] # partB = pair[1] # if self.points[partA] and self.points[partB]: # cv2.line(frame, self.points[partA], self.points[partB], (0, 255, 255), 2) # cv2.circle(frame, self.points[partA], 8, (0, 0, 255), thickness=-1, lineType=cv2.FILLED) # transfer the format from frame to image image = Image.fromarray(frame) # we found compatibility problem between Tkinter,PIL and Macos,and it will # sometimes result the very long preriod of the "ImageTk.PhotoImage" function, # so for Macos,we start a new thread to execute the _updateGUIImage function. if system == "Windows" or system == "Linux": self._updateGUIImage(image) # time.sleep(0.5) else: thread_tmp = threading.Thread(target=self._updateGUIImage, args=(image, )) thread_tmp.start() time.sleep(0.03) def _updateGUIImage(self, image): """ Main operation to initial the object of image,and update the GUI panel """ image = ImageTk.PhotoImage(image) # if the panel none ,we need to initial it if self.panel is None: self.panel = tki.Label(image=image) self.panel.image = image self.panel.pack(side="left", padx=10, pady=10) # otherwise, simply update the panel else: self.panel.configure(image=image) self.panel.image = image def _autoTakeoff(self): """ Firstly,it will waiting for the response that will be sent by Tello if Tello finish the takeoff command.If computer doesn't receive the response,it may be because tello doesn't takeoff normally,or because the UDP pack of response is lost.So in order to confirm the reason,computer will send 'height?'command to get several real-time height datas and get a average value.If the height is in normal range,tello will execute the moveup command.Otherwise,tello will land. Finally,the sending-command thread will start. """ response = None height_tmp = 0 # temp variable to content value of height height_val = 0 # average value of height cnt = 0 # effective number of height reading # todo change 1: set max time out timeout = 8 # max waiting time of tello's response timer = threading.Timer(timeout, self._setQuitWaitingFlag) timer.start() # waiting for the response from tello while response != 'ok': if self.quit_waiting_flag is True: break response = self.tello.get_response() print "ack:%s" % response timer.cancel() # receive the correct response if response == 'ok': # self.tello.move_up(0.5) self.tello.move_up(0.1) # calculate the height of tello else: # todo change 2: calcute the ave height for i in range(0, 10): time.sleep(0.5) height_tmp = self.tello.get_height() try: height_val = height_val + height_tmp cnt = cnt + 1 print height_tmp, cnt except: height_val = height_val height_val = height_val / cnt # if the height value is in normal range if height_val == 9 or height_val == 10 or height_val == 11: # todo change 3: 成功起飞后的默认提升高度 self.tello.move_up(0.2) else: self.tello.land() # start the sendingCmd thread self.sending_command_thread.start() def _sendingCommand(self): """ start a while loop that sends 'command' to tello every 5 second """ while True: self.tello.send_command('command') time.sleep(5) def _setQuitWaitingFlag(self): """ set the variable as TRUE,it will stop computer waiting for response from tello """ self.quit_waiting_flag = True def openCmdWindow(self): """ open the cmd window and initial all the button and text """ panel = Toplevel(self.root) panel.wm_title("Command Panel") # create text input entry text0 = tki.Label( panel, text= 'This Controller map keyboard inputs to Tello control commands\n' 'Adjust the trackbar to reset distance and degree parameter', font='Helvetica 10 bold') text0.pack(side='top') text1 = tki.Label( panel, text='W - Move Tello Up\t\t\tArrow Up - Move Tello Forward\n' 'S - Move Tello Down\t\t\tArrow Down - Move Tello Backward\n' 'A - Rotate Tello Counter-Clockwise\tArrow Left - Move Tello Left\n' 'D - Rotate Tello Clockwise\t\tArrow Right - Move Tello Right', justify="left") text1.pack(side="top") self.btn_landing = tki.Button(panel, text="Land", relief="raised", command=self.telloLanding) self.btn_landing.pack(side="bottom", fill="both", expand="yes", padx=10, pady=5) self.btn_takeoff = tki.Button(panel, text="Takeoff", relief="raised", command=self.telloTakeOff) self.btn_takeoff.pack(side="bottom", fill="both", expand="yes", padx=10, pady=5) # binding arrow keys to drone control self.tmp_f = tki.Frame(panel, width=100, height=2) self.tmp_f.bind('<KeyPress-w>', self.on_keypress_w) self.tmp_f.bind('<KeyPress-s>', self.on_keypress_s) self.tmp_f.bind('<KeyPress-a>', self.on_keypress_a) self.tmp_f.bind('<KeyPress-d>', self.on_keypress_d) self.tmp_f.bind('<KeyPress-Up>', self.on_keypress_up) self.tmp_f.bind('<KeyPress-Down>', self.on_keypress_down) self.tmp_f.bind('<KeyPress-Left>', self.on_keypress_left) self.tmp_f.bind('<KeyPress-Right>', self.on_keypress_right) self.tmp_f.pack(side="bottom") self.tmp_f.focus_set() self.btn_landing = tki.Button(panel, text="Flip", relief="raised", command=self.openFlipWindow) self.btn_landing.pack(side="bottom", fill="both", expand="yes", padx=10, pady=5) self.distance_bar = Scale(panel, from_=0.02, to=5, tickinterval=0.01, digits=3, label='Distance(m)', resolution=0.01) self.distance_bar.set(0.2) self.distance_bar.pack(side="left") self.btn_distance = tki.Button( panel, text="Reset Distance", relief="raised", command=self.updateDistancebar, ) self.btn_distance.pack(side="left", fill="both", expand="yes", padx=10, pady=5) self.degree_bar = Scale(panel, from_=1, to=360, tickinterval=10, label='Degree') self.degree_bar.set(30) self.degree_bar.pack(side="right") self.btn_distance = tki.Button(panel, text="Reset Degree", relief="raised", command=self.updateDegreebar) self.btn_distance.pack(side="right", fill="both", expand="yes", padx=10, pady=5) def openFlipWindow(self): """ open the flip window and initial all the button and text """ panel = Toplevel(self.root) panel.wm_title("Gesture Recognition") self.btn_flipl = tki.Button(panel, text="Flip Left", relief="raised", command=self.telloFlip_l) self.btn_flipl.pack(side="bottom", fill="both", expand="yes", padx=10, pady=5) self.btn_flipr = tki.Button(panel, text="Flip Right", relief="raised", command=self.telloFlip_r) self.btn_flipr.pack(side="bottom", fill="both", expand="yes", padx=10, pady=5) self.btn_flipf = tki.Button(panel, text="Flip Forward", relief="raised", command=self.telloFlip_f) self.btn_flipf.pack(side="bottom", fill="both", expand="yes", padx=10, pady=5) self.btn_flipb = tki.Button(panel, text="Flip Backward", relief="raised", command=self.telloFlip_b) self.btn_flipb.pack(side="bottom", fill="both", expand="yes", padx=10, pady=5) def takeSnapshot(self): """ save the current frame of the video as a jpg file and put it into outputpath """ # grab the current timestamp and use it to construct the filename ts = datetime.datetime.now() filename = "{}.jpg".format(ts.strftime("%Y-%m-%d_%H-%M-%S")) p = os.path.sep.join((self.outputPath, filename)) # save the file cv2.imwrite(p, cv2.cvtColor(self.frame, cv2.COLOR_RGB2BGR)) print("[INFO] saved {}".format(filename)) def setPoseMode(self): """ Toggle the open/close of pose recognition mode """ if self.pose_mode is False: self.pose_mode = True self.btn_pose.config(text='Pose Recognition Status: On') else: self.pose_mode = False self.btn_pose.config(text='Pose Recognition Status: Off') def pauseVideo(self): """ Toggle the freeze/unfreze of video """ if self.btn_pause.config('relief')[-1] == 'sunken': self.btn_pause.config(relief="raised") self.tello.video_freeze(False) else: self.btn_pause.config(relief="sunken") self.tello.video_freeze(True) def telloTakeOff(self): """ send the takeoff command to tello,and wait for the first response, if get the 'error'response,remind the "battery low" warning.Otherwise, start the auto-takeoff thread """ takeoff_response = None self.tello.takeoff() time.sleep(0.2) takeoff_response = self.tello.get_response() if takeoff_response != 'error': self.auto_takeoff_thread.start() else: print "battery low,please repalce with a new one" def telloLanding(self): return self.tello.land() def telloFlip_l(self): return self.tello.flip('l') def telloFlip_r(self): return self.tello.flip('r') def telloFlip_f(self): return self.tello.flip('f') def telloFlip_b(self): return self.tello.flip('b') def telloCW(self, degree): return self.tello.rotate_cw(degree) def telloCCW(self, degree): return self.tello.rotate_ccw(degree) def telloMoveForward(self, distance): return self.tello.move_forward(distance) def telloMoveBackward(self, distance): return self.tello.move_backward(distance) def telloMoveLeft(self, distance): return self.tello.move_left(distance) def telloMoveRight(self, distance): return self.tello.move_right(distance) def telloUp(self, dist): return self.tello.move_up(dist) def telloDown(self, dist): return self.tello.move_down(dist) def updateTrackBar(self): self.my_tello_hand.setThr(self.hand_thr_bar.get()) def updateDistancebar(self): self.distance = self.distance_bar.get() print 'reset distance to %.1f' % self.distance def updateDegreebar(self): self.degree = self.degree_bar.get() print 'reset distance to %d' % self.degree def on_keypress_w(self, event): print "up %d m" % self.distance self.telloUp(self.distance) def on_keypress_s(self, event): print "down %d m" % self.distance self.telloDown(self.distance) def on_keypress_a(self, event): print "ccw %d degree" % self.degree self.tello.rotate_ccw(self.degree) def on_keypress_d(self, event): print "cw %d m" % self.degree self.tello.rotate_cw(self.degree) def on_keypress_up(self, event): print "forward %d m" % self.distance self.telloMoveForward(self.distance) def on_keypress_down(self, event): print "backward %d m" % self.distance self.telloMoveBackward(self.distance) def on_keypress_left(self, event): print "left %d m" % self.distance self.telloMoveLeft(self.distance) def on_keypress_right(self, event): print "right %d m" % self.distance self.telloMoveRight(self.distance) def on_keypress_enter(self, event): if self.frame is not None: self.registerFace() self.tmp_f.focus_set() def onClose(self): """ set the stop event, cleanup the camera, and allow the rest of the quit process to continue """ print("[INFO] closing...") self.stopEvent.set() del self.tello self.root.quit()
class WindowExample(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.result = 0 self.master.title("This is a test") self.master.minsize(width=600, height=800) #self.master. self.prompt = Label(self, text="Enter a number:", anchor="w", fg="#984301") self.entry = Entry(self, width=50, highlightcolor="red") self.submit = Button(self, text="Submit", command=self.calculate) self.exit = Button(self, text="Exit", command=parent.destroy, fg="red") self.output = Label(self, text="") self.menu = Menu(self, title="Menu test", bg="black") self.canvas = Canvas(self, cursor="circle", highlightcolor="blue", bg="#019bf0") self.button1 = Button(self, text = "tast antum", bg = "red", fg = "green", command = self.newWindow, \ activebackground = "red", activeforeground = "blue", relief = "sunken", cursor = "dot") self.newFrame = Frame(self, bg="green", highlightcolor="blue") self.button2 = Button(self.newFrame, text="This is a tast") self.button2.grid() self.scale = Scale(self, from_=50, to_=60, orient="horizontal", digits=3, resolution=0.25, highlightcolor="red", command=self.calculate) self.scale.pack() self.open_file_button = Button(self, text="Open File", command=self.openFile) self.prompt.pack(side="top", fill="x") self.entry.pack(side="top", fill="x") self.output.pack(side="top", fill="x", expand=True) self.submit.pack(side="right") self.exit.pack(side="left") self.button1.pack(fill="x") self.newFrame.pack(side="bottom", fill="x", expand=True) self.button2.grid() self.canvas.pack() self.open_file_button.pack() #self.slider.pack() #self.tk = Tkinter.Tk() #self.tk.withdrow() #self.file_path = Tkinter.filedialog.askopenfilename() #print("test") self.entry.insert(string="3", index=0) #self.entry.insert(string = "blahblah", index = 3) def calculate(self, integer): integer = float(integer) #try: # i = int(self.entry.get()) # self.result = "%s*2=%s" % (i, i*2) #except ValueError: # self.result = "Please enter numbers only" self.entry.delete(0, len(self.entry.get())) self.result = "%s*2=%s" % (integer, integer * 2) self.entry.insert(0, integer) self.output.configure(text=self.result) def newWindow(self): try: r2 = Tk() r2.mainloop() except ValueError: return None def openFile(self): file_in = tkFileDialog.askopenfilename() self.output.configure(text=file_in)
class GUI: def __init__(self, model, title='PyCX Simulator', interval=0, stepSize=1, param_gui_names=None): self.model = model self.titleText = title self.timeInterval = interval self.stepSize = stepSize self.param_gui_names = param_gui_names if param_gui_names is None: self.param_gui_names = {} self.param_entries = {} self.statusStr = "" self.running = False self.modelFigure = None self.currentStep = 0 self.initGUI() def initGUI(self): #create root window self.rootWindow = Tk() self.statusText = StringVar(value=self.statusStr) self.setStatusStr("Simulation not yet started") self.rootWindow.wm_title(self.titleText) self.rootWindow.protocol('WM_DELETE_WINDOW', self.quitGUI) self.rootWindow.geometry('550x700') self.rootWindow.columnconfigure(0, weight=1) self.rootWindow.rowconfigure(0, weight=1) self.frameSim = Frame(self.rootWindow) self.frameSim.pack(expand=YES, fill=BOTH, padx=5, pady=5, side=TOP) self.status = Label(self.rootWindow, width=40, height=3, relief=SUNKEN, bd=1, textvariable=self.statusText) self.status.pack(side=TOP, fill=X, padx=1, pady=1, expand=NO) self.runPauseString = StringVar() self.runPauseString.set("Run") self.buttonRun = Button(self.frameSim, width=30, height=2, textvariable=self.runPauseString, command=self.runEvent) self.buttonRun.pack(side=TOP, padx=5, pady=5) self.showHelp(self.buttonRun, "Runs the simulation (or pauses the running simulation)") self.buttonStep = Button(self.frameSim, width=30, height=2, text="Step Once", command=self.stepOnce) self.buttonStep.pack(side=TOP, padx=5, pady=5) self.showHelp(self.buttonStep, "Steps the simulation only once") self.buttonReset = Button(self.frameSim, width=30, height=2, text="Reset", command=self.resetModel) self.buttonReset.pack(side=TOP, padx=5, pady=5) self.showHelp(self.buttonReset, "Resets the simulation") for param in self.model.params: var_text = self.param_gui_names.get(param, param) can = Canvas(self.frameSim) lab = Label(can, width=25, height=1 + var_text.count('\n'), text=var_text, anchor=W, takefocus=0) lab.pack(side='left') ent = Entry(can, width=11) val = getattr(self.model, param) if isinstance(val, bool): val = int(val) # Show 0/1 which can convert back to bool ent.insert(0, str(val)) ent.pack(side='left') can.pack(side='top') self.param_entries[param] = ent if self.param_entries: self.buttonSaveParameters = Button(self.frameSim, width=50, height=1, command=self.saveParametersCmd, text="Save parameters to the running model", state=DISABLED) self.showHelp(self.buttonSaveParameters, "Saves the parameter values.\n" + "Not all values may take effect on a running model\n" + "A model reset might be required.") self.buttonSaveParameters.pack(side='top', padx=5, pady=5) self.buttonSaveParametersAndReset = Button(self.frameSim, width=50, height=1, command=self.saveParametersAndResetCmd, text="Save parameters to the model and reset the model") self.showHelp(self.buttonSaveParametersAndReset, "Saves the given parameter values and resets the model") self.buttonSaveParametersAndReset.pack(side='top', padx=5, pady=5) can = Canvas(self.frameSim) lab = Label(can, width=25, height=1, text="Step size ", justify=LEFT, anchor=W, takefocus=0) lab.pack(side='left') self.stepScale = Scale(can, from_=1, to=500, resolution=1, command=self.changeStepSize, orient=HORIZONTAL, width=25, length=150) self.stepScale.set(self.stepSize) self.showHelp(self.stepScale, "Skips model redraw during every [n] simulation steps\n" + "Results in a faster model run.") self.stepScale.pack(side='left') can.pack(side='top') can = Canvas(self.frameSim) lab = Label(can, width=25, height=1, text="Step visualization delay in ms ", justify=LEFT, anchor=W, takefocus=0) lab.pack(side='left') self.stepDelay = Scale(can, from_=0, to=max(2000, self.timeInterval), resolution=10, command=self.changeStepDelay, orient=HORIZONTAL, width=25, length=150) self.stepDelay.set(self.timeInterval) self.showHelp(self.stepDelay, "The visualization of each step is " + "delays by the given number of " + "milliseconds.") self.stepDelay.pack(side='left') can.pack(side='top') def setStatusStr(self, newStatus): self.statusStr = newStatus self.statusText.set(self.statusStr) #model control functions def changeStepSize(self, val): self.stepSize = int(val) def changeStepDelay(self, val): self.timeInterval = int(val) def saveParametersCmd(self): for param, entry in self.param_entries.items(): val = entry.get() if isinstance(getattr(self.model, param), bool): val = bool(int(val)) setattr(self.model, param, val) # See if the model changed the value (e.g. clipping) new_val = getattr(self.model, param) if isinstance(new_val, bool): new_val = int(new_val) entry.delete(0, END) entry.insert(0, str(new_val)) self.setStatusStr("New parameter values have been set") def saveParametersAndResetCmd(self): self.saveParametersCmd() self.resetModel() def runEvent(self): if not self.running: self.running = True self.rootWindow.after(self.timeInterval, self.stepModel) self.runPauseString.set("Pause") self.buttonStep.configure(state=DISABLED) if self.param_entries: self.buttonSaveParameters.configure(state=NORMAL) self.buttonSaveParametersAndReset.configure(state=DISABLED) else: self.stopRunning() def stopRunning(self): self.running = False self.runPauseString.set("Continue Run") self.buttonStep.configure(state=NORMAL) self.drawModel() if self.param_entries: self.buttonSaveParameters.configure(state=NORMAL) self.buttonSaveParametersAndReset.configure(state=NORMAL) def stepModel(self): if self.running: if self.model.step() is True: self.stopRunning() self.currentStep += 1 self.setStatusStr("Step " + str(self.currentStep)) self.status.configure(foreground='black') if (self.currentStep) % self.stepSize == 0: self.drawModel() self.rootWindow.after(int(self.timeInterval * 1.0 / self.stepSize), self.stepModel) def stepOnce(self): self.running = False self.runPauseString.set("Continue Run") self.model.step() self.currentStep += 1 self.setStatusStr("Step " + str(self.currentStep)) self.drawModel() if self.param_entries: self.buttonSaveParameters.configure(state=NORMAL) def resetModel(self): self.running = False self.runPauseString.set("Run") self.model.reset() self.currentStep = 0 self.setStatusStr("Model has been reset") self.drawModel() def drawModel(self): if self.modelFigure is None: self.modelFigure = plt.figure() plt.ion() self.model.draw() # Tell matplotlib to redraw too. The darwin-version works with more # types of matplotlib backends, but seems to fail on some Linux # machines. Hence we use the TkAgg specific method when available. if sys.platform == 'darwin': self.modelFigure.canvas.manager.show() else: self.modelFigure.canvas.manager.window.update() def start(self): if self.model.step.__doc__: self.showHelp(self.buttonStep, self.model.step.__doc__.strip()) self.model.reset() self.drawModel() self.rootWindow.mainloop() def quitGUI(self): plt.close('all') self.rootWindow.quit() self.rootWindow.destroy() def showHelp(self, widget, text): def setText(self): self.statusText.set(text) self.status.configure(foreground='blue') def showHelpLeave(self): self.statusText.set(self.statusStr) self.status.configure(foreground='black') widget.bind("<Enter>", lambda e: setText(self)) widget.bind("<Leave>", lambda e: showHelpLeave(self))
class TelloUI(threading.Thread): """Wrapper class to enable the GUI.""" def __init__(self,tello,outputpath): """ Initial all the element of the GUI,support by Tkinter :param tello: class interacts with the Tello drone. Raises: RuntimeError: If the Tello rejects the attempt to enter command mode. """ self.tello = tello # videostream device self.outputPath = outputpath # the path that save pictures created by clicking the takeSnapshot button self.frame = None # frame read from h264decoder and used for pose recognition self.thread = None # thread of the Tkinter mainloop self.stopEvent = None # control variables self.distance = 0.1 # default distance for 'move' cmd self.degree = 30 # default degree for 'cw' or 'ccw' cmd # *************place of cut # start a thread that constantly pools the video sensor for # the most recently read frame self.stopEvent = threading.Event() self.thread = threading.Thread(target=self.videoLoop, args=()) self.thread.start() # *************place of cut ''' #### start main loop print("before main loop") self.thread_tk_main = threading.Thread(target=self.root.mainloop(), args=()) self.thread_tk_main.start() print("after main loop") ''' threading.Thread.__init__(self) self.start() # the sending_command will send command to tello every 5 seconds # self.sending_command_thread = threading.Thread(target = self._sendingCommand) def run(self): # if the flag is TRUE,the auto-takeoff thread will stop waiting for the response from tello self.quit_waiting_flag = False # initialize the root window and image panel self.root = tki.Tk() self.panel = None # create buttons self.btn_snapshot = tki.Button(self.root, text="Snapshot!", command=self.takeSnapshot) self.btn_snapshot.pack(side="bottom", fill="both", expand="yes", padx=10, pady=5) self.btn_pause = tki.Button(self.root, text="Pause", relief="raised", command=self.pauseVideo) self.btn_pause.pack(side="bottom", fill="both", expand="yes", padx=10, pady=5) self.btn_landing = tki.Button( self.root, text="Open Command Panel", relief="raised", command=self.openCmdWindow) self.btn_landing.pack(side="bottom", fill="both", expand="yes", padx=10, pady=5) #************************************************ # set a callback to handle when the window is closed self.root.wm_title("TELLO Controller") self.root.wm_protocol("WM_DELETE_WINDOW", self.onClose) print("before main loop") self.root.mainloop() def videoLoop(self): """ The mainloop thread of Tkinter Raises: RuntimeError: To get around a RunTime error that Tkinter throws due to threading. """ try: # start the thread that get GUI image and drwa skeleton time.sleep(0.5) # self.sending_command_thread.start() while not self.stopEvent.is_set(): system = platform.system() # read the frame for GUI show self.frame = self.tello.read() if self.frame is None or self.frame.size == 0: continue # transfer the format from frame to image image = Image.fromarray(self.frame) # we found compatibility problem between Tkinter,PIL and Macos,and it will # sometimes result the very long preriod of the "ImageTk.PhotoImage" function, # so for Macos,we start a new thread to execute the _updateGUIImage function. if system =="Windows" or system =="Linux": self._updateGUIImage(image) else: thread_tmp = threading.Thread(target=self._updateGUIImage,args=(image,)) thread_tmp.start() time.sleep(0.03) except RuntimeError as e: print("[INFO] caught a RuntimeError", e) def _updateGUIImage(self,image): """ Main operation to initial the object of image,and update the GUI panel """ image = ImageTk.PhotoImage(image) # if the panel none ,we need to initial it if self.panel is None: self.panel = tki.Label(image=image) self.panel.image = image self.panel.pack(side="left", padx=10, pady=10) # otherwise, simply update the panel else: self.panel.configure(image=image) self.panel.image = image def _sendingCommand(self): """ start a while loop that sends 'command' to tello every 5 second """ while True: self.tello.send_command('command') time.sleep(30) def _setQuitWaitingFlag(self): """ set the variable as TRUE,it will stop computer waiting for response from tello """ self.quit_waiting_flag = True def openCmdWindow(self): """ open the cmd window and initial all the button and text """ panel = Toplevel(self.root) panel.wm_title("Command Panel") # create text input entry text0 = tki.Label(panel, text='This Controller map keyboard inputs to Tello control commands\n' 'Adjust the trackbar to reset distance and degree parameter', font='Helvetica 10 bold' ) text0.pack(side='top') text1 = tki.Label(panel, text= 'W - Move Tello Up\t\t\tArrow Up - Move Tello Forward\n' 'S - Move Tello Down\t\t\tArrow Down - Move Tello Backward\n' 'A - Rotate Tello Counter-Clockwise\tArrow Left - Move Tello Left\n' 'D - Rotate Tello Clockwise\t\tArrow Right - Move Tello Right', justify="left") text1.pack(side="top") self.btn_landing = tki.Button( panel, text="Land", relief="raised", command=self.telloLanding) self.btn_landing.pack(side="bottom", fill="both", expand="yes", padx=10, pady=5) self.btn_takeoff = tki.Button( panel, text="Takeoff", relief="raised", command=self.telloTakeOff) self.btn_takeoff.pack(side="bottom", fill="both", expand="yes", padx=10, pady=5) # binding arrow keys to drone control self.tmp_f = tki.Frame(panel, width=100, height=2) self.tmp_f.bind('<KeyPress-w>', self.on_keypress_w) self.tmp_f.bind('<KeyPress-s>', self.on_keypress_s) self.tmp_f.bind('<KeyPress-a>', self.on_keypress_a) self.tmp_f.bind('<KeyPress-d>', self.on_keypress_d) self.tmp_f.bind('<KeyPress-Up>', self.on_keypress_up) self.tmp_f.bind('<KeyPress-Down>', self.on_keypress_down) self.tmp_f.bind('<KeyPress-Left>', self.on_keypress_left) self.tmp_f.bind('<KeyPress-Right>', self.on_keypress_right) self.tmp_f.pack(side="bottom") self.tmp_f.focus_set() self.btn_landing = tki.Button( panel, text="Flip", relief="raised", command=self.openFlipWindow) self.btn_landing.pack(side="bottom", fill="both", expand="yes", padx=10, pady=5) self.distance_bar = Scale(panel, from_=0.02, to=5, tickinterval=0.01, digits=3, label='Distance(m)', resolution=0.01) self.distance_bar.set(0.2) self.distance_bar.pack(side="left") self.btn_distance = tki.Button(panel, text="Reset Distance", relief="raised", command=self.updateDistancebar, ) self.btn_distance.pack(side="left", fill="both", expand="yes", padx=10, pady=5) self.degree_bar = Scale(panel, from_=1, to=360, tickinterval=10, label='Degree') self.degree_bar.set(30) self.degree_bar.pack(side="right") self.btn_distance = tki.Button(panel, text="Reset Degree", relief="raised", command=self.updateDegreebar) self.btn_distance.pack(side="right", fill="both", expand="yes", padx=10, pady=5) def openFlipWindow(self): """ open the flip window and initial all the button and text """ panel = Toplevel(self.root) panel.wm_title("Gesture Recognition") self.btn_flipl = tki.Button( panel, text="Flip Left", relief="raised", command=self.telloFlip_l) self.btn_flipl.pack(side="bottom", fill="both", expand="yes", padx=10, pady=5) self.btn_flipr = tki.Button( panel, text="Flip Right", relief="raised", command=self.telloFlip_r) self.btn_flipr.pack(side="bottom", fill="both", expand="yes", padx=10, pady=5) self.btn_flipf = tki.Button( panel, text="Flip Forward", relief="raised", command=self.telloFlip_f) self.btn_flipf.pack(side="bottom", fill="both", expand="yes", padx=10, pady=5) self.btn_flipb = tki.Button( panel, text="Flip Backward", relief="raised", command=self.telloFlip_b) self.btn_flipb.pack(side="bottom", fill="both", expand="yes", padx=10, pady=5) def takeSnapshot(self): """ save the current frame of the video as a jpg file and put it into outputpath """ # grab the current timestamp and use it to construct the filename ts = datetime.datetime.now() filename = "{}.jpg".format(ts.strftime("%Y-%m-%d_%H-%M-%S")) p = os.path.sep.join((self.outputPath, filename)) # save the file cv2.imwrite(p, cv2.cvtColor(self.frame, cv2.COLOR_RGB2BGR)) print(self.frame) print("[INFO] saved {}".format(filename)) def pauseVideo(self): """ Toggle the freeze/unfreze of video """ if self.btn_pause.config('relief')[-1] == 'sunken': self.btn_pause.config(relief="raised") self.tello.video_freeze(False) else: self.btn_pause.config(relief="sunken") self.tello.video_freeze(True) def telloTakeOff(self): return self.tello.takeoff() def telloLanding(self): return self.tello.land() def telloFlip_l(self): return self.tello.flip('l') def telloFlip_r(self): return self.tello.flip('r') def telloFlip_f(self): return self.tello.flip('f') def telloFlip_b(self): return self.tello.flip('b') def telloCW(self, degree): return self.tello.rotate_cw(degree) def telloCCW(self, degree): return self.tello.rotate_ccw(degree) def telloMoveForward(self, distance): return self.tello.move_forward(distance) def telloMoveBackward(self, distance): return self.tello.move_backward(distance) def telloMoveLeft(self, distance): return self.tello.move_left(distance) def telloMoveRight(self, distance): return self.tello.move_right(distance) def telloUp(self, dist): return self.tello.move_up(dist) def telloDown(self, dist): return self.tello.move_down(dist) def updateTrackBar(self): self.my_tello_hand.setThr(self.hand_thr_bar.get()) def updateDistancebar(self): self.distance = self.distance_bar.get() print('reset distance to %.1f' % self.distance) def updateDegreebar(self): self.degree = self.degree_bar.get() print('reset distance to %d' % self.degree) def on_keypress_w(self, event): print("up %d m" % self.distance) self.telloUp(self.distance) def on_keypress_s(self, event): print("down %d m" % self.distance) self.telloDown(self.distance) def on_keypress_a(self, event): print("ccw %d degree" % self.degree) self.tello.rotate_ccw(self.degree) def on_keypress_d(self, event): print("cw %d m" % self.degree) self.tello.rotate_cw(self.degree) def on_keypress_up(self, event): print("forward %d m" % self.distance) self.telloMoveForward(self.distance) def on_keypress_down(self, event): print("backward %d m" % self.distance) self.telloMoveBackward(self.distance) def on_keypress_left(self, event): print("left %d m" % self.distance) self.telloMoveLeft(self.distance) def on_keypress_right(self, event): print("right %d m" % self.distance) self.telloMoveRight(self.distance) def on_keypress_enter(self, event): if self.frame is not None: self.registerFace() self.tmp_f.focus_set() def onClose(self): """ set the stop event, cleanup the camera, and allow the rest of the quit process to continue """ print("[INFO] closing...") self.stopEvent.set() del self.tello self.root.quit()
class GUI: def __init__(self, model, title='PyCX Simulator', interval=0, step_size=1, param_gui_names=None): self.model = model self.titleText = title self.timeInterval = interval self.stepSize = step_size self.param_gui_names = param_gui_names if param_gui_names is None: self.param_gui_names = {} self.param_entries = {} self.statusStr = "" self.running = False self.modelFigure = None self.currentStep = 0 self.init_gui() def init_gui(self): # create root window self.rootWindow = Tk() self.statusText = StringVar(value=self.statusStr) self.set_status_str("Simulation not yet started") self.rootWindow.wm_title(self.titleText) self.rootWindow.protocol('WM_DELETE_WINDOW', self.quit_gui) self.rootWindow.geometry('550x700') self.rootWindow.columnconfigure(0, weight=1) self.rootWindow.rowconfigure(0, weight=1) self.frameSim = Frame(self.rootWindow) self.frameSim.pack(expand=YES, fill=BOTH, padx=5, pady=5, side=TOP) self.status = Label(self.rootWindow, width=40, height=3, relief=SUNKEN, bd=1, textvariable=self.statusText) self.status.pack(side=TOP, fill=X, padx=1, pady=1, expand=NO) self.runPauseString = StringVar() self.runPauseString.set("Run") self.buttonRun = Button(self.frameSim, width=30, height=2, textvariable=self.runPauseString, command=self.run_event) self.buttonRun.pack(side=TOP, padx=5, pady=5) self.show_help( self.buttonRun, "Runs the simulation (or pauses the running simulation)") self.buttonStep = Button(self.frameSim, width=30, height=2, text="Step Once", command=self.step_once) self.buttonStep.pack(side=TOP, padx=5, pady=5) self.show_help(self.buttonStep, "Steps the simulation only once") self.buttonReset = Button(self.frameSim, width=30, height=2, text="Reset", command=self.reset_model) self.buttonReset.pack(side=TOP, padx=5, pady=5) self.show_help(self.buttonReset, "Resets the simulation") for param in self.model.params: var_text = self.param_gui_names.get(param, param) can = Canvas(self.frameSim) lab = Label(can, width=25, height=1 + var_text.count('\n'), text=var_text, anchor=W, takefocus=0) lab.pack(side='left') ent = Entry(can, width=11) val = getattr(self.model, param) if isinstance(val, bool): val = int(val) # Show 0/1 which can convert back to bool ent.insert(0, str(val)) ent.pack(side='left') can.pack(side='top') self.param_entries[param] = ent if self.param_entries: self.buttonSaveParameters = Button( self.frameSim, width=50, height=1, command=self.save_parameters_cmd, text="Save parameters to the running model", state=DISABLED) self.show_help( self.buttonSaveParameters, "Saves the parameter values.\n Not all values may take effect " "on a running model\n A model reset might be required.") self.buttonSaveParameters.pack(side='top', padx=5, pady=5) self.buttonSaveParametersAndReset = Button( self.frameSim, width=50, height=1, command=self.save_parameters_and_reset_cmd, text="Save parameters to the model and reset the model") self.show_help( self.buttonSaveParametersAndReset, "Saves the given parameter values and resets the model") self.buttonSaveParametersAndReset.pack(side='top', padx=5, pady=5) can = Canvas(self.frameSim) lab = Label(can, width=25, height=1, text="Step size ", justify=LEFT, anchor=W, takefocus=0) lab.pack(side='left') self.stepScale = Scale(can, from_=1, to=500, resolution=1, command=self.change_step_size, orient=HORIZONTAL, width=25, length=150) self.stepScale.set(self.stepSize) self.show_help( self.stepScale, "Skips model redraw during every [n] simulation steps\n" + " Results in a faster model run.") self.stepScale.pack(side='left') can.pack(side='top') can = Canvas(self.frameSim) lab = Label(can, width=25, height=1, text="Step visualization delay in ms ", justify=LEFT, anchor=W, takefocus=0) lab.pack(side='left') self.stepDelay = Scale(can, from_=0, to=max(2000, self.timeInterval), resolution=10, command=self.change_step_delay, orient=HORIZONTAL, width=25, length=150) self.stepDelay.set(self.timeInterval) self.show_help( self.stepDelay, "The visualization of each step is " + "delays by the given number of " + "milliseconds.") self.stepDelay.pack(side='left') can.pack(side='top') def set_status_str(self, new_status): self.statusStr = new_status self.statusText.set(self.statusStr) # model control functions def change_step_size(self, val): self.stepSize = int(val) def change_step_delay(self, val): self.timeInterval = int(val) def save_parameters_cmd(self): for param, entry in self.param_entries.items(): val = entry.get() if isinstance(getattr(self.model, param), bool): val = bool(int(val)) setattr(self.model, param, val) # See if the model changed the value (e.g. clipping) new_val = getattr(self.model, param) if isinstance(new_val, bool): new_val = int(new_val) entry.delete(0, END) entry.insert(0, str(new_val)) self.set_status_str("New parameter values have been set") def save_parameters_and_reset_cmd(self): self.save_parameters_cmd() self.reset_model() def run_event(self): if not self.running: self.running = True self.rootWindow.after(self.timeInterval, self.step_model) self.runPauseString.set("Pause") self.buttonStep.configure(state=DISABLED) if self.param_entries: self.buttonSaveParameters.configure(state=NORMAL) self.buttonSaveParametersAndReset.configure(state=DISABLED) else: self.stop_running() def stop_running(self): self.running = False self.runPauseString.set("Continue Run") self.buttonStep.configure(state=NORMAL) self.draw_model() if self.param_entries: self.buttonSaveParameters.configure(state=NORMAL) self.buttonSaveParametersAndReset.configure(state=NORMAL) def step_model(self): if self.running: if self.model.step() is True: self.stop_running() self.currentStep += 1 self.set_status_str("Step " + str(self.currentStep)) self.status.configure(foreground='black') if self.currentStep % self.stepSize == 0: self.draw_model() self.rootWindow.after(int(self.timeInterval * 1.0 / self.stepSize), self.step_model) def step_once(self): self.running = False self.runPauseString.set("Continue Run") self.model.step() self.currentStep += 1 self.set_status_str("Step " + str(self.currentStep)) self.draw_model() if self.param_entries: self.buttonSaveParameters.configure(state=NORMAL) self.currentStep += 1 def reset_model(self): self.running = False self.runPauseString.set("Run") self.model.reset() self.currentStep = 0 self.set_status_str("Model has been reset") self.draw_model() def get_point_color(self, data): point_colors = [] for i in data: point_colors.append([0, 0, 0, i / self.model.k]) return point_colors def draw_model(self): if self.modelFigure is None: self.modelFigure = plt.figure() ax = self.modelFigure.add_subplot(111) xax = ax.xaxis xax.tick_top() points = self.init_values() ax.axis([0, len(points[0]) + 1, 0, 100]) ax.invert_yaxis() plt.scatter(points[0], points[1], c=self.get_point_color(points[2]), s=5, marker='s') plt.gray() plt.ion() dpi = self.modelFigure.get_dpi() self.modelFigure.set_size_inches(550.0 / float(dpi), 550.0 / float(dpi)) self.modelFigure.canvas.manager.window.resizable("false", "false") plt.show() if sys.platform == 'darwin': self.modelFigure.canvas.manager.show() else: points = self.init_values() plt.scatter(points[0], points[1], c=self.get_point_color(points[2]), s=5, marker='s') self.modelFigure.canvas.manager.window.update() def init_values(self): data = self.model.draw() x = [] point_value = 1 for _ in data: x.append(point_value) point_value += 1 t = np.empty(len(x)) t.fill(self.currentStep) return [x, t, data] def start(self): if self.model.step.__doc__: self.show_help(self.buttonStep, self.model.step.__doc__.strip()) self.model.reset() self.draw_model() self.rootWindow.mainloop() def quit_gui(self): plt.close('all') self.rootWindow.quit() self.rootWindow.destroy() def show_help(self, widget, text): def set_text(self): self.statusText.set(text) self.status.configure(foreground='blue') def show_help_leave(self): self.statusText.set(self.statusStr) self.status.configure(foreground='black') widget.bind("<Enter>", lambda e: set_text(self)) widget.bind("<Leave>", lambda e: show_help_leave(self))
class TelloUI: """Wrapper class to enable the GUI.""" def __init__(self, tello, outputpath): """ Initial all the element of the GUI,support by Tkinter :param tello: class interacts with the Tello drone. Raises: RuntimeError: If the Tello rejects the attempt to enter command mode. """ self.tello = tello # videostream device self.outputPath = outputpath # the path that save pictures created by clicking the takeSnapshot button self.frame = None # frame read from h264decoder and used for pose recognition self.thread = None # thread of the Tkinter mainloop self.stopEvent = None # control variables self.distance = 0.3 # default distance for :sad'move' cmd self.degree = 30 # default degree for 'cw' or 'ccw' cmd # if the flag is TRUE,the auto-takeoff thread will stop waiting for the response from tello self.quit_waiting_flag = False # initialize the root window and image panel self.root = tki.Tk() self.panel = None # create buttons self.btn_tracking = tki.Button(self.root, text="Tracking", relief="raised", command=self.Tracking) self.btn_tracking.pack(side="bottom", fill="both", expand="yes", padx=10, pady=5) # self.btn_tracking = tki.Button(self.root, text="Tracking!", # command=self.Tracking) # self.tracking.pack(side="bottom", fill="both", # expand="yes", padx=10, pady=5) self.btn_snapshot = tki.Button(self.root, text="Snapshot!", command=self.takeSnapshot) self.btn_snapshot.pack(side="bottom", fill="both", expand="yes", padx=10, pady=5) # self.btn_pause = tki.Button(self.root, text="Pause", relief="raised", command=self.pauseVideo) # self.btn_pause.pack(side="bottom", fill="both", # expand="yes", padx=10, pady=5) self.btn_landing = tki.Button(self.root, text="Open Command Panel", relief="raised", command=self.openCmdWindow) self.btn_landing.pack(side="bottom", fill="both", expand="yes", padx=10, pady=5) def _updateGUIImage(self, image): """ Main operation to initial the object of image,and update the GUI panel """ image = ImageTk.PhotoImage(image) # if the panel none ,we need to initial it if self.panel is None: self.panel = tki.Label(image=image) self.panel.image = image self.panel.pack(side="left", padx=10, pady=10) # otherwise, simply update the panel else: self.panel.configure(image=image) self.panel.image = image def _sendingCommand(self): """ start a while loop that sends 'command' to tello every 5 second """ while True: self.tello.send_command('command') time.sleep(5) def _setQuitWaitingFlag(self): """ set the variable as TRUE,it will stop computer waiting for response from tello """ self.quit_waiting_flag = True def Tracking(self): # start a thread that constantly pools the video sensor for # the most recently read frame self.stopEvent = threading.Event() self.thread = threading.Thread(target=self.videoLoop, args=()) self.thread.start() # set a callback to handle when the window is closed self.root.wm_title("TELLO Controller") self.root.wm_protocol("WM_DELETE_WINDOW", self.onClose) # the sending_command will send command to tello every 5 seconds self.sending_command_thread = threading.Thread( target=self._sendingCommand) def videoLoop(self): """ The mainloop thread of Tkinter Raises: RuntimeError: To get around a RunTime error that Tkinter throws due to threading. """ try: # start the thread that get GUI image and drwa skeleton time.sleep(0.5) self.sending_command_thread.start() while not self.stopEvent.is_set(): system = platform.system() # read the frame for GUI show self.frame = self.tello.read() if self.frame is None or self.frame.size == 0: continue integral_y = 0 integral_x = 0 previous_error_y = 0 start_time = time.time() hsv = cv2.cvtColor(self.frame, cv2.COLOR_BGR2HSV) low_red = np.array([120, 150, 50], np.uint8) high_red = np.array([150, 255, 255], np.uint8) mask = cv2.inRange(hsv, low_red, high_red) # median = cv2.medianBlur(mask, 15) font = cv2.FONT_HERSHEY_COMPLEX ret, contorno, hierarchy = cv2.findContours( mask, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) mensaje2 = "Bateria =" + str(self.tellobateria()) + "%" # mensaje3 = "Altura =" + str(self.telloheight()) + "cm" # cv2.putText(self.frame, mensaje3, (10, 130), font, 1, (255, 0, 0), 1, cv2.LINE_AA) if self.tellobateria() > 50: cv2.putText(self.frame, mensaje2, (10, 100), font, 1, (0, 255, 0), 1, cv2.LINE_AA) else: cv2.putText(self.frame, mensaje2, (10, 100), font, 1, (255, 0, 0), 1, cv2.LINE_AA) SET_POINT_X = 960 / 2 SET_POINT_Y = 720 / 2 cv2.putText(self.frame, '{},{}'.format(SET_POINT_X, SET_POINT_Y), (SET_POINT_X, SET_POINT_Y), font, 0.75, (255, 255, 255), 1, cv2.LINE_AA) for cnt in contorno: area = cv2.contourArea(cnt) approx = cv2.approxPolyDP(cnt, 0.03 * cv2.arcLength(cnt, True), True) if area > 2000: # start_time = time.time() M = cv2.moments(cnt) if (M["m00"] == 0): M["m00"] = 1 x = int(M["m10"] / M["m00"]) y = int(M['m01'] / M['m00']) nuevoContorno = cv2.convexHull(cnt) cv2.circle(self.frame, (x, y), 7, (0, 0, 255), -1) cv2.drawContours(self.frame, [nuevoContorno], -1, (0, 255, 0), 5) # start_time = time.time() if len(approx) == 4: delay_pid = time.time() - start_time # start_time = time.time() # tiempo_transcurrido = time.clock() - tiempo_inicial # elapsed_time = time() - start_time mensaje80 = "tiempo =" + str(delay_pid) cv2.putText(self.frame, mensaje80, (10, 90), font, 1, (255, 255, 255), 1, cv2.LINE_AA) kpy = 0.0022 kiy = 0.0008 # kdy = 0.02 kpx = 0.0022 kix = 0.0008 # kpx = 0.0022 w = 17 medidas = cv2.minAreaRect(nuevoContorno) p = medidas[1][0] f = 1000 # distancia = (w * f)/p errorx = x - SET_POINT_X errory = y - SET_POINT_Y # mensaje = "Distancia =" + str(round(distancia, 2)) + " cm" # erroryn = errory * kp derivative_y = (errory - previous_error_y) / delay_pid # integral_y = integral_y + errory * delay_pid # pi = kpy * errory + kiy*integral_y integral_y = integral_y + errory * delay_pid integral_x = integral_x + errorx * delay_pid piy = kpy * errory + kiy * integral_y pix = kpx * errorx + kix * integral_x # pi = kp * errory + ki + errory * delay_pid # pid = kpy * errory + kiy * integral_y + kdy * derivative_y mensaje90 = "value pi =" + str(piy) cv2.putText(self.frame, mensaje90, (10, 130), font, 1, (255, 255, 255), 1, cv2.LINE_AA) # pid = kp * errory + ki + errory * delay_pid + kd * errory / derivative_y if piy >= 0: self.telloDown(piy) previous_error_y = errory else: errory2n = piy * (-1) self.telloUp(errory2n) if pix >= 0: self.telloMoveRight(pix) else: errorx2n = pix * (-1) self.telloMoveLeft(errorx2n) # cv2.putText(self.frame, mensaje, (10, 70), font, 1, (255, 255, 255), 1, cv2.LINE_AA) # cv2.putText(self.frame, '{},{}'.format(x, y), (x-60, y+45), font, 0.75, (0, 255, 0), 1, # cv2.LINE_AA) # if distancia > 100: # distancia2 = distancia - 100 # self.telloMoveForward(distancia2/100) # elif distancia < 80: # distancia3 = 100 - distancia # self.telloMoveBackward(distancia3/100) image = Image.fromarray(self.frame) if system == "Windows" or system == "Linux": self._updateGUIImage(image) else: thread_tmp = threading.Thread(target=self._updateGUIImage, args=(image)) thread_tmp.start() time.sleep(0.03) except RuntimeError as e: print("[INFO] caught a RuntimeError") def openCmdWindow(self): """ open the cmd window and initial all the button and text """ panel = Toplevel(self.root) panel.wm_title("Command Panel") # create text input entry text0 = tki.Label( panel, text= 'This Controller map keyboard inputs to Tello control commands\n' 'Adjust the trackbar to reset distance and degree parameter', font='Helvetica 10 bold') text0.pack(side='top') text1 = tki.Label( panel, text='W - Move Tello Up\t\t\tArrow Up - Move Tello Forward\n' 'S - Move Tello Down\t\t\tArrow Down - Move Tello Backward\n' 'A - Rotate Tello Counter-Clockwise\tArrow Left - Move Tello Left\n' 'D - Rotate Tello Clockwise\t\tArrow Right - Move Tello Right', justify="left") text1.pack(side="top") self.btn_landing = tki.Button(panel, text="Land", relief="raised", command=self.telloLanding) self.btn_landing.pack(side="bottom", fill="both", expand="yes", padx=10, pady=5) self.btn_takeoff = tki.Button(panel, text="Takeoff", relief="raised", command=self.telloTakeOff) self.btn_takeoff.pack(side="bottom", fill="both", expand="yes", padx=10, pady=5) # binding arrow keys to drone control self.tmp_f = tki.Frame(panel, width=100, height=2) self.tmp_f.bind('<KeyPress-w>', self.on_keypress_w) self.tmp_f.bind('<KeyPress-s>', self.on_keypress_s) self.tmp_f.bind('<KeyPress-a>', self.on_keypress_a) self.tmp_f.bind('<KeyPress-d>', self.on_keypress_d) self.tmp_f.bind('<KeyPress-Up>', self.on_keypress_up) self.tmp_f.bind('<KeyPress-Down>', self.on_keypress_down) self.tmp_f.bind('<KeyPress-Left>', self.on_keypress_left) self.tmp_f.bind('<KeyPress-Right>', self.on_keypress_right) self.tmp_f.pack(side="bottom") self.tmp_f.focus_set() self.btn_landing = tki.Button(panel, text="Flip", relief="raised", command=self.openFlipWindow) self.btn_landing.pack(side="bottom", fill="both", expand="yes", padx=10, pady=5) self.distance_bar = Scale(panel, from_=0.02, to=5, tickinterval=0.01, digits=3, label='Distance(m)', resolution=0.01) self.distance_bar.set(0.2) self.distance_bar.pack(side="left") self.btn_distance = tki.Button( panel, text="Reset Distance", relief="raised", command=self.updateDistancebar, ) self.btn_distance.pack(side="left", fill="both", expand="yes", padx=10, pady=5) self.degree_bar = Scale(panel, from_=1, to=360, tickinterval=10, label='Degree') self.degree_bar.set(30) self.degree_bar.pack(side="right") self.btn_distance = tki.Button( panel, text="Reset Degreejustin bieber love yourself", relief="raised", command=self.updateDegreebar) self.btn_distance.pack(side="right", fill="both", expand="yes", padx=10, pady=5) def openFlipWindow(self): """ open the flip window and initial all the button and text """ panel = Toplevel(self.root) panel.wm_title("Gesture Recognition") self.btn_flipl = tki.Button(panel, text="Flip Left", relief="raised", command=self.telloFlip_l) self.btn_flipl.pack(side="bottom", fill="both", expand="yes", padx=10, pady=5) self.btn_flipr = tki.Button(panel, text="Flip Right", relief="raised", command=self.telloFlip_r) self.btn_flipr.pack(side="bottom", fill="both", expand="yes", padx=10, pady=5) self.btn_flipf = tki.Button(panel, text="Flip Forward", relief="raised", command=self.telloFlip_f) self.btn_flipf.pack(side="bottom", fill="both", expand="yes", padx=10, pady=5) self.btn_flipb = tki.Button(panel, text="Flip Backward", relief="raised", command=self.telloFlip_b) self.btn_flipb.pack(side="bottom", fill="both", expand="yes", padx=10, pady=5) def takeSnapshot(self): """ save the current frame of the video as a jpg file and put it into outputpath """ # grab the current timestamp and use it to construct the filename ts = datetime.datetime.now() filename = "{}.jpg".format(ts.strftime("%Y-%m-%d_%H-%M-%S")) p = os.path.sep.join((self.outputPath, filename)) # save the file cv2.imshow("gray", self.frame) cv2.imwrite(p, cv2.cvtColor(self.frame, cv2.COLOR_RGB2BGR)) print("[INFO] saved {}".format(filename)) # def Tracking(self): def tellobateria(self): return self.tello.get_battery() def telloheight(self): return self.tello.get_height() def telloTakeOff(self): return self.tello.takeoff() def telloLanding(self): return self.tello.land() def telloFlip_l(self): return self.tello.flip('l') def telloFlip_r(self): return self.tello.flip('r') def telloFlip_f(self): return self.tello.flip('f') def telloFlip_b(self): return self.tello.flip('b') def telloCW(self, degree): return self.tello.rotate_cw(degree) def telloCCW(self, degree): return self.tello.rotate_ccw(degree) def telloMoveForward(self, distance): return self.tello.move_forward(distance) def telloMoveBackward(self, distance): return self.tello.move_backward(distance) def telloMoveLeft(self, distance): return self.tello.move_left(distance) def telloMoveRight(self, distance): return self.tello.move_right(distance) def telloUp(self, dist): return self.tello.move_up(dist) def telloDown(self, dist): return self.tello.move_down(dist) def updateTrackBar(self): self.my_tello_hand.setThr(self.hand_thr_bar.get()) def updateDistancebar(self): self.distance = self.distance_bar.get() print 'reset distance to %.1f' % self.distance def updateDegreebar(self): self.degree = self.degree_bar.get() print 'reset distance to %d' % self.degree def on_keypress_w(self, event): print "up %d m" % self.distance self.telloUp(self.distance) def on_keypress_s(self, event): print "down %d m" % self.distance self.telloDown(self.distance) def on_keypress_a(self, event): print "ccw %d degree" % self.degree self.tello.rotate_ccw(self.degree) def on_keypress_d(self, event): print "cw %d m" % self.degree self.tello.rotate_cw(self.degree) def on_keypress_up(self, event): print "forward %d m" % self.distance self.telloMoveForward(self.distance) def on_keypress_down(self, event): print "backward %d m" % self.distance self.telloMoveBackward(self.distance) def on_keypress_left(self, event): print "left %d m" % self.distance self.telloMoveLeft(self.distance) def on_keypress_right(self, event): print "right %d m" % self.distance self.telloMoveRight(self.distance) def on_keypress_enter(self, event): if self.frame is not None: self.registerFace() self.tmp_f.focus_set() def onClose(self): """ set the stop event, cleanup the camera, and allow the rest of the quit process to continue """ print("[INFO] closing...") self.stopEvent.set() del self.tello self.root.quit()
class Generator(Frame): """calcul d'une vibration harmonique du type : e=a*sin(2*pi*f*t+p) scale_A : controleur d'amplitude """ def __init__(self, parent, name="X",color="red"): """ initialisation parent : un oscilloscope name : nom du signal """ Frame.__init__(self) self.configure(bd=1, relief="sunken", background = color) self.parent = parent self.name = name self.color = color self.scale_A = Scale(self, length=300, orient="horizontal", label=name + " Amplitude", showvalue=1, from_=0, to=10, tickinterval=1, command=self.update_signal) self.scale_P = Scale(self, length=300, orient="horizontal", label=name + " Phase", showvalue=1, from_=0, to=90, tickinterval=20, command=self.update_signal) self.scale_F = Scale(self, length=300, orient="horizontal", label=name + " Fréquence", showvalue=1, from_=0, to=100, tickinterval=10, command=self.update_signal) self.scale_A.pack(expand="yes", fill="both") self.scale_P.pack(expand="yes", fill="both") self.scale_F.pack(expand="yes", fill="both") def update_signal(self, event): """mise a jour de courbe si modifications (amplitude, frequence, phase).""" #print("Vibration.update_signal()") #print("Amplitude :", self.scale_A.get()) scaling=0.05 amp = scaling*self.scale_A.get() fre = scaling*self.scale_F.get() pha = scaling*self.scale_P.get() signal = self.generate_signal(a=amp, f=fre, p=pha) if not isinstance(self.parent, Tk): self.parent.set_signal(self.name, signal, self.color) return signal def generate_signal(self, a=1.0, f=2.0, p=0): """Calcul de l'elongation, amplitude, frequence et phase sur une periode.""" signal = [] samples = 100 for t in range(0, samples): samples = float(samples) e = a * sin((2*pi*f*(t/samples)) - p) signal.append((t/samples,e)) return signal def get_parameter(self): """ Récupère les valeurs des paramètres de la courbe et les renvoie sous forme d'un tuple """ return [str(self.scale_A.get()), str(self.scale_F.get()), str(self.scale_P.get())] def set_parameter(self, amp=1.0, freq=2.0, phase=0): """ Modifie les valeurs des paramètres de la courbe """ self.scale_A.set(amp) self.scale_F.set(freq) self.scale_P.set(phase)
from Tkinter import Tk,Scale,IntVar,DoubleVar def update_magnitude(event): global data x=int(event.widget.get()) print(x,type(x)) print(data.get(),data.get()) if __name__ == "__main__" : root = Tk() root.title("Oscilloscope v.1") data=DoubleVar() magnitude=Scale(root,variable=data, length=250,orient="horizontal", label="Magnitude",sliderlength=20, showvalue=0,from_=0,to=5,tickinterval=25) magnitude.pack() magnitude.bind("<B2-Motion>",update_magnitude) root.mainloop()
class Generator(Frame): """ Vibration harmonique du type : e=a*sin(2*pi*f*t+p) scale_A : controleur d'Amplitude scale_F : controleur de Frequence scale_P : controleur de Phase """ def __init__(self, parent, name="X"): """ Initialisation parent : un oscilloscope name : nom du signal """ Frame.__init__(self) self.configure(bd=1, relief="sunken") self.parent = parent self.name = name self.scale_A = Scale(self, length=100, orient="horizontal", label=name + " Amplitude", showvalue=1, from_=0, to=10, tickinterval=1, command=self.update_signal) self.scale_F = Scale(self, length=100, orient="horizontal", label=name + " Fréquence", showvalue=1, from_=0, to=10, tickinterval=1, command=self.update_signal) self.scale_P = Scale(self, length=100, orient="horizontal", label=name + " Phase", showvalue=1, from_=0, to=5, tickinterval=1, command=self.update_signal) self.scale_F.pack(expand="yes", fill="both") self.scale_A.pack(expand="yes", fill="both") self.scale_P.pack(expand="yes", fill="both") def update_signal(self, event): """ Mise a jour de signal si modifications (amplitude, frequence, phase) """ scaling = 0.05 amp = scaling * self.scale_A.get() freq = self.scale_F.get() phase = self.scale_P.get() signal = self.generate_signal(a=amp, f=freq, p=phase) if not isinstance(self.parent, Tk): self.parent.update_view(self.name, signal) return signal def generate_signal(self, a=1.0, f=2.0, p=0): """ Calcul de l'elongation : e=a*sin(2*pi*f*t+p) sur une periode a : amplitude f : frequence p : phase """ signal = [] samples = 1000 for t in range(0, samples): samples = float(samples) e = a * sin((2 * pi * f * (t / samples)) - p) signal.append((t / samples, e)) return signal