Example #1
0
class MyCheckBox(object):
    def __init__(self, parent, group, command, x=0, y=0):
        self.state = BooleanVar(False)
        self.object = Checkbutton(parent.container, var=self.state, command=command, width=0)
        self.group = group
        self.x = x
        self.y = y
        self.object.place(x=self.x, y=self.y)
        self.buf_state = self.object["state"]
def flag(i, com, xi, yi):
    """
    Function register click on a checkbutton and performs command
    :param i: flag number which corresponds to command number in list_cb
    :param com: command name
    :param xi: x coordinate of chk
    :param yi: y coordinate of chk
    """
    chk = Checkbutton(window1, variable=list_cb[i], command=com)
    chk.focus()
    chk.place(x=xi, y=yi)
    return
Example #3
0
class spi(Frame):
    def __init__(self, master):
        self.master = master
        self.CLKIn = 0
        self.DataIn = 0
        self.SSIn = 0

        self.cpol = 0
        self.cpha = 0

        self.decode_index = []
        self.decode_state1 = []
        self.decode_state2 = []
        self.decode_position = []
        self.decode_text = []

    def set_decode(self, channelStates):
        #self.master.withdraw()
        self.top = Toplevel(self.master)
        self.top.geometry("300x210")
        self.top.title("spi")
        self.top.grab_set()

        self.Datalab = Label(self.top, text="MISO/MOSI:")
        self.Datalab.place(x=70, y=20)

        self.CLKlab = Label(self.top, text="CLK:")
        self.CLKlab.place(x=70, y=50)

        self.SSlab = Label(self.top, text="SS:")
        self.SSlab.place(x=70, y=80)

        self.DataCombo = Combobox(self.top, state="readonly", width=8)
        self.DataCombo.place(x=150, y=20)

        self.CLKCombo = Combobox(self.top, state="readonly", width=8)
        self.CLKCombo.place(x=150, y=50)

        self.SSCombo = Combobox(self.top, state="readonly", width=8)
        self.SSCombo.place(x=150, y=80)

        clk_in_temp = 100
        data_in_temp = 100
        ss_in_temp = 100

        for i in range(0, len(channelStates)):
            if (channelStates[i] == 1 and i == self.CLKIn):
                clk_in_temp = i
            if (channelStates[i] == 1 and i == self.DataIn):
                data_in_temp = i
            if (channelStates[i] == 1 and i == self.SSIn):
                ss_in_temp = i

        for i in range(0, len(channelStates)):
            if (channelStates[i] == 1 and clk_in_temp == 100):
                clk_in_temp = i
            if (channelStates[i] == 1 and data_in_temp == 100):
                data_in_temp = i
            if (channelStates[i] == 1 and ss_in_temp == 100):
                ss_in_temp = i

        if (clk_in_temp == 100):
            clk_in_temp = 0
        if (data_in_temp == 100):
            data_in_temp = 0
        if (ss_in_temp == 100):
            ss_in_temp = 0

        self.CLKIn = clk_in_temp
        self.DataIn = data_in_temp
        self.SSIn = ss_in_temp

        self.DataCombo['values'] += (str(self.DataIn))
        self.CLKCombo['values'] += (str(self.CLKIn))
        self.SSCombo['values'] += (str(self.SSIn))
        for i in range(0, len(channelStates)):
            if (channelStates[i] == 1):
                if str(i) not in self.DataCombo['values']:
                    self.DataCombo['values'] += (str(i), )
                if str(i) not in self.CLKCombo['values']:
                    self.CLKCombo['values'] += (str(i), )
                if str(i) not in self.SSCombo['values']:
                    self.SSCombo['values'] += (str(i), )

        self.cpol_var = IntVar()
        self.CB1 = Checkbutton(self.top,
                               text='CPOL',
                               variable=self.cpol_var,
                               onvalue=1,
                               offvalue=0)  #
        self.CB1.place(x=150, y=110)
        self.cpol_var.set(self.cpol)

        self.cpha_var = IntVar()
        self.CB2 = Checkbutton(self.top,
                               text='CPHA',
                               variable=self.cpha_var,
                               onvalue=1,
                               offvalue=0)  #
        self.CB2.place(x=150, y=130)
        self.cpha_var.set(self.cpha)

        self.Button = Button(self.top,
                             text="OK",
                             height=2,
                             width=18,
                             command=self.OkCallBack)
        self.Button.place(x=80, y=155)
        self.CLKCombo.current(0)
        self.DataCombo.current(0)
        self.SSCombo.current(0)

        self.top.protocol('WM_DELETE_WINDOW', self.exit_handler)
        self.top.mainloop()

    def decode(self, results, max_index, frequence):
        print(results[self.DataIn][100:4])
        self.decode_index = []
        self.decode_state1 = []
        self.decode_state2 = []
        self.decode_index.append(0)
        self.decode_state1.append(1)
        self.decode_state2.append(0)
        self.bit_count = 0
        self.data = 0
        self.data_end_pos = 0
        self.decodeStrTmp = ""
        for i in range(1, max_index):

            if (results[self.SSIn][i - 1] == 1 and results[self.SSIn][i] == 0
                    and self.bit_count == 0):  #START
                self.add_point(i)

                self.decodeStrTmp += "St"
                self.decode_position.append(i -
                                            ((i - self.decode_index[-1]) / 2))
                self.decode_text.append(self.decodeStrTmp)
                self.decodeStrTmp = ""
                self.data = 0
                self.bit_count = 1
            elif (results[self.SSIn][i - 1] == 0
                  and results[self.SSIn][i] == 1):  #STOP
                self.decode_position.append(self.data_end_pos - (
                    (self.data_end_pos - self.decode_index[-1]) / 2))
                self.decodeStrTmp = str(hex(self.data))
                self.decode_text.append(self.decodeStrTmp)
                self.data = 0
                self.add_point(self.data_end_pos)  #data end position

                self.decode_position.append(i -
                                            ((i - self.decode_index[-1]) / 2))
                self.decodeStrTmp = "Sp"
                self.decode_text.append(self.decodeStrTmp)
                self.decodeStrTmp = ""
                self.add_point(i)
                self.bit_count = 0
            elif (self.cpol == self.cpha and self.bit_count > 0
                  and results[self.CLKIn][i] == 1
                  and results[self.CLKIn][i - 1] == 0):  #DATA
                self.data = (self.data << 1) & results[self.DataIn][i]
                self.bit_count += 1
            elif (self.cpol == self.cpha and self.bit_count > 0
                  and results[self.CLKIn][i] == 0
                  and results[self.CLKIn][i - 1] == 1):
                self.data = (self.data << 1) & results[self.DataIn][i]
                self.data_end_pos = i
            elif (self.cpol != self.cpha and self.bit_count > 0
                  and results[self.CLKIn][i] == 0
                  and results[self.CLKIn][i - 1] == 1):  #DATA
                self.data = (self.data << 1) & results[self.DataIn][i]
                self.bit_count += 1
            elif (self.cpol != self.cpha and self.bit_count > 0
                  and results[self.CLKIn][i] == 1
                  and results[self.CLKIn][i - 1] == 0):
                self.data = (self.data << 1) & results[self.DataIn][i]
                self.data_end_pos = i
            elif (self.bit_count >= 128 and results[self.CLKIn][i] == 0
                  and results[self.CLKIn][i - 1] == 1):
                self.bit_count = 1
                self.decode_position.append(i -
                                            ((i - self.decode_index[-1]) / 2))
                self.decodeStrTmp = str(hex(self.data))
                self.decode_text.append(self.decodeStrTmp)
                self.data = 0
                self.add_point(i)

    def OkCallBack(self):
        self.DataIn = int(self.DataCombo.get())
        self.CLKIn = int(self.CLKCombo.get())
        self.SSIn = int(self.SSCombo.get())
        self.cpol = int(self.cpol_var.get())
        self.cpha = int(self.cpha_var.get())
        self.exit_handler()

    def exit_handler(self):
        #self.master.deiconify()
        self.top.grab_release()
        self.top.destroy()

    def add_point(self, i):
        self.decode_index.append(i)
        self.decode_state1.append(self.decode_state1[-1])
        self.decode_state2.append(self.decode_state2[-1])
        self.decode_index.append(i + 0.5)
        self.decode_state1.append(1 - self.decode_state1[-1])
        self.decode_state2.append(1 - self.decode_state2[-1])
Example #4
0
#TODO : make entry for epochs

label = Label(text="epochs:")
label.place(x=100, y=250)

label.config(font=("Century Gothic", 10))
epochs_entry = Entry()

epochs_entry.place(x=400, y=250)
###############################################
#TODO : make entry To get Bais

var = IntVar()
bias_check = Checkbutton(window, text="Bais", variable=var)

bias_check.place(x=400, y=300)
#####################################################
#TODO : make entry for activation function

label = Label(text="activation function:")
label.place(x=100, y=350)

label.config(font=("Century Gothic", 10))
AF = ["sigmoid", "tanh"]
activationFunctionCombo = Combobox(window, values=AF, state='readonly')
activationFunctionCombo.current(0)
activationFunctionCombo.place(x=400, y=350)


######################################################
#TODO : Run button
Example #5
0
janela = Tk()
janela.geometry("500x300")
janela.title("Exercício 2")

chk_state = BooleanVar()
chk_state2 = BooleanVar()
chk_state3 = BooleanVar()
chk_state4 = BooleanVar()
chk_state.set(False)
chk_state2.set(False)
chk_state3.set(False)
chk_state4.set(False)

chk = Checkbutton(janela, text='Ar condicionado', var=chk_state)
chk.place(relx=0.58, rely=0.1)
chk2 = Checkbutton(janela, text='Direção hidráulica', var=chk_state2)
chk2.place(relx=0.58, rely=0.2)
chk3 = Checkbutton(janela, text='Rádio', var=chk_state3)
chk3.place(relx=0.58, rely=0.3)
chk4 = Checkbutton(janela, text='Airbag', var=chk_state4)
chk4.place(relx=0.58, rely=0.4)

marca = Label(janela, text='Marca:')
marca.place(relx=0.1, rely=0.1, anchor=CENTER)
modelo = Label(janela, text='Modelo:')
modelo.place(relx=0.1, rely=0.2, anchor=CENTER)
ano = Label(janela, text='Ano:')
ano.place(relx=0.1, rely=0.3, anchor=CENTER)
placa = Label(janela, text='Placa:')
placa.place(relx=0.1, rely=0.4, anchor=CENTER)
class LogicAnalyzer :
    def __init__(self,master) :
        self.master = master
        
        self.BLOCK_LEN = 2048 * 32

        self.RxTimerState = 1
        self.deviceIndex = -1
        self.dev = None
        self.rx_buffer = bytearray()
        
        self.timeout = 0;
        
        self.x  = np.arange(0, 30, 1)
        self.axis  = np.arange(25, 100, 1)
        self.z = [0] * 75
        
        self.index_max = 0
        self.results = []
        self.index = []
        for i in range(0,16):
            tempList = []
            self.results.append(tempList)
        
        self.startPosition = 0
        self.sampPitch = 1
        self.sampOnScreen = 30
        self.finishPosition = 0
        
        self.channelActiveMask = 0
        
        self.coreFrq = 300000000 #300MHz
        self.coreFrqPeriod = 1000000000/self.coreFrq
        self.sampFrq = 300000000.0
        self.AARate = 0;
        self.BBSamp = 0;
        self.HHTrigPos = 0;
        self.EEVolt = 0;
        
        self.decoder_instances = []
        self.dec_instance_state = []
        for i in range(0,8):
            inst_temp = i2c(self.master)
            self.decoder_instances.append(inst_temp)
            self.dec_instance_state.append("_")
        
        self.channel_count = 0
        self.channel_decode = [0]*16
        
        self.decode_count = 0
        self.decode_decode = [0]*8
        
        self.top1 = Frame(self.master, height = 500, width = 260, borderwidth=2,highlightbackground="gray" , highlightthickness=1)
        self.top1.pack(side="left", fill="both")
        self.top2 = Frame(self.master, height = 500, width = 500, borderwidth=2,highlightbackground="gray" , highlightthickness=1)
        self.top2.pack(side="right", fill="both")
        
        self.top_slider = Frame(self.top2, height = 5, width = 500)
        self.top_slider.pack(side="top", fill="x")
        
        self.plot_frame = Frame(self.top2) 
        self.plot_frame.pack(side="top", fill="both",expand = 1)
        
        self.right_slider = Frame(self.plot_frame)
        self.right_slider.pack(side="right", fill="y")
        
        self.AxisFrame = Frame(self.plot_frame, height = 5, width = 500)
        self.AxisFrame.pack(side="top")
        
        self.RSB1 = Button(self.right_slider, text = "+",height=1, width=4, command = self.zoomSliderP)
        self.RSB1.pack(side="top")
        
        self.w1 = Scale(self.right_slider, from_=1000, to=0,showvalue = 0,command = self.calcPosition)#command = self.calcPosition
        self.w1.set(0)
        self.w1.pack(side="top", fill="y",expand = 1)
        
        self.RSB2 = Button(self.right_slider, text = "-",height=1, width=4, command = self.zoomSliderM)
        self.RSB2.pack(side="top")
        
        self.w2 = Scale(self.top_slider, from_=0, to=100000, orient=HORIZONTAL, showvalue = 0,command = self.calcPosition) #command = self.calcPosition
        self.w2.set(0)

        self.SB1 = Button(self.top_slider, text = "<<<",height=1, width=3, command = self.shiftSliderMM)
        self.SB1.pack(side="left")
        self.SB2 = Button(self.top_slider, text = "<",height=1, width=3, command = self.shiftSliderM)
        self.SB2.pack(side="left")
        self.w2.pack(side="left", fill="both",expand=1)
        self.SB3 = Button(self.top_slider, text = ">>>",height=1, width=3, command = self.shiftSliderPP)
        self.SB3.pack(side="right")
        self.SB4 = Button(self.top_slider, text = ">",height=1, width=3, command = self.shiftSliderP)
        self.SB4.pack(side="right")
        
        self.AxisFig = plt.Figure(figsize=(25,2), dpi=100)
        self.AxisFig.set_figheight(0.25)
        self.AxisFig.subplots_adjust(left=-0.05, right=1.05, top=2, bottom=1)
        self.af = self.AxisFig.add_subplot(111)
        self.AxisFig.patch.set_facecolor('whitesmoke')
        self.af.axes.get_yaxis().set_visible(False)
        self.af.step(self.axis, self.z, where='post', label='post')
        self.af.set_frame_on(False)
        
        self.axVar = StringVar()
        self.axLab = Label(self.AxisFrame, textvariable=self.axVar,height = 1,width=2)
        self.axVar.set("sp")
        self.axLab.pack(side="left")
        
        self.AxCanvas = FigureCanvasTkAgg(self.AxisFig, self.AxisFrame)
        self.AxCanvas.get_tk_widget().pack(side = "left",pady=2)
        

        self.decode_frame = Frame(self.plot_frame) 
        self.decode_frame.pack(side="top", fill="both",expand = 0)
        self.channel_frame = Frame(self.plot_frame) 
        self.channel_frame.pack(side="top", fill="both",expand = 0)#<-----------------------------
        
        self.plot_frames = []
        for i in range(0,16):
            self.plotFrame = Frame(self.channel_frame)
            self.plot_frames.append(self.plotFrame)
        
        self.decode_frames = []
        for i in range(0,8):
            self.decodeFrame = Frame(self.decode_frame)
            self.decode_frames.append(self.decodeFrame)

        self.plot_figures = []
        self.plot_axes = []
        self.plot_canvases = []
        self.plot_labels = []
        self.plot_label_values = []
        for i in range(0,16):
            
            self.figure = plt.Figure(figsize=(25,2), dpi=150)
            self.plot_figures.append(self.figure)
            self.plot_figures[i].set_figheight(0.2)#<------------------------------------------------
            self.plot_figures[i].subplots_adjust(left=-0.05, right=1.05, top=1, bottom=0)
            self.plot_figures[i].patch.set_visible(False)
            
            self.ax = self.plot_figures[i].add_subplot(111)
            self.plot_axes.append(self.ax)
            self.canvas = FigureCanvasTkAgg(self.plot_figures[i], self.plot_frames[i])
            self.plot_canvases.append(self.canvas)
            
            self.insideVar = StringVar()
            self.plot_label_values.append(self.insideVar)
            self.plot_label_values[i].set(str(i))
            self.plotLabel = Label(self.plot_frames[i], textvariable=self.plot_label_values[i],height = 1,width=2)
            self.plot_labels.append(self.plotLabel)
            self.plot_labels[i].pack(side="left")
            
            self.plot_canvases[i].get_tk_widget().pack(side="right", fill="both", expand=1,pady=2)
        
        self.decode_figures = []
        self.decode_axes = []
        self.decode_canvases = []
        self.decode_labels = []
        self.decode_label_values = []
        for i in range(0,8):
            
            self.figure = plt.Figure(figsize=(25,2), dpi=100)
            self.decode_figures.append(self.figure)
            self.decode_figures[i].set_figheight(0.3)
            self.decode_figures[i].subplots_adjust(left=-0.05, right=1.05, top=1, bottom=0)
            self.decode_figures[i].patch.set_visible(False)
            
            self.ax = self.decode_figures[i].add_subplot(111)
            self.decode_axes.append(self.ax)
            self.canvas = FigureCanvasTkAgg(self.decode_figures[i], self.decode_frames[i])
            self.decode_canvases.append(self.canvas)
            
            self.insideVar = StringVar()
            self.decode_label_values.append(self.insideVar)
            self.decode_label_values[i].set(str(i+1))
            self.decodeLabel = Label(self.decode_frames[i], textvariable=self.decode_label_values[i],height = 1,width=2)
            self.decode_labels.append(self.decodeLabel)
            self.decode_labels[i].pack(side="left")
            
            self.decode_canvases[i].get_tk_widget().pack(side="right", fill="both", expand=1,pady=2)
        
        
        self.BStart = Button(self.top1, text = "Start",height=2, width=30, command = self.StartCallBack)
        self.BStart.place(x = 20,y = 10)
        
        self.L2var = StringVar()
        self.L2 = Label(self.top1, textvariable=self.L2var)
        self.L2var.set("Duration:")
        self.L2.place(x = 20,y = 70)
        
        self.STB1var = StringVar()
        self.STB1var.set("255")
        self.STB1 = Entry(self.top1, width=11,textvariable = self.STB1var)
        self.STB1.place(x = 85,y = 70)
        
        self.comboDuration = Combobox(self.top1, 
                                    values=[
                                            "samp", 
                                            "sec",
                                            "msec",
                                            "usec",
                                            "nsec"],
                                    state="readonly",
                                    width = 8)
        self.comboDuration.place(x = 170,y = 70)
        self.comboDuration.current(0)
        
        self.L3var = StringVar()
        self.L3 = Label(self.top1, textvariable = self.L3var)
        self.L3var.set("Samp. rate:")
        self.L3.place(x = 20,y = 90)
        
        self.STB2var = StringVar()
        self.STB2var.set("300")
        self.STB2 = Entry(self.top1, width=11,textvariable = self.STB2var)
        self.STB2.place(x = 85,y = 90)
        
        self.comboRate = Combobox(self.top1, 
                                    values=[
                                            "Hz", 
                                            "kHz",
                                            "MHz"],
                                    state="readonly",
                                    width = 8)
        self.comboRate.place(x = 170,y = 90)
        self.comboRate.current(2)
        
        self.L6var = StringVar()
        self.L6 = Label(self.top1, textvariable=self.L6var)
        self.L6var.set("Input threshold, V:")
        self.L6.place(x = 20,y = 110)
        
        self.STB3var = StringVar()
        self.STB3var.set("3")
        self.STB3 = Entry(self.top1, width=11,textvariable = self.STB3var)
        self.STB3.place(x = 170,y = 110)
        
        self.var1 = IntVar()
        self.CB1 = Checkbutton(self.top1, text='Trigger',variable=self.var1, onvalue=1, offvalue=0, command=self.TriggerCallBack) #
        self.CB1.place(x = 20,y = 145)
        
        self.L4var = StringVar()
        self.L4 = Label(self.top1, textvariable=self.L4var)
        self.L4var.set("Trigger type:")
        self.L4.place(x = 20,y = 165)
        
        self.comboTriggerT = Combobox(self.top1, 
                                    values=["Rising edge",
                                            "Falling edge",
                                            "High", 
                                            "Low"],
                                    state="disabled",
                                    width = 15)
        self.comboTriggerT.place(x = 125,y = 165)
        self.comboTriggerT.current(0)
        
        self.L5var = StringVar()
        self.L5 = Label(self.top1, textvariable=self.L5var)
        self.L5var.set("Trigger channel:")
        self.L5.place(x = 20,y = 185)
        
        self.comboTriggerCh = Combobox(self.top1, 
                                    values=["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15"],
                                    state="disabled",
                                    width = 15)
        self.comboTriggerCh.place(x = 125,y = 185)
        self.comboTriggerCh.current(0)

        self.channel_active_int = []
        for i in range(0,16):
            self.channel_active_int.append(0)
            
        self.decode_active_int = []
        for i in range(0,8):
            self.decode_active_int.append(0)
        
        self.L61var = StringVar()
        self.L61 = Label(self.top1, textvariable=self.L61var)
        self.L61var.set("Samp. before trig:")
        self.L61.place(x = 20,y = 205)
        
        self.STB31var = StringVar()
        self.STB31var.set("3")
        self.STB31 = Entry(self.top1, width=18,state="disabled",textvariable = self.STB31var)
        self.STB31.place(x = 125,y = 205)
        
        self.L7var = StringVar()
        self.L7 = Label(self.top1, textvariable=self.L7var)
        self.L7var.set("Channels:")
        self.L7.place(x = 20,y = 240)
        
        self.channel_active = []
        self.channel_ch_box = []
        for i in range(0,16):
            self.chAct = IntVar()
            self.channel_active.append(self.chAct)
            self.chActChB = Checkbutton(self.top1, text=str(i),variable=self.channel_active[i], onvalue=1, offvalue=0, command=self.RefreshCh)
            self.channel_ch_box.append(self.chActChB)
            self.channel_ch_box[i].place(x = 20+(i%4)*60,y = 260+(i//4)*20)
        
        self.L8var = StringVar()
        self.L8 = Label(self.top1, textvariable=self.L8var)
        self.L8var.set("Decoders:")
        self.L8.place(x = 20,y = 355)
        
        self.decode_cb = []
        self.decode_cb_var = []
        self.decode_combo = []
        self.decode_buttons = []
        for i in range(0,8):
            dec_cb = IntVar()
            self.decode_cb_var.append(dec_cb)
            decActChB = Checkbutton(self.top1, text=str(i+1),variable=self.decode_cb_var[i], onvalue=1, offvalue=0, command=self.ResetDecodes) #
            self.decode_cb.append(decActChB)
            self.decode_cb[i].place(x = 20,y = 375+(i*28))
            decodeCombo = Combobox(self.top1, values=["i2c"],state="disabled",width = 20)
            self.decode_combo.append(decodeCombo)
            self.decode_combo[i].place(x = 60,y = 375+(i*28))
            self.decode_combo[i].current(0)
            self.decode_combo[i].bind("<<ComboboxSelected>>", self.ComboUpdate)
            self.decodeButton = Button(self.top1, text = "set",height=1, width=3, state="disabled")
            self.decode_buttons.append(self.decodeButton)
            self.decode_buttons[i].place(x = 210,y = 372+(i*28))            
            self.decode_buttons[i].configure(command=lambda:self.decoder_instances[i].set_decode(self.channel_active_int))
        
        self.BDecode = Button(self.top1, text = "Decode",height=2, width=30, command = self.ResetDecodes)
        self.BDecode.place(x = 20,y = 600)
        
        self.BFill = Button(self.top1, text = "Fill",height=2, width=13, command = self.FillCallBack)
        self.BFill.place(x = 20,y = 650)
        
        self.BSort = Button(self.top1, text = "Sort",height=2, width=13, command = self.SortCallBack)
        self.BSort.place(x = 140,y = 650)
        
        for root, dirs, files in os.walk("."):
            for filename in files:
                if(filename[0:3]== "la_" and filename[-3:]== ".py"):
                    print(filename)
                    module_name = filename[3:len(filename)-3]
                    for i in range(0,8):
                        if module_name not in self.decode_combo[i]['values']:
                            self.decode_combo[i]['values'] += (module_name,)    
        
        
        self.drawDecodes([1,0,0,0,0,0,0,0],0)
        self.drawPlots([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],1,1)
        self.drawDecodes([0,0,0,0,0,0,0,0],0)
        
        
        self.master.protocol("WM_DELETE_WINDOW",self.exit_handler)
    
    def calcPosition(self,*args):
        sampOnScreenMin = 30
        sampOnScreenMax = 10000
        self.index_max = 0
        for i in range(0,16):
            if(self.index_max < len(self.results[i])):
               self.index_max = len(self.results[i])
        
        if (self.index_max > sampOnScreenMin and self.index_max < sampOnScreenMax):
            self.sampOnScreen = sampOnScreenMin + int(((self.index_max-sampOnScreenMin) / 1000) * (1000-self.w1.get()))
        elif (self.index_max > sampOnScreenMax):
            self.sampOnScreen = sampOnScreenMin + int(((sampOnScreenMax-sampOnScreenMin) / 1000) * (1000-self.w1.get()))
        else:
            self.sampOnScreen = self.index_max
            
        self.sampPitch = (self.sampOnScreen // 1000) +1#
        
        if (self.index_max > sampOnScreenMin):
            self.startPosition = int((self.index_max - self.sampOnScreen)/100000 * self.w2.get())
        else:
            self.startPosition = 0
        
        self.finishPosition = self.startPosition + self.sampOnScreen
        self.drawPlots(self.channel_active_int,0,0)
    
    def RefreshCh(self):
        for i in range(0,16):
            if(self.index_max < len(self.results[i])):
               self.index_max = len(self.results[i])
               
        for i in range(0,16):
            if(len(self.results[i])<self.index_max and self.channel_active[i].get() == 1):
                self.results[i] = [0]*self.index_max

        self.calcPosition()
        self.ResetPlots()
    
    def ResetPlots(self):
        self.channelActiveMask = 0
        self.channel_count = 0
        for i in range(0,16):
            self.channel_active_int[i] = self.channel_active[i].get()
            if(self.channel_active_int[i]==1):
                self.channel_count += 1
                self.channel_decode[i] = self.channel_count-1
        for i in range(0,16):
            self.channelActiveMask = (self.channelActiveMask << 1) | self.channel_active_int[15-i]
        print(self.channel_active_int)
        self.drawPlots(self.channel_active_int,1,0)

    def ResetDecodes(self):
        self.decodeActiveMask = 0
        self.decode_count = 0
        for i in range(0,8):
            self.decode_active_int[i] = self.decode_cb_var[i].get()
            if(self.decode_active_int[i]==1):
                self.decode_count += 1
                self.decode_decode[i] = self.decode_count-1
                self.decode_combo[i]["state"] = "readonly"
                self.decode_buttons[i]["state"] = "normal"
            else:
                self.decode_combo[i]["state"] = "disabled"
                self.decode_buttons[i]["state"] = "disabled"
        self.UpdateDecodeInstances()
        for i in range(0,8):
            if(self.decode_active_int[i] == 1):
                self.decoder_instances[i].decode(self.results,self.index_max,self.sampFrq)
        self.drawDecodes(self.decode_active_int,0)
                  
    def drawPlots(self,plot_state,refreshFlag,sortFlag):
        
        self.index = np.arange(0, self.index_max, 1)
        self.z = [0] * self.index_max
        
        self.af.clear()
        self.af.axes.get_yaxis().set_visible(False)
        self.af.step(self.index[self.startPosition:self.finishPosition:1], 
                     self.z[self.startPosition:self.finishPosition:1],
                                 where='post', label='post')
        self.af.set_frame_on(False)

        self.AxCanvas.draw()
        self.AxisFrame.pack(side="top")
        
        if(sortFlag == 1):
            for i in range(0,16): 
                self.plot_frames[i].pack_forget()
        
        for i in range(0,16):     
            if(refreshFlag == 1):
                self.plot_axes[i].clear()
                self.plot_figures[i].patch.set_visible(False)
            
            if(plot_state[i]==1):
                self.plot_axes[i].clear()
                self.plot_figures[i].patch.set_visible(False)
                self.plot_axes[i].step(self.index[self.startPosition:self.finishPosition:1], #self.sampPitch
                                                  self.results[i][self.startPosition:self.finishPosition:1], #self.sampPitch
                                                  where='post', label='post')
                self.plot_axes[i].set_ylim(-0.01,1.01)
                self.plot_axes[i].axis('off')

                self.plot_canvases[i].draw()
                self.plot_canvases[i].get_tk_widget().update_idletasks()
                if(refreshFlag == 1):
                    self.plot_frames[i].pack(side="top", fill="both", expand=1)
            elif(refreshFlag == 1):
                self.plot_frames[i].pack_forget()
        self.ResetDecodes()
    
    def drawDecodes(self,decode_state,sortFlag):
        if(sortFlag == 1):
            for i in range(0,8): 
                self.decode_frames[i].pack_forget()  
                
        for i in range(0,8):
            self.decode_axes[i].clear()
            self.decode_figures[i].patch.set_visible(False)
            
            if(decode_state[i]==1):
                self.decode_ind_temp = []
                self.decode_state1_temp = []
                self.decode_state2_temp = []
                
                if(len(self.decoder_instances[i].decode_index)>0):
                    for f in range(0,len(self.decoder_instances[i].decode_index)):
                        if(self.decoder_instances[i].decode_index[f] > self.startPosition+0.5 and self.decoder_instances[i].decode_index[f] < self.finishPosition-0.5):
                           self.decode_ind_temp.append(self.decoder_instances[i].decode_index[f])
                           self.decode_state1_temp.append(self.decoder_instances[i].decode_state1[f])
                           self.decode_state2_temp.append(self.decoder_instances[i].decode_state2[f])
                    
                if(len(self.decode_ind_temp)==0):
                    self.decode_ind_temp.append(self.startPosition)
                    self.decode_state1_temp.append(0)
                    self.decode_state2_temp.append(1)

                self.decode_ind_temp.insert(0,self.startPosition)
                self.decode_state1_temp.insert(0,self.decode_state1_temp[0])
                self.decode_state2_temp.insert(0,self.decode_state2_temp[0])
    
                self.decode_ind_temp.append(self.finishPosition)
                self.decode_state1_temp.append(self.decode_state1_temp[-1])
                self.decode_state2_temp.append(self.decode_state2_temp[-1])                
                
                self.decode_axes[i].plot(self.decode_ind_temp, self.decode_state1_temp, color='r')
                self.decode_axes[i].plot(self.decode_ind_temp, self.decode_state2_temp, color='r')
                self.decode_axes[i].set_ylim(-0.01,1.01)
                self.decode_axes[i].axis('off')
                for d in range(0,len(self.decoder_instances[i].decode_position)):
                    self.decode_axes[i].text(self.decoder_instances[i].decode_position[d],0.1,self.decoder_instances[i].decode_text[d], fontsize=10)
                self.decode_canvases[i].draw()
                self.decode_frames[i].pack(side="top", fill="both", expand=1)
            else:
                self.decode_frames[i].pack_forget()

    def TriggerCallBack(self):
        if(self.var1.get() == 1):
            self.comboTriggerCh["state"] = "readonly"
            self.comboTriggerT["state"] = "readonly"
            self.STB31["state"] = "normal"
        else:
            self.comboTriggerCh["state"] = "disabled"
            self.comboTriggerT["state"] = "disabled"
            #self.STB31var.set(3)
            self.STB31["state"] = "disabled"

    def ft_init(self):
        #Get the device list and save the index of logic analyzer into deviceIndex
        self.deviceList = ftd2xx.listDevices(0) # returns the list of ftdi devices S/Ns 
        self.deviceIndex = -1;
        self.status = -1;
        if self.deviceList : 
             print(len(self.deviceList), 'ftdi devices found')
             for x in range(0,len(self.deviceList)):
                 if ( "LogicAnalyzer" in str(ftd2xx.getDeviceInfoDetail(x)['description'])) :
                     print("Device %d details: "%x)
                     print('-------------------------------------------------')
                     print("Serial : " + str(ftd2xx.getDeviceInfoDetail(x)['serial']))
                     print("Type : "  + str(ftd2xx.getDeviceInfoDetail(x)['type']))
                     print("ID : " + str(ftd2xx.getDeviceInfoDetail(x)['id']))
                     print("Description : " + str(ftd2xx.getDeviceInfoDetail(x)['description']))
                     print('-------------------------------------------------')
                     
                     if self.deviceIndex < 0:
                         self.deviceIndex = x
                     break
        else:
             print("no ftdi devices connected")
     
    def connect(self):
        if self.deviceIndex >= 0 :
             print('Connecting to device with index %d'% self.deviceIndex)
             self.dev = ftd2xx.open(self.deviceIndex) #FT4HNA7Z
             self.status = 1
             time.sleep(0.1)
             self.dev.setBitMode(0x00, 0x40)
             
             print('Device connected')
       
        elif ftd2xx.listDevices(0):
             print("no FTDI devices to be connected")
             self.messagebox.showinfo(title=None, message="Logic Analyzer was not found")


    def disconnect(self):
        self.dev.close()
        print("Device disconnected")

    def timerHandler(self): 
        self.read()
        print("check if all data collected %d"%len(self.rx_buffer))
        print("needed %d"%(self.BBSamp-self.BBSamp*0.01))
        if (len(self.rx_buffer) < (self.BBSamp-self.BBSamp*0.01) and (self.timeout < 50 or self.var1.get() == 1)) :
            self.timeout += 1
            self.master.after(1, self.timerHandler)
        else:
            print("data collected") 
            self.disconnect()
            self.w1.set(0)
            self.w2.set(0)
            self.calcPosition()
            
    def send(self):
        
        print("Send data")
        self.tx_data =  "#>HH"
        self.tx_data =  "#$FF" + self.HHTrigPosStr 
        self.tx_data += "#$EE" + self.EEVoltStr
        self.tx_data += "#$AA" + self.AARateStr
        self.tx_data += "#$BB" + self.BBSampStr
        self.tx_data += "#$CC" + self.CCTrigStr
        self.tx_data += "#$DD" + self.DDMaskStr
        self.tx_data += "#>GG"
        self.tx_data = self.tx_data.upper()
        self.tx_data += self.tx_data
        for a in range(0,16):
            self.results[a] = []
        
        print(self.tx_data)        
        b=bytearray()
        b.extend(map(ord,self.tx_data))
        if len(self.tx_data)>0 :
            print("\r\nSending %d bytes:"%len(self.tx_data))
            print('-------------------------------------------------')
            print(self.tx_data)
            print('-------------------------------------------------')
            self.written = self.dev.write(self.tx_data)
        else :
            print("Please enter data into a top text field")
        #self.timer1.start()
        self.timeout = 0
        self.rx_buffer = bytearray()
        self.timerHandler()

    def read(self):
        rx_data = bytearray()

        while self.dev.getQueueStatus()>0 :
             rx_data = self.dev.read(self.dev.getQueueStatus())

        if len(rx_data)>0 :
            self.rx_buffer += rx_data
            print("\r\nReceived %d bytes:"%len(rx_data))
            print('-------------------------------------------------')
            self.timeout = 0 # reset timeout if some data received
            if(self.channel_count <= 8):
                for i in range(0,len(rx_data),1):
                    x = bytearray()
                    x.append(rx_data[i]);
                
                    if(self.channel_count <= 2):
                        for ind in range(0,16):
                            if(self.channel_active_int[ind] == 1):
                                self.results[ind].append((int(int.from_bytes(x, byteorder='big', signed=False)>>self.channel_decode[ind]+6)&1))
                                self.results[ind].append((int(int.from_bytes(x, byteorder='big', signed=False)>>self.channel_decode[ind]+4)&1))
                                self.results[ind].append((int(int.from_bytes(x, byteorder='big', signed=False)>>self.channel_decode[ind]+2)&1))
                                self.results[ind].append((int(int.from_bytes(x, byteorder='big', signed=False)>>self.channel_decode[ind])&1))
                    elif(self.channel_count <= 4):
                        for ind in range(0,16):
                            if(self.channel_active_int[ind] == 1):
                                self.results[ind].append((int(int.from_bytes(x, byteorder='big', signed=False)>>self.channel_decode[ind]+4)&1))
                                self.results[ind].append((int(int.from_bytes(x, byteorder='big', signed=False)>>self.channel_decode[ind])&1))
                    elif(self.channel_count <= 8):
                        for ind in range(0,16):
                            if(self.channel_active_int[ind] == 1):
                                self.results[ind].append((int(int.from_bytes(x, byteorder='big', signed=False)>>self.channel_decode[ind])&1))
            elif(self.channel_count > 8 and self.channel_count <= 16):
                for i in range(0,len(rx_data)//2,2):
                    for ind in range(0,16):
                        x = bytearray()
                        x.append(rx_data[i])
                        x.append(rx_data[i+1])
                        self.results[ind].append((int(int.from_bytes(x, byteorder='big', signed=False)>>ind)&1))

    def updSet(self):
        temp1 = 1
        
        ##AA DATA RATE
        if (self.comboRate.get() == "Hz"):
            temp1 = 1
        elif(self.comboRate.get() == "kHz"):
            temp1 = 1000    
        elif(self.comboRate.get() == "MHz"):
            temp1 = 1000000
        
        self.AARate = self.coreFrq // (float(self.STB2var.get())*temp1)-1
        if (self.AARate > 16777215):
            self.AARate = 16777215
        elif(self.AARate < 0):
            self.AARate = 0
        self.sampFrq = self.coreFrq / ((self.AARate+1)*temp1)
        self.STB2var.set(str(self.sampFrq))
        self.sampFrq = self.coreFrq / (self.AARate+1)
        
        AARateByte = hex(int(self.AARate))
        self.AARateStr = str(AARateByte)
        self.AARateStr = self.AARateStr[2:]
        for ind in range(0,6-len(self.AARateStr)):
            self.AARateStr = '0' + self.AARateStr
        print("AA(Frq) = %d"%self.AARate)
        print(self.AARateStr)
        
        ##BB DURATION
        if (self.comboDuration.get() == "samp"):
            self.BBSamp = float(self.STB1var.get()) // 1
            self.STB1var.set(str(int(self.BBSamp)))
        else:
            if (self.comboDuration.get() == "sec"):
                temp1 = 1000000000
            elif(self.comboDuration.get() == "msec"):
                temp1 = 1000000    
            elif(self.comboDuration.get() == "usec"):
                temp1 = 1000
            elif(self.comboDuration.get() == "nsec"):
                temp1 = 1
            self.BBSamp = (temp1 * float(self.STB1var.get())) // self.coreFrqPeriod
            self.BBSamp += 1
            
        if(self.channel_count>0 and self.channel_count<=2):
            self.BBSamp = self.BBSamp / 4
            print("2")
        elif(self.channel_count>2 and self.channel_count<=4):
            self.BBSamp = self.BBSamp / 2
            print("4")
        elif(self.channel_count>8):
            self.BBSamp = self.BBSamp * 2
            print("16")
        
        if (self.BBSamp > 16777215):
            self.BBSamp = 16777215
        elif(self.BBSamp < 0):
            self.BBSamp = 0

        BBSampByte = hex(int(self.BBSamp))
        self.BBSampStr = str(BBSampByte)
        self.BBSampStr = self.BBSampStr[2:]
        for ind in range(0,6-len(self.BBSampStr)): #fill most sign bits with 0
            self.BBSampStr = '0' + self.BBSampStr
        print("BB(Samp) = %d"%self.BBSamp)
        print(self.BBSampStr)
        
        #CC TRIGGER CH
        if (self.var1.get() == 1):
            if(self.comboTriggerT.get()=="Rising edge"):
                CCTrigTStr = '0'
            elif(self.comboTriggerT.get()=="Falling edge"):
                CCTrigTStr = '1'
            elif(self.comboTriggerT.get()=="High"):
                CCTrigTStr = '2'
            elif(self.comboTriggerT.get()=="Low"):
                CCTrigTStr = '3'
        else: 
            CCTrigTStr = 'F'
            
        CCTrigChByte = hex(int(self.comboTriggerCh.get()))
        CCTrigChStr = str(CCTrigChByte)    
        self.CCTrigStr = "0000" + CCTrigTStr + CCTrigChStr[2:]
        print("CC(TrigCh) = %d"%int(self.comboTriggerCh.get()))
        print(self.CCTrigStr)
        
        #HH TRIGGER POSITION
        self.HHTrigPos = int(self.STB31var.get())
        
        if(self.channel_count>0 and self.channel_count<=2):
            self.HHTrigPos = self.HHTrigPos // 8
            print("2")
        elif(self.channel_count>2 and self.channel_count<=4):
            self.HHTrigPos = self.HHTrigPos // 4
            print("4")
        elif(self.channel_count>4 and self.channel_count<=8):
            self.HHTrigPos = self.HHTrigPos // 2
            print("8")
        
        if (self.HHTrigPos > 64000):
            self.HHTrigPos = 64000
        elif(self.HHTrigPos < 0):
            self.HHTrigPos = 0
        
        HHTrigPosByte = hex(self.HHTrigPos)
        self.HHTrigPosStr = str(HHTrigPosByte)
        self.HHTrigPosStr = self.HHTrigPosStr[2:]
        for ind in range(0,6-len(self.HHTrigPosStr)):
            self.HHTrigPosStr = '0' + self.HHTrigPosStr
        print("лала(TrigPos) = %d"%self.HHTrigPos)
        print(self.HHTrigPosStr)
        
        
        #DD CH BITMAP
        DDMaskByte = hex(self.channelActiveMask)
        self.DDMaskStr = str(DDMaskByte)
        self.DDMaskStr = self.DDMaskStr[2:]
        for i in range(0,6-len(self.DDMaskStr)):
            self.DDMaskStr = '0' + self.DDMaskStr
        print("DD(Mask) = %d"%self.channelActiveMask)
        print(self.DDMaskStr)
        
        #EE VOLTAGE
        EEVoltFl = float(self.STB3var.get())
        if (EEVoltFl > 5):
            self.STB3var.set("5")
        if (EEVoltFl > 3.6):    
            EEVoltFl = 3.6
        elif (EEVoltFl < 0.6):
            self.STB3var.set("0.6")
            EEVoltFl = 0.6
        self.EEVolt = (EEVoltFl-0.6) * 65
        self.EEVolt = int(255 - self.EEVolt)
        
        EEVoltByte = hex(self.EEVolt)
        self.EEVoltStr = str(EEVoltByte)    
        self.EEVoltStr = "0000" + self.EEVoltStr[2:]
        
        print("EE(Volt) = %d"%self.EEVolt)
        print(self.EEVoltStr)
 
    def StartCallBack(self):
        self.updSet()
        self.ft_init()
        self.connect()
        self.send()
    
    def FillCallBack(self):
        self.decode_frame.pack_forget()
        self.channel_frame.pack_forget()
        if(self.BFill['text'] == "Fill"):
            self.BFill['text'] = "standart view"
            self.decode_frame.pack(side="top", fill="both",expand = 1)
            self.channel_frame.pack(side="top", fill="both",expand = 1)
        else:
            self.BFill['text'] = "Fill"
            self.decode_frame.pack(side="top", fill="both",expand = 0)
            self.channel_frame.pack(side="top", fill="both",expand = 0)
        
    def SortCallBack(self):
        self.drawDecodes(self.decode_active_int,1)
        self.drawPlots(self.channel_active_int,1,1)
                
    def ComboUpdate(self,event):
        self.UpdateDecodeInstances()
        
    def UpdateDecodeInstances(self):
        for i in range(0,8):
            if(self.dec_instance_state[i] != self.decode_combo[i].get() and self.decode_cb_var[i].get() == 1):
                self.dec_instance_state[i] = self.decode_combo[i].get()
                if(self.decode_combo[i].get() == "i2c"):
                    self.decoder_instances[i] = i2c(self.master)
                else:
                    filename = "la_" + self.decode_combo[i].get()
                    module = importlib.import_module(filename)
                    class_ = getattr(module, filename[3:])
                    self.decoder_instances[i] = class_(self.master)
                    
                self.decode_buttons[i].configure(command=lambda x=i :self.setDecode(x))
    
    def setDecode(self,ch):
        self.decoder_instances[ch].set_decode(self.channel_active_int)
        
    def zoomSliderP(self):
        temp = self.w1.get()
        temp += 1
        self.w1.set(temp)
    
    def zoomSliderM(self):
        temp = self.w1.get()
        temp -= 1
        self.w1.set(temp)
        
    def shiftSliderMM(self):
        temp1 = self.index_max/100000
        temp2 = int(self.sampOnScreen/temp1)
        temp = self.w2.get()
        temp -= temp2
        self.w2.set(temp)
    def shiftSliderM(self):
        temp1 = self.index_max/100000
        temp2 = int(self.sampOnScreen/temp1/10)
        temp = self.w2.get()
        temp -= temp2
        self.w2.set(temp)
    def shiftSliderP(self):
        temp1 = self.index_max/100000
        temp2 = int(self.sampOnScreen/temp1/10)
        temp = self.w2.get()
        temp += temp2
        self.w2.set(temp)
    def shiftSliderPP(self):
        temp1 = self.index_max/100000
        temp2 = int(self.sampOnScreen/temp1)
        temp = self.w2.get()
        temp += temp2
        self.w2.set(temp)
   
    def disconnectCallBack(self):
        self.disconnect()

    def sendCallBack(self):
        self.send()
    
    def exit_handler(self):
        #disconnect() #add checking if connected
        self.drawPlots([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],1,0)
        self.drawDecodes([0,0,0,0,0,0,0,0],0)
        print('Bye! :)')
        self.master.destroy()
class NewSliderWindow(Toplevel):
    def __init__(self, master=None):
        super().__init__(master=master)
        self.set_basic()

        self.bind('<Configure>', lambda e: self.place_buttons())

    def set_basic(self):
        self.overrideredirect(1)
        self.set_geometry()
        self.set_scale()
        self.set_checkButton()
        self.set_save_closeButtons()

    def set_geometry(self):
        self.width = 60
        parentX = self.master.winfo_rootx()
        parentY = self.master.winfo_rooty()
        parentHeight = self.master.winfo_height()
        parentWidth = self.master.winfo_width()
        self.geometry(
            '%dx%d+%d+%d' %
            (self.width, parentHeight, parentX + parentWidth + 2, parentY))

    def set_save_closeButtons(self):
        self.saveButton = Button(self,
                                 image=saveIcon,
                                 command=self.update_image)
        self.cancelButton = Button(self, image=closeIcon, command=self.cancel)

        self.saveButton.place(relx=0.1, rely=0.8, relwidth=0.4)
        self.cancelButton.place(relx=0.55, rely=0.8, relwidth=0.4)

        self.saveButton.place(
            relx=0.1,
            rely=1 - ((0.4 * self.width) / self.master.winfo_height()),
            relwidth=0.4)
        self.cancelButton.place(
            relx=0.55,
            rely=1 - ((0.4 * self.width) / self.master.winfo_height()),
            relwidth=0.4)

    def place_buttons(self):
        self.saveButton.place(
            relx=0.03,
            rely=1 - ((0.45 * self.width) / self.master.winfo_height()),
            relwidth=0.45)
        self.cancelButton.place(
            relx=0.52,
            rely=1 - ((0.45 * self.width) / self.master.winfo_height()),
            relwidth=0.45)

    def set_scale(self):
        self.var = IntVar()
        self.scale = Scale(self,
                           length=256,
                           from_=0,
                           to=255,
                           orient=VERTICAL,
                           command=lambda e: self.update_preview(
                               int(self.var.get()), self.cbVal.get()),
                           variable=self.var,
                           digits=1,
                           resolution=1)
        self.scale.place(relx=0, rely=0.1, relwidth=0.9, relheight=0.7)
        self.scale.set(0)

    def set_checkButton(self):
        self.cbVal = IntVar()
        self.cb = Checkbutton(self,
                              width=0,
                              variable=self.cbVal,
                              command=lambda: self.update_preview(
                                  int(self.var.get()), self.cbVal.get()))
        self.cb.place(relx=0.4, rely=0.78)
        self.cb.invoke()

    #UPDATE IMAGE ON SLIDER CHANGE
    def update_preview(self, thresholdVal, checkBoxVal):
        self.master.image.threshold(thresholdVal, checkBoxVal)
        self.master.update_visible_image()

    #UPDATE IMAGE ON "SAVE" AND UPDATE HISTOGRAM
    def update_image(self):
        self.master.update_visible_image()
        self.master.image.copy = copy.deepcopy(self.master.image.cv2Image)
        self.master.image.fill_histogram()
        self.master.update_child_windows()
        self.master.thresholdScaleWindow = None
        self.master.manager.new_state(self.master.image.cv2Image)
        self.destroy()

    #GO BACK TO ORIGINAL ON "CANCEL"
    def cancel(self):
        self.master.image.cv2Image = copy.deepcopy(self.master.image.copy)
        self.master.update_visible_image()
        self.master.image.fill_histogram()
        self.master.update_child_windows()
        self.master.thresholdScaleWindow = None
        self.destroy()
Example #8
0
File: UI.py Project: Greazy/nlp
entry_txt1.place(x=1000,y=675)
entry_txt2.place(x=1100,y=675)
entry_txt3.place(x=1200,y=675)

btn1.place(x=350,y=650)
btn2.place(x=350,y=680)
btn3.place(x=350,y=710)
btn4.place(x=600,y=650)
btn5.place(x=600,y=680)
btn6.place(x=600,y=710)
btn7.place(x=800,y=650)
btn8.place(x=800,y=680)
btn9.place(x=800,y=710)

btn_del.place(x=1000,y=710)

btn_open.place(x=1200,y=710)

btn_save.place(x=1200,y=690)

chk.place(x=200, y=653)

time_shower.place(x=200, y=670)
txt.place(x=1,y=1)





window.mainloop()
Example #9
0
styl.theme_use('clam')
styl.configure('.', background=_bgcolor)
styl.configure('.', foreground=_fgcolor)
styl.configure('.', sliderthickness='20')
styl.configure('.', font="TkDefaultFont")
styl.map('.', background=[('selected', _compcolor), ('active', _ana2color)])

Frame1 = Frame(root)
Frame1.place(relx=0.02, rely=0.02, relheight=0.27, relwidth=0.46)
Frame1.configure(relief=GROOVE)
Frame1.configure(borderwidth="2")
Frame1.configure(relief=GROOVE)
Frame1.configure(width=285)

Checkbutton1 = Checkbutton(Frame1)
Checkbutton1.place(relx=0.07, rely=0.43, relheight=0.22, relwidth=0.34)
Checkbutton1.configure(text='''Profile photo''')
Checkbutton1.configure(variable=check1)

Checkbutton3 = Checkbutton(Frame1)
Checkbutton3.place(relx=0.07, rely=0.7, relheight=0.22, relwidth=0.35)
Checkbutton3.configure(text='''Header photo''')
Checkbutton3.configure(variable=check2)

Label1 = Label(Frame1)
Label1.place(relx=0.04, rely=-0.04)
Label1.configure(text='''Upload''')

Button1 = Button(Frame1)
Button1.place(relx=0.74, rely=0.7, height=25, width=60)
Button1.configure(padding=(2, 0, 0, 0))
Example #10
0
class MainWindow:
    def __init__(self) -> None:
        self.Root = Tk()
        self.App = Frame(self.Root, padding=(5, 2))
        self.UpdatesFrame = LabelFrame(self.App, text='Обновление',
                                       borderwidth=2, relief='sunken', padding=(5, 2))
        self.upd_enabled = BooleanVar()  # Флаг обновлений
        self.upd_unit = StringVar()  # Единица измерения времени
        self.time_units = {Minutes: 'Минут', Hours: 'Часов',
                           Days: 'Дней', Weeks: 'Недель', Months: 'Месяцев'}
        self.size_units = {Bytes: 'Байт', KBytes: 'Кбайт', MBytes:'Мбайт',
                           GBytes:'Гбайт', TBytes:'Тбайт'}  # Список единиц измерения времени
        self.maxfsize = StringVar()  # Максимальный размер файла
        self.size_unit = StringVar()  # Единица измерения информации
        self.units_amount1 = StringVar()  # Количество единиц
        self.quar = BooleanVar()  # False - удалять, True - карантин
        self.quar_path = StringVar() # Расположение карантина
        self.rpt_enabled = BooleanVar()  # Флаг отправки отчета
        self.email = StringVar()  # Адрес отправки
        self.passwd = StringVar() # Пароль исходящего ящика
        self.rpt_unit = StringVar()  # Единица измерения времени
        self.units_amount2 = StringVar()  # Количество единиц

        self.Upd_Label1 = Label(self.UpdatesFrame, text='Проверять обновления антивирусных баз')
        self.Upd_Checkbutton1 = Checkbutton(self.UpdatesFrame, variable=self.upd_enabled)
        self.Upd_Label2 = Label(self.UpdatesFrame, text='Частота проверки:   каждые')
        self.Upd_Spinbox1 = Spinbox(self.UpdatesFrame, textvariable=self.units_amount1,
                                    from_=1, to=999999999, width=4)
        self.Upd_OptionMenu1 = OptionMenu(self.UpdatesFrame, self.upd_unit, *self.time_units.values())
        self.Upd_Button1 = Button(
            self.UpdatesFrame, text='Источники антивирусных сигнатур', command=EntryOptionsWindow('AV_SOURCES', self.Root).main)

        self.ScanFrame = LabelFrame(self.App, text='Сканирование',
                                    borderwidth=2, relief='sunken', padding=(5, 2))
        self.Scn_Label1 = Label(self.ScanFrame, text='Максимальный размер файла:')
        self.Scn_Spinbox1 = Spinbox(self.ScanFrame, textvariable=self.maxfsize,
                                    from_=0, to=999999999, width=8)

        self.Quar_Label = Label(self.ScanFrame, text='При обнаружении угрозы')
        self.Quar_RadButton1 = Radiobutton(self.ScanFrame, text='Удаление', variable=self.quar, value=False)
        self.Quar_RadButton2 = Radiobutton(self.ScanFrame, text='Карантин', variable=self.quar, value=True)

        self.Scn_OptionMenu1 = OptionMenu(self.ScanFrame, self.size_unit, *self.size_units.values())
        self.Scn_Edit_Targets = Button(self.ScanFrame, text='Цели сканирования', command=EntryOptionsWindow('SCAN_TARGETS', self.Root, select_path=True).main)
        self.Scn_Edit_Exceptions = Button(self.ScanFrame, text='Исключения', command=EntryOptionsWindow('SCAN_EXCLUDE', self.Root).main)
        self.Quar_Button1 = Button(self.ScanFrame, text='Расположение карантина',
                                   command=lambda: self.quar_path.set(filedialog.askdirectory()))

        self.ReportFrame = LabelFrame(self.App, text='Отправка отчета',
                                      borderwidth=2, relief='sunken', padding=(5, 2))

        self.Rpt_Label1 = Label(self.ReportFrame, text='Отправлять отчеты о сканировании')
        self.Rpt_Checkbutton1 = Checkbutton(self.ReportFrame, variable=self.rpt_enabled)
        self.Rpt_Label2 = Label(self.ReportFrame, text='Адрес отправки отчетов:')
        self.Rpt_Entry1 = Entry(self.ReportFrame, textvariable=self.email, width=32)
        self.Rpt_Label3 = Label(self.ReportFrame, text='Пароль:')
        self.Rpt_Entry2 = Entry(self.ReportFrame, textvariable=self.passwd, width=32, show='*')
        self.Rpt_Label4 = Label(self.ReportFrame, text='Частота:')
        self.Rpt_Spinbox1 = Spinbox(self.ReportFrame, textvariable=self.units_amount2,
                                    from_=1, to=999999999, width=4)
        self.Rpt_OptionMenu1 = OptionMenu(self.ReportFrame, self.rpt_unit, *self.time_units.values())
        self.Rpt_Button1 = Button(self.ReportFrame, text='Получатели', command=EntryOptionsWindow('SEND_TO', self.Root).main)

        self.Buttons = Frame(self.App, padding=(5, 2))
        self.Button1 = Button(self.Buttons, text='Готово', command=self.save_conf)
        self.Button2 = Button(self.Buttons, text='Отмена', command=self.Root.destroy)

    def main(self) -> None:
        self.upd_unit.set(self.time_units[type(UPDATE_FREQ)])
        self.units_amount1.set(UPDATE_FREQ.value)
        self.upd_enabled.set(CHECK_FOR_UPDATES)
        self.Upd_Checkbutton1.configure(command=(
            lambda: self.__change_state(
                self.upd_enabled, self.Upd_Label2, self.Upd_Spinbox1, self.Upd_OptionMenu1, self.Upd_Button1)
            and self.upd_enabled.set(not self.upd_enabled.get())))
        self.Rpt_Checkbutton1.configure(command=(
            lambda: self.__change_state(
                self.rpt_enabled, self.Rpt_Label2, self.Rpt_Entry1, self.Rpt_Label3, self.Rpt_Entry2,
                 self.Rpt_Label4, self. Rpt_Spinbox1, self.Rpt_OptionMenu1, self.Rpt_Button1)
                 and self.rpt_enabled.set(not self.rpt_enabled.get())))
        self.maxfsize.set(MAX_FILE_SIZE.value)
        self.size_unit.set(self.size_units[type(MAX_FILE_SIZE)])
        self.quar.set(REMOVE_THREATS)
        self.quar_path.set(QUARANTINE_PATH)
        self.rpt_enabled.set(SEND_SCAN_REPORTS)
        self.email.set(SEND_FROM)
        self.passwd.set(SEND_PASSWD)
        self.rpt_unit.set(self.time_units[type(SEND_FREQ)])
        self.units_amount2.set(SEND_FREQ.value)

        self.App.pack(fill='both', expand=True)
        center_win(self.Root, '500x500')
        self.Root.resizable(False, False)
        self.Root.title('CobraAV Configuration')

        self.UpdatesFrame.place(y=0, height=150, width=490)
        self.__change_state(self.upd_enabled, self.Upd_Label2,
                            self.Upd_Spinbox1, self.Upd_OptionMenu1)

        self.__change_state(self.rpt_enabled, self.Rpt_Label2, self.Rpt_Entry1, self.Rpt_Label3,
                            self.Rpt_Entry2, self.Rpt_Label4, self.Rpt_Spinbox1, self.Rpt_OptionMenu1, self.Rpt_Button1)

        self.Upd_Label1.place(relx=.01, rely=.05)  # Проверять обновления ?
        self.Upd_Checkbutton1.place(relx=.8, rely=.05)  # Да/Нет

        self.Upd_Label2.place(relx=.01, rely=.3)  # Частота проверки
        self.Upd_Spinbox1.place(relx=.55, rely=.3, width=60)  # Количество
        self.Upd_OptionMenu1.place(relx=.72, rely=.28)  # Единицы измерения
        self.Upd_Button1.place(relx=.01, rely=.65)  # Источники сигнатур

        self.ScanFrame.place(y=150, height=150, width=490)

        self.Scn_Label1.place(relx=.01, rely=.05)  # Максимальный размер файла
        self.Scn_Spinbox1.place(relx=.55, rely=.05, width=60)  # Количество

        self.Quar_Label.place(relx=.01, rely=.35)
        self.Quar_RadButton1.place(relx=.52, rely=.35)  # Переключатель на удаление угрозы
        self.Quar_RadButton2.place(relx=.72, rely=.35)  # Переключатель на добавление вкарантина угрозы
        self.Quar_Button1.place(relx=.56, rely=.65)  # Расположение карантина

        self.Scn_OptionMenu1.place(relx=.72, rely=.014)  # Единицы измерения
        self.Scn_Edit_Targets.place(relx=.01, rely=.65)  # Цели сканирования
        self.Scn_Edit_Exceptions.place(relx=.33, rely=.65)  # Исключения

        self.Rpt_Label1.place(relx=.01, rely=.05)  # Отправлять отчеты ?
        self.Rpt_Checkbutton1.place(relx=.8, rely=.05)  # Да/Нет

        self.ReportFrame.place(y=300, height=150, width=490)
        self.Rpt_Label2.place(relx=.01, rely=.35)  # Адрес отправки отчетов:
        self.Rpt_Entry1.place(relx=.35, rely=.35)  # Ввод адреса отправки отчетов
        self.Rpt_Label3.place(relx=.01, rely=.50) # Пароль:
        self.Rpt_Entry2.place(relx=.35, rely=.50) # Ввод пароля:
        self.Rpt_Label4.place(relx=.01, rely=.75)  # Частота отправки
        self.Rpt_Spinbox1.place(relx=.35, rely=.75, width=60)  # Количество
        self.Rpt_OptionMenu1.place(relx=.52, rely=.72)  # Единицы измерения
        self.Rpt_Button1.place(relx=.72, rely=.74) # Получатели

        self.Buttons.place(y=450, height=50, width=490)
        self.Button1.place(relx=.62, rely=.2) # Кнопка "Готово"
        self.Button2.place(relx=.82, rely=.2) # Кнопка "Отмена"

        self.Root.mainloop()

    @staticmethod
    def __change_state(state: BooleanVar, *args: Widget) -> None:
        for i in args:
            i.configure(state=('disabled', 'normal')[state.get()])

    def save_conf(self) -> None:
        size_units = {v: k for k, v in self.size_units.items()}
        time_units = {v: k for k, v in self.time_units.items()}

        def wrap_list(a: 'list[str]') -> str:
            return '[' + ', '.join(f"r'{i}'" for i in a) + ']'

        def wrap_cls(_unit: Variable, amount: Variable) -> str:
            unit = _unit.get()
            if unit in size_units:
                return size_units[unit].__name__ + f'({amount.get()})'
            elif unit in time_units:
                return time_units[unit].__name__ + f'({amount.get()})'
            else:
                raise NotImplementedError

        with open(CONF_PATH, 'w') as f:
            f.write(
                f"""from libunits import *

CHECK_FOR_UPDATES = {int(self.upd_enabled.get())}  # Check for updates
UPDATE_FREQ = {wrap_cls(self.upd_unit, self.units_amount1)}  # Check interval
MAX_FILE_SIZE = {wrap_cls(self.size_unit, self.maxfsize)}  # Max file size

# Antivirus database sources
AV_SOURCES = {wrap_list(AV_SOURCES)}

# Antivirus database path
DB_PATH = r'{DB_PATH}'

# On threat:
# 0 - quarantine
# 1 - remove
REMOVE_THREATS = {int(self.quar.get())}

# Directories to scan
SCAN_TARGETS = {wrap_list(SCAN_TARGETS)}

# Exclude from scanning
SCAN_EXCLUDE = {wrap_list(SCAN_EXCLUDE)}

# quarantine location
QUARANTINE_PATH = r'{self.quar_path.get() or QUARANTINE_PATH}'

# Send scan reports
SEND_SCAN_REPORTS = {int(self.rpt_enabled.get())}

# Scan reports frequency
SEND_FREQ = {wrap_cls(self.rpt_unit, self.units_amount2)}

# Send from this email
SEND_FROM = r'{self.email.get()}'

# Sender email password
SEND_PASSWD = r'{self.passwd.get()}'

# Send to these emails
SEND_TO = {wrap_list(SEND_TO)}
""")
        self.Root.destroy()
class NewTwoArgsWindow(Toplevel):
    images = {}

    def __init__(self, master=None):
        super().__init__(master=master)

        self.set_basic()
        self.set_widgets()

    def set_basic(self):
        self.minsize(200, 200)
        self.maxsize(200, 200)
        self.title("Operacje logiczne")
        self.imageWindow1, self.imageWindow2 = None, None
        self.operations = ["DODAJ", "ODEJMIJ", "ZMIESZAJ", "AND", "OR", "XOR"]

    def set_widgets(self):
        self.firstChoice = StringVar(self)
        self.secondChoice = StringVar(self)
        self.operationChoice = StringVar(self)

        self.firstImageList = OptionMenu(self, self.firstChoice)
        self.secondImageList = OptionMenu(self, self.secondChoice)
        self.operationList = OptionMenu(self, self.operationChoice)

        self.update_list()
        self.operationChoice.set(self.operations[0])
        for oper in self.operations:
            self.operationList['menu'].add_command(
                label=oper, command=lambda v=oper: self.operationChoice.set(v))

        self.cbVal = IntVar()
        self.cb = Checkbutton(self, width=0, variable=self.cbVal)

        self.saveButton = Button(self,
                                 image=saveIcon,
                                 command=self.update_image)
        self.cancelButton = Button(self, image=closeIcon, command=self.cancel)

        self.place_widgets()

    def update_image(self):
        for obj, name in NewTwoArgsWindow.images.items():
            if name == self.firstChoice.get():
                self.imageWindow1 = obj
                break
        for obj, name in NewTwoArgsWindow.images.items():
            if name == self.secondChoice.get():
                self.imageWindow2 = obj
                break

        outputImage = self.imageWindow1.image.two_args_operations(
            self.operationChoice.get(), self.imageWindow2.image)

        if self.cbVal:
            windowName = self.imageWindow1.name + " " + self.operationChoice.get(
            ) + " " + self.imageWindow2.name
            self.imageWindow1.create_another(self.master, None, windowName,
                                             ImageSaved(None, outputImage))
        else:
            self.imageWindow1.image.cv2Image = outputImage
            self.master.image.copy = copy.deepcopy(self.master.image.cv2Image)
            self.imageWindow1.image.fill_histogram()
            self.imageWindow1.manager.new_state(
                self.imageWindow1.image.cv2Image)
            self.imageWindow1.update_visible_image()
            self.imageWindow1.update_child_windows()
        self.cancel()

    def cancel(self):
        self.destroy()

    def update_list(self):
        if len(NewTwoArgsWindow.images) <= 0:
            self.cancel()
            return
        openFilesNames = list(NewTwoArgsWindow.images.values())
        self.firstChoice.set(openFilesNames[0])
        self.secondChoice.set(openFilesNames[0]) if len(
            NewTwoArgsWindow.images) == 1 else self.secondChoice.set(
                openFilesNames[1])

        self.firstImageList['menu'].delete(0, 'end')
        self.secondImageList['menu'].delete(0, 'end')

        for file in openFilesNames:
            self.firstImageList['menu'].add_command(
                label=file, command=lambda v=file: self.firstChoice.set(v))
            self.secondImageList['menu'].add_command(
                label=file, command=lambda v=file: self.secondChoice.set(v))

    def place_widgets(self):
        Label(self, text="Obraz1: ").place(relx=0.05, y=7)
        Label(self, text="Operacja: ").place(relx=0.05, y=42)
        Label(self, text="Obraz2: ").place(relx=0.05, y=77)
        Label(self, text="Obraz wynikowy").place(relx=0.05, y=102)
        Label(self, text="w nowym okienku?").place(relx=0.05, y=120)
        self.firstImageList.place(y=5, relx=0.35)
        self.operationList.place(y=40, relx=0.35)
        self.secondImageList.place(y=75, relx=0.35)

        self.cb.place(y=110, relx=0.7)
        self.cb.invoke()

        self.saveButton.place(width=40, height=40, x=50, y=150)
        self.cancelButton.place(width=40, height=40, x=110, y=150)
Example #12
0
class App_test(object):
    def __init__(self):
        self.win = Tk()
        self.win.title('12306火车票查询系统V2.6')
        self.win.geometry('860x400')
        self.creat_res()
        self.add_train_info()
        self.add_check_button()
        self.res_config()
        self.train_message = {}
        # self.get_train_args()
        self.win.mainloop()

    def creat_res(self):
        self.v = IntVar()  #车票查询
        self.v.set(True)
        self.temp = StringVar()  #开始站
        self.temp2 = StringVar()  #目的站
        self.start_mon = StringVar()  #出发月
        self.start_day = StringVar()  #出发日
        self.start_year = StringVar()  #出啊年
        self.E_startstation = Entry(self.win, textvariable=self.temp)
        self.E_endstation = Entry(self.win, textvariable=self.temp2)
        self.La_startstation = Label(self.win, text="出发站:")
        self.La_endstation = Label(self.win, text="目的站:")
        self.La_time = Label(self.win, text="请选择出发时间-年-月-日", fg="blue")
        self.B_search = Button(self.win, text="搜索")
        self.R_site = Radiobutton(self.win,
                                  text="车票查询",
                                  variable=self.v,
                                  value=True)
        self.R_price = Radiobutton(self.win,
                                   text="票价查询",
                                   variable=self.v,
                                   value=False)
        self.B_buy_tick = Button(self.win, text="购票")
        self.C_year = Combobox(self.win, textvariable=self.start_year)
        self.C_mon = Combobox(self.win, textvariable=self.start_mon)
        self.La_s = Label(self.win, text="--")
        self.C_day = Combobox(self.win, textvariable=self.start_day)
        self.S_move = Scrollbar(self.win)
        self.E_startstation.place(x=70, y=10, width=65, height=30)
        self.E_endstation.place(x=70, y=60, width=65, height=30)
        self.La_startstation.place(x=10, y=10, width=50, height=30)
        self.La_endstation.place(x=10, y=60, width=50, height=30)
        self.La_time.place(x=10, y=100, width=150, height=30)
        self.C_year.place(x=10, y=140, width=70, height=30)
        self.C_mon.place(x=100, y=140, width=50, height=30)
        self.C_day.place(x=100, y=180, width=50, height=30)
        self.La_s.place(x=80, y=140, width=20, height=30)
        self.B_search.place(x=10, y=180, width=50, height=30)
        self.S_move.place(x=834, y=40, width=30, height=350)
        self.B_buy_tick.place(x=10, y=260, width=80, height=40)
        self.R_site.place(x=10, y=230, width=70, height=30)
        self.R_price.place(x=90, y=230, width=70, height=30)

    def res_config(self):
        self.C_year.config(values=[x for x in range(2018, 2020)])
        self.C_mon.config(values=["{:02d}".format(x)
                                  for x in range(1, 13)])  #时间格式是2018-01-01
        self.C_day.config(values=["{:02d}".format(x) for x in range(1, 32)])
        self.B_search.config(command=self.search_train_message)
        self.S_move.config(command=self.tree.yview)
        self.tree.config(yscrollcommand=self.S_move.set)

    def add_train_info(self):
        lis_train = ["C" + str(x) for x in range(0, 15)]
        tuple_train = tuple(lis_train)
        self.tree = Treeview(self.win,
                             columns=tuple_train,
                             height=30,
                             show="headings")
        self.tree.place(x=168, y=40, width=670, height=350)
        train_info = [
            ' 车次 ', ' 出发/到达站', '出发/到达时间', '历时 ', '商/特座', '一等座', '二等座', '高软',
            '软卧', '动卧', '硬卧', '软座', '硬座', '无座', '其他'
        ]
        for i in range(0, len(lis_train)):
            self.tree.column(lis_train[i],
                             width=len(train_info[i]) * 11,
                             anchor='center')
            self.tree.heading(lis_train[i], text=train_info[i])

    def add_check_button(self):
        self.v1 = IntVar()
        self.v2 = IntVar()
        self.v3 = IntVar()
        self.v4 = IntVar()
        self.v5 = IntVar()
        self.v6 = IntVar()
        self.v7 = IntVar()
        self.v1.set("T")
        self.Check_total = Checkbutton(self.win,
                                       text="全部车次",
                                       variable=self.v1,
                                       onvalue='T')
        self.Check_total.place(x=168, y=7, width=80, height=30)
        self.Check_total = Checkbutton(self.win,
                                       text="G-高铁",
                                       variable=self.v2,
                                       onvalue='T')
        self.Check_total.place(x=258, y=7, width=70, height=30)
        self.Check_total = Checkbutton(self.win,
                                       text="D-动车",
                                       variable=self.v3,
                                       onvalue='T')
        self.Check_total.place(x=348, y=7, width=60, height=30)
        self.Check_total = Checkbutton(self.win,
                                       text="Z-直达",
                                       variable=self.v4,
                                       onvalue='T')
        self.Check_total.place(x=418, y=7, width=60, height=30)
        self.Check_total = Checkbutton(self.win,
                                       text="T-特快",
                                       variable=self.v5,
                                       onvalue='T')
        self.Check_total.place(x=488, y=7, width=60, height=30)
        self.Check_total = Checkbutton(self.win,
                                       text="K-快速",
                                       variable=self.v6,
                                       onvalue='T')
        self.Check_total.place(x=568, y=7, width=60, height=30)
        self.Check_total = Checkbutton(self.win,
                                       text="其他",
                                       variable=self.v7,
                                       onvalue='T')
        self.Check_total.place(x=648, y=7, width=60, height=30)

    def get_train_args(self):  #输出获得的日期,出发站代码,目的站代码
        date = self.start_year.get() + "-" + self.start_mon.get(
        ) + "-" + self.start_day.get()
        start_station = self.temp.get()
        end_station = self.temp2.get()
        start_station_str = ""
        end_station_str = ""
        count1, count2 = 0, 0
        with open("res/dict2.txt", mode='r', encoding='utf-8') as f:
            mes = f.readlines()
            for i in mes:
                d = json.loads(i)
                if start_station in d:
                    start_station_str = d[start_station]
                else:
                    count1 += 1
                if end_station in d:
                    end_station_str = d[end_station]
                else:
                    count2 += 1
            if count1 == len(mes) or count2 == len(mes):
                messagebox.showwarning(title="友情提示", message="无法找到车站数据")
        return date, start_station_str, end_station_str

    def is_leapyear(self):
        #先判断输入是否是日期,如果是日期执行方法体,
        a = self.C_year.get()
        b = self.C_mon.get()
        c = self.C_day.get()
        pa_year = '20[\d][\d]'  # 2018
        if re.compile(pa_year).findall(a) and b in [
                "{:02d}".format(x) for x in range(1, 13)
        ] and c in ["{:02d}".format(x) for x in range(1, 32)]:
            nowtime = time.localtime()
            now_time_sp = time.mktime(nowtime)
            start_time = a + "-" + b + "-" + c + " 23:59:29"  #"2018-08-09  23:59:29"
            start_timestrip = time.strptime(start_time, "%Y-%m-%d %H:%M:%S")
            start_times = time.mktime(start_timestrip)
            days = (start_times - now_time_sp) / 60 / 60 / 24
            print(days)
            print(a, b, c)
            if days > 29:
                messagebox.showerror(title="警告", message="大于30天无法获取数据")
            elif days < 0:
                messagebox.showerror(title="警告", message="小于1天无法获取数据")
            elif days > 0 and days < 30:
                if int(a) % 4 == 0 and int(a) % 100 != 0 or int(
                        a) % 400 == 0:  #如果是闰年
                    if (int(b) in (1, 3, 5, 7, 8, 10, 12) and int(c) > 31) or (
                        (int(b) in (4, 6, 9, 11)
                         and int(c) > 30)) or (int(b) == 2 and int(c) > 29):
                        messagebox.showerror(title="警告", message="你确定这个月有这一天么")
                else:
                    if (int(b) in (1, 3, 5, 8, 10, 12) and int(c) > 31) or (
                        (int(b) in (4, 6, 9, 11)
                         and int(c) > 30)) or (int(b) == 2 and int(c) > 28):
                        messagebox.showerror(title="警告", message="你确定这个月有这一天么")
        else:
            messagebox.showerror(title="警告", message="请输入正确格式的年:月:日")

    def manage_date(self):  #处理时间,闰年以及当天时间
        self.is_leapyear()

    def change_str(self, mm):
        for i, j in mm.items():
            with open("res/dict.txt", mode='r', encoding='utf-8') as f:
                mes = f.readlines()
                for s in mes:
                    d = json.loads(s)
                    if j[0] in d:
                        j[0] = d[j[0]]
                    if j[1] in d:
                        j[1] = d[j[1]]
        # print(self.new_train_message) #车次信息
        non_empty_str = ['']
        for m, n in mm.items():
            mm[m] = ['-' if x in non_empty_str else x for x in n]  # 替换''字符为'-'
        return mm

    def trans_train_dic(self):  #输出出发站-目的站-名字
        date, start_station, end_station = self.get_train_args()
        print(date, start_station, end_station)
        try:
            p = Pro_train(date, start_station, end_station)
            self.train_message = p.get_train_res()  # 获得车次信息字典 车次英文
            self.train_tick = p.get_tarin_ticket()  #获得票价信息
            # print(self.train_message) #车次信息
            self.new_train_message = self.train_message  #复制一份
            self.new_train_tick = self.train_tick
            self.new_train_message = self.change_str(self.new_train_message)
            self.new_train_tick = self.change_str(self.new_train_tick)
            return self.new_train_message, self.new_train_tick  # 中文字典
        except Exception as e:
            # messagebox.showerror(title="警告",message="无法解析数据,请重新选择")
            print("错误码:", e.args)

    def search_train_message(self):
        self.manage_date()  #处理日期-True-transe-view
        if self.v.get():
            self.view_list()
        else:
            self.view_price()

    def clear_tree(self):
        x = self.tree.get_children()
        for n in x:
            self.tree.delete(n)

    def view_list(self):  #显示到网格
        # 车次 出发/站 出发到达时间 历时 商务座31  一等座30 二等座29  高软20 软卧22 动卧 硬卧27 软座23 硬座28 无座25 其他21
        try:
            self.clear_tree()
            self.new_train_message, x = self.trans_train_dic()  #生成新车次字典
            for i, j in self.new_train_message.items():
                self.tree.insert("",
                                 "end",
                                 values=(i, j[0] + "->" + j[1],
                                         j[2] + "->" + j[3], j[4], j[5], j[6],
                                         j[7], j[8], j[9], j[10], j[11], j[12],
                                         j[13], j[14], j[15]))
        except Exception as e:
            # messagebox.showerror(title="警告",message="无法处理数据")
            print("错误:", e.args)

    def view_price(self):
        print("-------票价ok-------")
        try:
            self.clear_tree()
            y, self.new_train_tick = self.trans_train_dic()  #生成新车次字典
            for i, j in self.new_train_tick.items():
                self.tree.insert("",
                                 "end",
                                 values=(i, j[0] + "->" + j[1],
                                         j[2] + "->" + j[3], j[4], j[5], j[6],
                                         j[7], j[8], j[9], j[10], j[11], j[12],
                                         j[13], j[14], "-"))
        except Exception as e:
            # messagebox.showerror(title="警告",message="无法处理数据")
            print("错误:", e.args)
class HighlightCode():
	"""
	Created by yogesh singh and please follow my instagram page @dynamiccoding for more projects 
	Plese install pygments and pyperclip .
	.
	make sure to follow me on github as well .

	and give feedback and suggestions also .........
	"""
	def __init__(self,root):
		self.root = root

		self.check_line_on = BooleanVar()   

		self.code_text = ScrolledText(self.root,bd=4,relief=GROOVE)
		self.code_text.place(x=0,y=0,height=300,width=300)


		self.output_code = ScrolledText(self.root,bd=4,relief=GROOVE)
		self.output_code.place(x=300,y=0,height=300,width=300) 

		self.control_frame = Frame(self.root,bd=2,relief=GROOVE)
		self.control_frame.place(x=25,y=310,height=130,width=550)

		# ................ controls in control frames ...................

		self.languages = ['python','C','C++','java','php','C#']

		self.borders = ['dotted','dashed','solid','double','groove','ridge','inset','none','hidden']

		#self.border_width = ['2px','4px','6px','8px','10px','medium','thick']

		self.border_clrs = ['red','black','gray','white','green','yellow','pink','cyan','sky blue']

		self.styles = ['default', 'emacs', 'friendly', 'colorful', 'autumn', 'murphy', 
		 'monokai', 'perldoc', 'pastie', 'borland', 'trac', 'native', 'fruity', 'bw', 
		'vim', 'vs', 'tango', 'rrt', 'xcode', 'igor', 'paraiso-light', 'paraiso-dark', 'lovelace', 
		'algol', 'algol_nu', 'arduino', 'rainbow_dash', 'abap',
		 'solarized-dark', 'solarized-light', 'sas', 'stata', 'stata-light', 'stata-dark', 'inkpot']

		self.style_combo = Combobox(self.control_frame,width=20,values=self.styles,justify=CENTER)
		self.style_combo.set('Select Style')
		self.style_combo.place(x=10,y=5)

		self.border_combo = Combobox(self.control_frame,width=20,values=self.borders,justify=CENTER)
		self.border_combo.set('Select Border')
		self.border_combo.place(x=10,y=45)

		
		self.border_color_combo = Combobox(self.control_frame,width=20,values=self.border_clrs,justify=CENTER)
		self.border_color_combo.set('Border Color')
		self.border_color_combo.place(x=10,y=85)

		self.language_combo = Combobox(self.control_frame,width=15,values=self.languages,justify=CENTER)
		self.language_combo.set('python')
		self.language_combo.place(x=180,y=40)

		self.Line_no_check = Checkbutton(self.control_frame,text='Enable Line No.',onvalue=True,offvalue=False,
			variable=self.check_line_on)
		self.Line_no_check.place(x=180,y=9)

		


		highlight_btn = ttk.Button(self.control_frame,text='Highlight',command=self.highlight_code)
		highlight_btn.place(x=300,y=10)

		copy_edit_code = ttk.Button(self.control_frame,text='Copy Code',command=self.copy_code)
		copy_edit_code.place(x=300,y=50)

		clear_input_text = ttk.Button(self.control_frame,text='Clear Input Box',
			width=20,command=lambda:self.code_text.delete(0.0,END))
		clear_input_text.place(x=400,y=10)

		clear_output_text = ttk.Button(self.control_frame,text='Clear Output Box',
			width=20,command=lambda:self.output_code.delete(0.0,END))
		clear_output_text.place(x=400,y=50)


# ............... Functions  .....................

	def highlight_code(self):
		self.output_code.delete(0.0,END)
		lexer = self.language_combo.get()
		linenos = self.check_line_on.get()
		defstyles = 'overflow:auto;width:auto;'
		divstyles = self.get_default_style()
		style = self.style_combo.get()
		if style == 'Select Style':
			style ='default'

		code = self.code_text.get(0.0,END)

		formatter = HtmlFormatter(style=style,
                              linenos=False,
                              noclasses=True,
                              cssclass='',
                              cssstyles=defstyles + divstyles,
                              prestyles='margin: 0')
		html = highlight(code, get_lexer_by_name(lexer, stripall=True), formatter)
		if linenos:
			html = self.insert_line_numbers(html)
		html = "<!-- Syntax Highlighter by Dynamic Coding Code Highlighter -->" + html
		self.output_code.insert(0.0,html)

	def get_default_style(self):
		if self.border_color_combo.get() != 'Border Color'  or self.border_combo.get() != 'Select Border':
			if self.border_color_combo.get() == 'Border Color':
				self.border_color_combo.set('solid')
			if self.border_combo.get() == 'Select Border':
				self.border_combo.set('gray')

			return 'border:'+str(self.border_combo.get())+' '+str(self.border_color_combo.get())+';border-width:.1em .1em .1em .8em;padding:.2em .6em;'
		else:
			return 'border:solid gray;border-width:.1em .1em .1em .8em;padding:.2em .6em;'

	def insert_line_numbers(self,html):
	    match = re.search('(<pre[^>]*>)(.*)(</pre>)', html, re.DOTALL)
	    if not match: return html

	    pre_open = match.group(1)
	    pre = match.group(2)
	    pre_close = match.group(3)

	    html = html.replace(pre_close, '</pre></td></tr></table>')
	    numbers = range(1, pre.count('\n') + 1)
	    format = '%' + str(len(str(numbers[-1]))) + 'i'
	    lines = '\n'.join(format % i for i in numbers)
	    html = html.replace(pre_open, '<table><tr><td>' + pre_open + lines + '</pre></td><td>' + pre_open)
	    return html

	def copy_code(self):
		pc.copy(self.output_code.get(0.0,END))
		messagebox.showinfo("Highlighter says"," Code is copied to Clipboard")
Example #14
0
total = Entry(janela)
total.place(relx=0.65, rely=0.8, anchor=CENTER)
calculado = Entry(janela)
calculado.place(relx=0.65, rely=0.9, anchor=CENTER)

chuveiroEstado = BooleanVar()
chuveiroEstado.set(False)
lampadaEstado = BooleanVar()
lampadaEstado.set(False)
tomadaEstado = BooleanVar()
tomadaEstado.set(False)
arEstado = BooleanVar()
arEstado.set(False)

lampada = Checkbutton(janela, text='Lâmpadas', var=lampadaEstado)
lampada.place(relx=0.407, rely=0.55, anchor=CENTER)
chuveiro = Checkbutton(janela, text='Chuveiro', var=chuveiroEstado)
chuveiro.place(relx=0.4, rely=0.65, anchor=CENTER)
tomada = Checkbutton(janela, text='Tomadas', var=tomadaEstado)
tomada.place(relx=0.61, rely=0.55, anchor=CENTER)
ar = Checkbutton(janela, text='Ar Condicionado', var=arEstado)
ar.place(relx=0.655, rely=0.65, anchor=CENTER)

#FUNÇÕES


def aluno():
    mensagem = messagebox.showinfo(
        "Discente", "Nome: Milena Teixeira Correia\n\nR.A: 22.219.011-8")

class Application(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.pack(fill=BOTH, expand=1)
        self.initUI()
        self.setGeometry()
        self.component = NewComponent()

    def setGeometry(self):
        x = 300
        y = 100
        self.master.geometry("400x300+%d+%d" % (x, y))
        self.master.update()

    def initUI(self):
        #setup title
        self.master.title("Component Creator")
        self.style = Style()
        self.style.theme_use("clam")

        #indicator label
        self.labelName = Label(self, text="Component Name:")
        self.labelName.place(x=10, y=10)
        self.master.update()

        # create variable and namefield for input of component name
        sv = StringVar()
        sv.trace("w", lambda name, index, mode, sv=sv: self.nameChanged(sv))
        self.nameField = Entry(self, textvariable=sv)
        self.nameField.place(x=10 + self.labelName.winfo_width() + 10, y=10)
        self.master.update()

        # label for image name that will show img name for a given component name
        self.imgNameVar = StringVar()
        self.imgNameVar.set('imageName:')
        self.labelImageName = Label(self, textvariable=self.imgNameVar)
        self.labelImageName.place(x=10 + self.labelName.winfo_width() + 10,
                                  y=40)

        # checkbox for visible component or not
        self.cbVar = IntVar()
        self.cb = Checkbutton(self,
                              text="Visible Component",
                              variable=self.cbVar)
        self.cb.place(x=10, y=70)

        # dropdown list for category
        self.labelCategory = Label(self, text="Category:")
        self.labelCategory.place(x=10, y=110)
        self.master.update()

        acts = [
            'UserInterface', 'Layout', 'Media', 'Animation', 'Sensors',
            'Social', 'Storage', 'Connectivity', 'LegoMindStorms',
            'Experimental', 'Internal', 'Uninitialized'
        ]

        self.catBox = Combobox(self, values=acts)
        self.catBox.place(x=10 + self.labelCategory.winfo_width() + 10, y=110)

        # button to select icon image
        self.getImageButton = Button(self,
                                     text="Select icon",
                                     command=self.getImage)
        self.getImageButton.place(x=10, y=150)
        self.master.update()

        # explanation for resizing
        self.resizeVar = IntVar()
        self.resizeCB = Checkbutton(
            self,
            text="ON=Resize Image (Requires PIL)\nOFF=Provide 16x16 Image",
            variable=self.resizeVar)
        self.resizeCB.place(x=10 + self.getImageButton.winfo_width() + 10,
                            y=150)

        # create button
        self.createButton = Button(self, text="Create", command=self.create)
        self.createButton.place(x=10, y=230)

        #cancel button
        self.cancelButton = Button(self, text="Cancel", command=self.quit)
        self.cancelButton.place(x=200, y=230)

    # open file picker for selecting an icon
    def getImage(self):
        ftypes = [('All Picture Files', ('*.jpg', '*.png', '*.jpeg', '*.bmp')),
                  ('All files', '*')]
        self.component.imgFile = askopenfilename(filetypes=ftypes,
                                                 title="Select an Icon file")

    # update component name and image name for component by lowercasing first letter
    def nameChanged(self, sv):
        s = sv.get()
        self.component.compName = s
        self.component.compImgName = s[:1].lower() + s[1:] if s else ''
        self.imgNameVar.set('imageName: %s' % self.component.compImgName)

    # tries to create component
    def create(self):
        # sets parameters for new component based on input values
        self.component.visibleComponent = bool(self.cbVar.get())
        self.component.resizeImage = bool(self.resizeVar.get())
        self.component.category = self.catBox.get().upper()
        self.component.compName = self.nameField.get()

        try:
            # check if component already exists
            try:
                open(
                    '../../components/src/com/google/appinentor/components/runtime/%s.java',
                    'r')
                messagebox.showerror(
                    "Duplicate Component",
                    "%s already exists" % self.component.compName)
            # if doesnt exist will raise error
            except IOError:
                # check for name input
                if not self.component.compImgName:
                    messagebox.showerror("Missing Name",
                                         "Please enter component name")
                    return

                #check for category selection
                if not self.component.category:
                    messagebox.showerror("Missing Category",
                                         "Please select a category")
                    return

                # check if selected an icon
                if not self.component.imgFile:
                    messagebox.showerror("Missing Icon",
                                         "Please select an icon image")
                    return

                # copy image file to folder, can get error if user checked resize and doest have PIL installed
                try:
                    self.component.copyImageToFolder()
                except ImportError as e:
                    messagebox.showerror(
                        "Unable to import PIL",
                        "Please install PIL or unselect checkbox")
                    return

                # add references to the image file, can get error if component already exists
                try:
                    self.component.addImageReference()
                except DuplicateError as e:
                    messagebox.showerror(
                        "Duplicate Component",
                        "%s already exists" % self.component.compName)
                    return

                # will create mock component if is visible and add references to SimpleComponentDescriptor
                self.component.createMockComponent()

                # will create the actual component file
                self.component.createComponent()

                messagebox.showinfo('Success',
                                    'Component created successfully')

        # if could not open some file for writing
        except Exception as e:
            messagebox.showerror("Exception", str(e))
Example #16
0
class App_test(object):
    def __init__(self, master, fuc):
        self.win = master
        self.win.title('12306火车票查询系统V2.6')
        curWidth = self.win.winfo_width()
        curHeight = self.win.winfo_height()
        scnWidth, scnHeight = self.win.maxsize()
        tmpcnf = '1130x600+500+300'  # % ((scnWidth - curWidth) / 2, (scnHeight - curHeight) / 2)
        self.win.geometry(tmpcnf)
        self.creat_res()
        self.add_train_info()
        self.add_check_button()
        self.res_config(fuc)
        self.set_combox_defaut()
        self.train_message = {}

    # self.get_train_args()
    # self.win.mainloop()

    def creat_res(self):
        self.v = IntVar()  # 车票查询
        self.v.set(True)
        self.temp = StringVar()  # 开始站
        self.temp2 = StringVar()  # 目的站
        self.start_mon = StringVar()  # 出发月
        self.start_day = StringVar()  # 出发日
        self.start_year = StringVar()  # 出啊年
        self.La_start_end = Label(self.win, text="请输入出发地和目的地", fg="blue")
        self.E_startstation = Entry(self.win, textvariable=self.temp)
        self.E_endstation = Entry(self.win, textvariable=self.temp2)
        self.La_startstation = Label(self.win, text="出发站:")
        self.La_endstation = Label(self.win, text="目的站:")
        self.La_time = Label(self.win, text="请选择出发时间-年-月-日", fg="blue")
        self.B_search = Button(self.win, text="搜索")
        self.R_site = Radiobutton(self.win,
                                  text="车票查询",
                                  variable=self.v,
                                  value=True)
        self.R_price = Radiobutton(self.win,
                                   text="票价查询",
                                   variable=self.v,
                                   value=False)
        self.B_buy_tick = Button(self.win, text="购票")
        self.C_year = Combobox(self.win, textvariable=self.start_year)
        self.La_s = Label(self.win, text="--")
        self.C_mon = Combobox(self.win, textvariable=self.start_mon)
        self.La_s1 = Label(self.win, text="--")
        self.C_day = Combobox(self.win, textvariable=self.start_day)
        # 滚动条
        self.S_move = Scrollbar(self.win)
        self.La_start_end.place(x=10, y=10, width=150, height=30)
        self.E_startstation.place(x=70, y=50, width=145, height=30)
        self.E_startstation.insert(10, "杭州东")
        self.E_endstation.place(x=70, y=100, width=145, height=30)
        self.E_endstation.insert(10, "南京南")
        self.La_startstation.place(x=10, y=50, width=50, height=30)
        self.La_endstation.place(x=10, y=100, width=50, height=30)
        self.La_time.place(x=0, y=140, width=190, height=30)
        self.C_year.place(x=10, y=180, width=70, height=30)
        self.La_s.place(x=80, y=180, width=20, height=30)
        self.C_mon.place(x=100, y=180, width=50, height=30)
        self.La_s1.place(x=150, y=180, width=20, height=30)
        self.C_day.place(x=170, y=180, width=50, height=30)
        self.B_search.place(x=10, y=220, width=80, height=40)
        self.S_move.place(x=1100, y=40, width=30, height=550)
        self.B_buy_tick.place(x=10, y=310, width=80, height=40)
        self.R_site.place(x=10, y=270, width=90, height=30)
        self.R_price.place(x=100, y=270, width=90, height=30)

    def res_config(self, fuc):
        localTime = time.localtime(int(time.time()))
        # 获取今年的年份
        startTime = int(time.strftime("%Y", localTime))  # 2018
        self.C_year.config(
            values=[x for x in range(startTime, startTime + 10)])
        self.C_mon.config(values=["{:02d}".format(x)
                                  for x in range(1, 13)])  # 时间格式是2018-01-01
        self.C_day.config(values=["{:02d}".format(x) for x in range(1, 32)])
        self.B_search.config(command=fuc)
        self.S_move.config(command=self.tree.yview)
        self.tree.config(yscrollcommand=self.S_move.set)

    def add_train_info(self):
        lis_train = ["C" + str(x) for x in range(0, 15)]
        tuple_train = tuple(lis_train)
        self.tree = Treeview(self.win,
                             columns=tuple_train,
                             height=30,
                             show="headings")
        self.tree.place(x=228, y=40, width=870, height=550)
        train_info = [
            ' 车次 ', ' 出发/到达站', '出发/到达时间', '历时 ', '商/特座', '一等座', '二等座', '高软',
            '软卧', '动卧', '硬卧', '软座', '硬座', '无座', '其他'
        ]
        for i in range(0, len(lis_train)):
            self.tree.column(lis_train[i],
                             width=len(train_info[i]) * 11,
                             anchor='center')
            self.tree.heading(lis_train[i], text=train_info[i])

    def add_check_button(self):
        self.v1 = IntVar()
        self.v2 = IntVar()
        self.v3 = IntVar()
        self.v4 = IntVar()
        self.v5 = IntVar()
        self.v6 = IntVar()
        self.v7 = IntVar()
        self.v1.set("T")
        self.Check_total = Checkbutton(self.win,
                                       text="全部车次",
                                       variable=self.v1,
                                       onvalue='T')
        self.Check_total.place(x=228, y=7, width=90, height=30)
        self.Check_total = Checkbutton(self.win,
                                       text="G-高铁",
                                       variable=self.v2,
                                       onvalue='T')
        self.Check_total.place(x=318, y=7, width=70, height=30)
        self.Check_total = Checkbutton(self.win,
                                       text="D-动车",
                                       variable=self.v3,
                                       onvalue='T')
        self.Check_total.place(x=398, y=7, width=70, height=30)
        self.Check_total = Checkbutton(self.win,
                                       text="Z-直达",
                                       variable=self.v4,
                                       onvalue='T')
        self.Check_total.place(x=478, y=7, width=70, height=30)
        self.Check_total = Checkbutton(self.win,
                                       text="T-特快",
                                       variable=self.v5,
                                       onvalue='T')
        self.Check_total.place(x=558, y=7, width=70, height=30)
        self.Check_total = Checkbutton(self.win,
                                       text="K-快速",
                                       variable=self.v6,
                                       onvalue='T')
        self.Check_total.place(x=638, y=7, width=70, height=30)
        self.Check_total = Checkbutton(self.win,
                                       text="其他",
                                       variable=self.v7,
                                       onvalue='T')
        self.Check_total.place(x=718, y=7, width=70, height=30)

    # 设置下拉框默认值
    def set_combox_defaut(self):
        localTime = time.localtime(int(time.time()))
        mon = int(time.strftime("%m", localTime))
        day = int(time.strftime("%d", localTime))
        self.C_year.current(0)
        self.C_mon.current(mon - 1)
        self.C_day.current(day - 1)
Example #17
0
    def initUI(self):
        # define dialog box properties
        self.parent.title("Duokan Footnote Linker")
        self.pack(fill=BOTH, expand=1)

        # get preferences
        prefs = self.bk.getPrefs()

        # info
        infoLabel = Label(self, text="Additional compatibility: ")
        infoLabel.place(x=25, y=10)

        # compatibility check
        self.kindle = IntVar()
        # if 'kindle' in prefs:
        #     self.kindle.set(prefs['kindle'])
        # else:
        #     self.kindle.set(1)
        self.kindle.set(1)
        kindleCheck = Checkbutton(self, text="Kindle", variable=self.kindle)
        kindleCheck.place(x=40, y=30)

        self.ibooks = IntVar()
        # if 'ibooks' in prefs:
        #     self.ibooks.set(prefs['ibooks'])
        # else:
        #     self.ibooks.set(1)
        self.ibooks.set(1)
        ibooksCheck = Checkbutton(self,
                                  text="iBooks(macOS only)",
                                  variable=self.ibooks)
        ibooksCheck.place(x=150, y=30)

        # disable compatibility check temporarily
        # kindleCheck.config(state=tk.DISABLED)
        # ibooksCheck.config(state=tk.DISABLED)

        # footnote id prefix
        anchorIDLabel = Label(self, text="Anchor ID prefix: ")
        anchorIDLabel.place(x=25, y=60)
        self.anchorid = StringVar(None)
        if 'anchorid' in prefs:
            self.anchorid.set(prefs['anchorid'])
        else:
            self.anchorid.set('fnanchor-')
        anchorIDEntry = Entry(self, textvariable=self.anchorid)
        anchorIDEntry.place(x=150, y=60, width=85)

        # footnote definition id
        fndefIDLabel = Label(self, text="Definition ID prefix: ")
        fndefIDLabel.place(x=25, y=85)
        self.fndefid = StringVar(None)
        if 'fndefid' in prefs:
            self.fndefid.set(prefs['fndefid'])
        else:
            self.fndefid.set('fndef-')
        fndefIDEntry = Entry(self, textvariable=self.fndefid)
        fndefIDEntry.place(x=150, y=85, width=85)

        # backlink class
        backlinkLabel = Label(self, text="Backlink class: ")
        backlinkLabel.place(x=25, y=110)
        self.backlink = StringVar(None)
        if 'backlink' in prefs:
            self.backlink.set(prefs['backlink'])
        else:
            self.backlink.set('fnsymbol')
        backlinkEntry = Entry(self, textvariable=self.backlink)
        backlinkEntry.place(x=150, y=110, width=85)

        # Notes source location
        self.separate = IntVar()
        separateSourceCheck = Checkbutton(self,
                                          text="Footnote file: ",
                                          variable=self.separate)
        separateSourceCheck.place(x=5, y=135)

        self.notesource = StringVar()
        opf_guide_items = {}
        for ref_type, title, href in self.bk.getguide():
            opf_guide_items[ref_type] = href
        # look for notes guide item
        if 'notes' in opf_guide_items:
            print(
                'Separate note source found from OPF guide according to semantics.'
            )
            self.notesource.set(opf_guide_items['notes'])
            self.separate.set(1)
        noteSourceEntry = Entry(self, textvariable=self.notesource)
        noteSourceEntry.place(x=150, y=135, width=150)

        # OK and Cancel buttons
        cancelButton = Button(self, text="Cancel", command=self.quit)
        cancelButton.place(x=25, y=165)
        okButton = Button(self, text="OK", command=self.savevalues)
        okButton.place(x=150, y=165)
Example #18
0
class uart(Frame) :
    def __init__(self,master):
        self.master = master
        self.dataPin = 0
        self.baudRate = 9600
        self.parity = 0
        
        self.PusleWidth = 1.0
        
        self.decode_index  = []
        self.decode_state1 = []
        self.decode_state2 = []
        self.decode_position = []
        self.decode_text     = []
        
    def set_decode(self,channelStates):
        #self.master.withdraw()
        self.top = Toplevel(self.master)
        self.top.geometry("300x160")
        self.top.title("uart") 
        self.top.grab_set()
        
        self.datalab = Label(self.top, text="data pin:")
        self.datalab.place(x = 80,y = 20)
        
        self.baudlab = Label(self.top, text="baud rate:")
        self.baudlab.place(x = 80,y = 50)
        
        self.dataCombo = Combobox(self.top, state="readonly",width = 8)
        self.dataCombo.place(x = 140,y = 20)
        #self.SdaCombo.current(0)
        
        self.BaudVar = StringVar()
        self.BaudVar.set(str(self.baudRate))
        self.BaudEntry = Entry(self.top, width=11,textvariable = self.BaudVar)
        self.BaudEntry.place(x = 140,y = 50)
        
        data_in_temp = 100
        for i in range(0,len(channelStates)):
            if(channelStates[i] == 1 and i == self.dataPin):
                data_in_temp = i
                
        for i in range(0,len(channelStates)):
            if(channelStates[i] == 1 and data_in_temp == 100):
                data_in_temp = i

        if (data_in_temp == 100):
            data_in_temp = 0
        
        self.dataPin = data_in_temp
        
        self.dataCombo['values'] += (str(self.dataPin))
        for i in range(0,len(channelStates)):
            if (channelStates[i] == 1):
                if str(i) not in self.dataCombo['values']:
                    self.dataCombo['values'] += (str(i),)
        
        self.parity_var = IntVar()
        self.CB1 = Checkbutton(self.top, 
                               text='Parity bit',
                               variable=self.parity_var, 
                               onvalue=1, 
                               offvalue=0) #
        self.CB1.place(x = 140,y = 80)
        self.parity_var.set(self.parity)        
        
        self.Button = Button(self.top, 
                             text = "OK",
                             height=2, 
                             width=18, 
                             command = self.OkCallBack)
        self.Button.place(x = 80,y = 110)
        self.dataCombo.current(0)
        
        self.top.protocol('WM_DELETE_WINDOW', self.exit_handler)
        self.top.mainloop()
    
    def decode(self,results,max_index,frq):
        self.decode_index =  []
        self.decode_state1 =  []
        self.decode_state2 =  []
        self.decode_position = []
        self.decode_text = []
        self.decode_index.append(0)
        self.decode_state1.append(1)
        self.decode_state2.append(0)
        
        self.bit_count = 0
        self.data = 0
        self.decodeStrTmp = ""
        
        self.PulseWidth = frq / self.baudRate
        
        i = 0
        while i < max_index:
            if (results[self.dataPin][i-1]==1 and results[self.dataPin][i]==0):#START
                offsetStart = int(round(self.PulseWidth))
                offset8 = int(round(self.PulseWidth * 8 + self.PulseWidth/2))  
                
                
                self.add_point(i)
                self.decode_position.append(i+(self.PulseWidth/5))
                self.decode_text.append("St")
                
                offsetDecode = (offset8 - offsetStart)//2
                
                self.data = 0
                for d in range(0,8):
                    self.data = self.data>>1
                    offset = int(round(self.PulseWidth * (d+1) + self.PulseWidth/2))
                    self.data += results[self.dataPin][i+offset] * 128
                
                self.add_point(i+offsetStart)
                self.decode_position.append(i+offsetDecode)
                self.decode_text.append(str(hex(self.data)))
                
                if(self.parity == 0):
                    offsetStop = int(round(self.PulseWidth * 9))
                    self.add_point(i+offsetStop)
                    self.decode_position.append(i+offsetStop+ (self.PulseWidth/5))
                    self.decode_text.append("Sp")
                else:
                    offsetParity = int(round(self.PulseWidth * 9))
                    offsetStop = int(round(self.PulseWidth * 10))
                    self.add_point(i+offsetParity)
                    self.decode_position.append(i+offsetParity+ (self.PulseWidth/5))
                    self.decode_text.append(str(results[self.dataPin][i+int(offsetParity + self.PulseWidth/2)]))
                    
                    self.add_point(i+offsetStop)
                    self.decode_position.append(i+ offsetStop + (self.PulseWidth/5))
                    self.decode_text.append("Sp")
                
                i+=offsetStop
                i+=1
            else:
                i+=1
    def OkCallBack(self):
        self.dataPin = int(self.dataCombo.get())
        self.baudRate = int(self.BaudVar.get())
        self.exit_handler()
        self.parity = self.parity_var.get()
    
    def exit_handler(self):
        self.top.grab_release()
        self.top.destroy()
    def add_point(self,i):
        self.decode_index.append(i)
        self.decode_state1.append(self.decode_state1[-1])
        self.decode_state2.append(self.decode_state2[-1])
        self.decode_index.append(i+0.5)
        self.decode_state1.append(1-self.decode_state1[-1])
        self.decode_state2.append(1-self.decode_state2[-1])
Example #19
0
class CompilationScreen(TkPage):
    Name = 'Compilation'
    Font = lambda Size: ('Courier', Size) #font of the page

    def __init__(self, Parent, *args, **kwargs):
        super().__init__() #constructor of super class
        self.Songs = [Song for Song in DirList('Songs') if Song.endswith('.mid')] #mappable songs
        self.MappedSongs = [Song for Song in DirList('MappedSongs') if Song.endswith('.cmid')] #mapped and compiled song

        TopLabel = Label(self, text = 'Compile a Song', font= CompilationScreen.Font(24), bd = 10) #top label with a title for the page
        TopLabel.place(anchor= 'n', relx= 0.5, rely = 0.015, relwidth = 1, relheight=0.15) #placing the label

        self.ItemList = ListBox(self) #item list of the song
        for Index, Item in enumerate(self.Songs): #for loop for every compiled comiled song
            self.ItemList.insert(Index, Item) #indexing the song in the list
            self.ItemList.itemconfig(Index, {'bg' : '#C2C2C2'})
        self.ItemList.place(anchor= 'n', relx= 0.5, rely = 0.19, relwidth = 1, relheight = 0.46) #placing the item list

        self.ApproxValue = IntVar()
        self.ApproxValue.set(1)
        self.SingleTracks = IntVar()
        self.SingleTracks.set(0)

        self.Closest = Radio(self, text = 'Closest Approximation (A# = A, A- = A)', variable = self.ApproxValue, value = 1)
        self.Closest.place(anchor = 'nw', relx = 0.008, rely = 0.65, relheight = 0.07, relwidth = 0.6)
        self.Upper = Radio(self, text = 'Upper Approximation (A# = B, A- = A)', variable = self.ApproxValue, value = 0)
        self.Upper.place(anchor = 'nw', relx = 0.008, rely = 0.71, relheight = 0.07, relwidth = 0.6)
        self.Split = Check(self, text = 'Split MIDI into single tracks', variable = self.SingleTracks, onvalue = 1, offvalue = 0)
        self.Split.place(anchor = 'nw', relx = 0.008, rely = 0.77, relheight = 0.07, relwidth = 0.6)

        self.Compilation = Button\
        (
            self,
            text = 'Compile selected song',
            command = lambda : self.CompileSong()
        )
        self.Compilation.place(anchor = 'nw', relx = 0.615, rely = 0.66, relheight = 0.17, relwidth = 0.38)

        self.Back = Button\
        (
            self,
            text = 'Back to Home',
            command = lambda : self.TurnBack()
        )
        self.Back.place(anchor = 'nw', relx = 0.008, rely = 0.84, relheight = 0.07, relwidth = 0.988)

    def CompileSong(self):
        Song = str(self.ItemList.get('active'))
        Approximation = bool(self.ApproxValue.get())
        SplitMIDI = bool(self.SingleTracks.get())

        if Approximation:
            print('closest approximation')
            Compile(Song, True, False, SplitMIDI)
        else:
            print('upper approximation')
            Compile(Song, False, True, SplitMIDI)

    def TurnBack(self):
        GenshinLyrePlayer.Raise(Home.Name)

    def Refresh(self): #this function update the song list
        self.Songs = [Song for Song in DirList('Songs') if Song.endswith('.mid')] #check the folder for the songs
        self.ItemList.delete('0','end') #delete every item of the list
        for Index, Item in enumerate(self.Songs): #loop for every song in the folder
            self.ItemList.insert(Index, Item) #index the song in the item list
            self.ItemList.itemconfig(Index, {'bg' : '#C2C2C2'}) #background of the itemlist