Esempio n. 1
0
 def configure(self, dic={}, **kwargs):
     dic2 = {}
     dic2.update(dic)
     dic2.update(kwargs)
     self._allow_other_values = dic2.pop('allow_other_values',
                                         self._allow_other_values)
     Combobox.config(self, dic2)
Esempio n. 2
0
def statistics(df, dictionaries):
    """ фомрмирование статистик """
    global stat
    report = Toplevel()
    qty = StringVar(report)
    headers = [item for item in df if item not in ['Цена', 'Билет', 'Время']]
    q1 = LabelFrame(report, text='Качественные')
    q2 = LabelFrame(report, text='Количественные')
    choice = Combobox(q1, values=headers, textvariable=qty)
    qty.trace('w', lambda name, index, mode, sv=qty: updateBoxes(sv))
    qty.set(headers[0])
    choice.current(0)
    choice.pack(side=LEFT, padx=5, pady=5)
    q1.pack(side=TOP, padx=10, pady=10)
    choice2 = Combobox(q2, values=['Цена'])
    choice2.pack(side=LEFT, padx=5, pady=5)
    choice2.current(0)
    choice2.config(state=DISABLED)
    q2.pack(side=TOP, padx=10, pady=10)
    bframe = Frame(report)
    Button(bframe, text='Сформировать', command=lambda frame=df: text_report_old(frame))\
        .pack(side=LEFT, padx=10, pady=10)
    Button(bframe, text='Закрыть', command=lambda: report.destroy())\
        .pack(side=LEFT, padx=10, pady=10)
    bframe.pack(side=TOP)
Esempio n. 3
0
class InfoChoice(InfoMaster):
    def __init__(self, master, label, value):
        super(InfoChoice, self).__init__(master, label, value)
        self.optVar = value

        #self._label = Label(self._master, text="{0}: ".format(data[0]))
        try:
            self._value = Combobox(self._master,
                                   values=self.optVar.options,
                                   state='readonly')
        except AttributeError:
            # In this case a Variable that isn't an OptionsVar has probably
            # been passed. Just do some default values.
            self._value = Combobox(self._master,
                                   values=['Error', 'Values'],
                                   state='readonly')
        self._value.set(self.optVar.get())
        self._value.bind("<<ComboboxSelected>>", self.select_value)

        self._value.bind('<KeyPress>', self._select_from_key)

    def select_value(self, event):
        self.optVar.set(self._value.get())

    def _set_value(self, value):
        self.optVar = value
        self._value.set(self.optVar.get())
        self._value.config(values=self.optVar.options)

    def bind(self, event, func):
        # allow external overriding of the bind event
        self.select_value(event)
        self._value.bind(event, func)

    def _select_from_key(self, *args):
        """ select the first entry starting with the entered key """
        # TODO: make it continue through them?
        char = args[0].char.upper()
        for opt in self.optVar.options:
            if opt.upper().startswith(char):
                self.optVar.set(opt)
                self._value.set(self.optVar.get())
                break
def main():
    global arrLength, col, grad, fps, algo, reverse, trueRand

    WIDTH = 700
    HEIGHT = 700

    window = Tk(
        className=
        " Sorting Algorithm Visualiser - Visualise 8 Different Sorting Algorithms"
    )

    window.config(bg="#E6F6FF")
    window.geometry(f"{WIDTH}x{HEIGHT}")

    Label(window,
          text="Sorting Algorithm Visualiser - v2021.06.19",
          font=("Courier", 30),
          wraplength=500,
          justify="left").place(x=20, y=40)

    # Elements in Array

    Label(window, text="Array Length", font=("Courier", 30),
          justify="center").place(x=20, y=130)

    arrLength = StringVar()
    Entry(window, justify="center", textvariable=arrLength).place(x=20, y=180)

    Label(window, text="Default: 30 Elements",
          font=("Courier", 15)).place(x=20, y=210)

    # Algorithm Choice

    Label(window, text="Sorting Algorithm", font=("Courier", 30)).place(x=20,
                                                                        y=260)

    display = [algo[:-4:] + " " + algo[-4::] for algo in algorithms]

    algo = StringVar()
    view_algorithms = Combobox(window,
                               width=27,
                               textvariable=algo,
                               justify="center")
    view_algorithms['values'] = display
    view_algorithms.config(justify="center")

    view_algorithms.place(x=20, y=310)
    view_algorithms.current()

    Label(window, text="Default: Bubble Sort",
          font=("Courier", 15)).place(x=20, y=340)

    # Colour Picker

    Label(window, text="Colour [Hex]", font=("Courier", 30),
          justify="center").place(x=420, y=130)

    col = StringVar()
    Entry(window, justify="center", textvariable=col).place(x=420, y=180)

    Label(window, text="Default: #0396A3 (Turquoise)",
          font=("Courier", 15)).place(x=420, y=210)

    # Time Between Frames

    Label(window, text="Speed (FPS)", font=("Courier", 30),
          justify="center").place(x=420, y=260)

    fps = StringVar()
    Entry(window, justify="center", textvariable=fps).place(x=420, y=310)

    Label(window, text="Default: 5FPS", font=("Courier", 15)).place(x=420,
                                                                    y=340)

    ## Additional Settings

    Label(window,
          text="Additional Settings",
          font=("Courier", 30),
          justify="center").place(x=20, y=390)

    # Gradient Colouring

    grad = IntVar()
    Checkbutton(window, variable=grad, text="  Colour Gradient").place(x=20,
                                                                       y=440)

    # Reversed Array (Descending)

    reverse = IntVar()
    Checkbutton(window, variable=reverse,
                text="  Order Descending").place(x=20, y=470)

    # True Random Array

    trueRand = IntVar()
    Checkbutton(window, variable=trueRand,
                text="  True Random Array").place(x=20, y=500)

    # VISUALISE! Button

    Button(window,
           text=" Visualise! ",
           command=button_click,
           width=31,
           font=("Courier", 30)).place(x=20, y=550)

    Label(window, text="Siddharth Rout 2021",
          font=("Courier", 15)).place(x=20, y=595)
    Label(window,
          text="Built using Python | Tkinter | Matplotlib",
          font=("Courier", 15)).place(x=20, y=615)

    window.mainloop()
Esempio n. 5
0
class MainFrame(tk.Frame):
    def __init__(self, master=None, db_session=None):
        super().__init__(master)
        self.master = master
        self.db_session = db_session

        self.board_tile_width = 100

        x = self.master.winfo_screenwidth() // 2 - 150
        y = self.master.winfo_screenheight() // 2 - 50
        self.master.geometry("%dx%d+%d+%d" % (300, 275, x, y))
        self.master.resizable(False, False)

        padx = 10
        pady = 5

        self.tabs = Notebook(self)
        self.tabs.grid(row=0, column=0, sticky="NW")

        self.tabs_game = tk.Frame(self.tabs)
        self.tabs.add(self.tabs_game, text="Game")

        self.start_frame = tk.Frame(self.tabs_game)
        self.start_frame.grid(row=0, column=0, pady=pady, sticky="NW")
        self.start_btn = tk.Button(self.start_frame,
                                   text="Play",
                                   command=self.start_game)
        self.start_btn.grid(row=0, column=0, padx=padx, pady=pady, sticky="NW")
        self.ai_difficulty = tk.IntVar(self, -1)
        for ai_difficulty in [((0, 0), "2 players", -1),
                              ((1, 0), "Random AI", 0),
                              ((0, 1), "Normal AI", 1)]:
            radio_btn = tk.Radiobutton(
                self.start_frame,
                variable=self.ai_difficulty,
                text=ai_difficulty[1],
                val=ai_difficulty[2],
            )
            radio_btn.grid(row=ai_difficulty[0][1],
                           column=ai_difficulty[0][0] + 1,
                           pady=pady,
                           sticky="NW")

        self.status_frame = tk.Frame(self.tabs_game)
        self.status_frame.grid(row=1,
                               column=0,
                               padx=padx,
                               pady=pady,
                               sticky="NW")
        self.status_frame.grid_remove()

        self.status_label = tk.Label(self.status_frame, text="")
        self.status_label.grid(row=0, column=0, pady=pady, sticky="NW")

        self.draw_btn = tk.Button(self.status_frame,
                                  text="Claim draw",
                                  command=self.claim_draw)
        self.draw_btn.grid(row=0, column=1, padx=padx, pady=pady, sticky="NE")
        self.draw_btn.grid_remove()

        self.moves_text = ScrolledText(self.status_frame,
                                       width=20,
                                       height=3,
                                       state=tk.DISABLED)
        self.moves_text.grid(row=1, column=0, pady=pady)

        self.promotion_piece = tk.StringVar(self, "Q")
        self.promotion_piece_selection_frame = tk.Frame(self.tabs_game)
        self.promotion_piece_selection_frame.grid(row=3,
                                                  column=0,
                                                  padx=padx,
                                                  pady=pady)
        self.promotion_piece_selection_frame.grid_remove()
        promotion_label = tk.Label(self.promotion_piece_selection_frame,
                                   text="Promotion piece")
        promotion_label.grid(row=0, column=0, sticky="NW")
        for promotion_piece in [
            (0, "Knight", "N"),
            (1, "Bishop", "B"),
            (2, "Rook", "R"),
            (3, "Queen", "Q"),
        ]:
            radio_btn = tk.Radiobutton(
                self.promotion_piece_selection_frame,
                variable=self.promotion_piece,
                command=self.on_promotion_piece_selected,
                text=promotion_piece[1],
                val=promotion_piece[2],
            )
            radio_btn.grid(row=1, column=promotion_piece[0], pady=pady)

        self.view_control_btn_frame = tk.Frame(self.tabs_game)
        self.view_control_btn_frame.grid(row=3, column=0, padx=padx, pady=pady)
        self.view_control_btn_frame.grid_remove()

        self.previous_move_btn = tk.Button(self.view_control_btn_frame,
                                           text="Previous",
                                           command=self.previous_move)
        self.previous_move_btn.grid(row=0, column=0, padx=padx, pady=pady)

        self.next_move_btn = tk.Button(self.view_control_btn_frame,
                                       text="Next",
                                       command=self.next_move)
        self.next_move_btn.grid(row=0, column=1, padx=padx, pady=pady)

        self.save_game_btn = tk.Button(self.tabs_game,
                                       text="Save",
                                       command=self.db_save_game)
        self.save_game_btn.grid(row=4,
                                column=0,
                                padx=padx,
                                pady=pady,
                                sticky="NW")
        self.save_game_btn.grid_remove()

        self.tabs_database = tk.Frame(self.tabs)
        self.tabs.add(self.tabs_database, text="Database")

        self.pgn_label = tk.Label(self.tabs_database,
                                  text="Portable Game Notation")
        self.pgn_label.grid(row=0, column=0, padx=padx, sticky="NW")

        self.pgn_text = ScrolledText(self.tabs_database, width=20, height=3)
        self.pgn_text.grid(row=1, column=0, padx=padx, pady=pady, sticky="NW")

        pgn_btn_frame = tk.Frame(self.tabs_database)
        pgn_btn_frame.grid(row=2, column=0, pady=pady, sticky="NW")

        import_btn = tk.Button(pgn_btn_frame,
                               text="Import",
                               command=self.import_pgn)
        import_btn.grid(row=0, column=0, padx=padx, pady=pady)

        export_btn = tk.Button(pgn_btn_frame,
                               text="Export",
                               command=self.export_pgn)
        export_btn.grid(row=0, column=1, padx=padx, pady=pady)

        view_btn = tk.Button(pgn_btn_frame,
                             text="View",
                             command=lambda: self.start_game(view_mode=True))
        view_btn.grid(row=0, column=2, padx=padx, pady=pady)

        game_list_frame = tk.Frame(self.tabs_database)
        game_list_frame.grid(row=4, column=0, pady=pady)

        game_list_label = tk.Label(game_list_frame, text="Stored games")
        game_list_label.grid(row=0, column=0, padx=padx, sticky="NW")

        self.game_combobox = Combobox(game_list_frame, state="readonly")
        self.game_combobox.grid(row=1, column=0, padx=padx, pady=pady)

        load_btn = tk.Button(game_list_frame,
                             text="Load",
                             command=self.db_load_pgn)
        load_btn.grid(row=1, column=1, padx=padx, pady=pady)

        delete_btn = tk.Button(game_list_frame,
                               text="Delete",
                               command=self.db_delete_game)
        delete_btn.grid(row=1, column=2, padx=padx, pady=pady)

        self.db_load_games()

        self.tabs_settings = tk.Frame(self.tabs)
        self.tabs.add(self.tabs_settings, text="Settings")

        self.enable_sounds = tk.BooleanVar(
            value=self.db_get_setting("enable_sounds", "0") == "1")
        if system() != "Linux":
            sound_checkbtn = tk.Checkbutton(
                self.tabs_settings,
                text="Enable sounds",
                variable=self.enable_sounds,
                command=lambda: self.db_store_setting(
                    "enable_sounds", "1" if self.enable_sounds.get() else "0"),
            )
            sound_checkbtn.grid(row=0,
                                column=0,
                                padx=padx,
                                pady=pady,
                                sticky="NW")

        self.theme = tk.StringVar(self,
                                  self.db_get_setting("theme", "Classic"))

        theme_frame = tk.Frame(self.tabs_settings)
        theme_frame.grid(row=1, column=0, pady=pady)

        theme_label = tk.Label(theme_frame, text="Theme")
        theme_label.grid(row=0, column=0, padx=padx, sticky="NW")
        theme_combobox = Combobox(
            theme_frame,
            textvariable=self.theme,
            values=["Classic", "Dark"],
            state="readonly",
        )
        theme_combobox.bind("<<ComboboxSelected>>", self.update_theme)
        theme_combobox.grid(row=1, column=0, padx=padx, pady=pady)

        credits_btn = tk.Button(
            self.tabs_settings,
            text="Credits",
            command=lambda: tk.messagebox.showinfo(
                title="Credits",
                message="%s by %s\n\nIcons:\n%s" % (
                    self.master.title(),
                    "Kekalainen ([email protected])",
                    "Font Awesome Free 5.15.3 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0)",
                ),
            ),
        )
        credits_btn.grid(row=2, column=0, padx=padx, pady=pady, sticky="NW")

        quit_btn = tk.Button(self, text="Quit", command=self.master.destroy)
        quit_btn.grid(row=1, column=0, padx=padx, pady=pady, sticky="NW")

        self.grid()

    def import_pgn(self):
        path = filedialog.askopenfilename(
            title="Import a PGN file",
            filetypes=[("PGN file", "*.pgn")],
        )
        if path:
            with open(path) as f:
                self.pgn_text.delete(1.0, tk.END)
                self.pgn_text.insert(1.0, f.read())

    def export_pgn(self):
        path = filedialog.asksaveasfilename(
            title="Export a PGN file",
            filetypes=[("PGN file", "*.pgn")],
            defaultextension=".pgn",
        )
        if path:
            with open(path, "w") as f:
                f.write(self.pgn_text.get(1.0, tk.END))

    def db_save_game(self):
        name = simpledialog.askstring("Save PGN",
                                      "Enter a name for the game.",
                                      parent=self)
        if name:
            game = GameModel(name=name, pgn=self.moves_text.get(1.0, tk.END))
            self.db_session.add(game)
            self.db_session.commit()
            self.db_load_games()

    def db_load_games(self):
        self.db_games = (self.db_session.query(GameModel).order_by(
            GameModel.id.desc()).all())
        names = []
        for game in self.db_games:
            names.append(game.name)
        self.game_combobox.config(values=names)
        if names:
            self.game_combobox.set(names[0])
        else:
            self.game_combobox.set("")

    def db_load_pgn(self):
        if len(self.db_games) > 0:
            game = self.db_games[self.game_combobox.current()]
            self.pgn_text.delete(1.0, tk.END)
            self.pgn_text.insert(1.0, game.pgn)

    def db_delete_game(self):
        if len(self.db_games) > 0:
            game = self.db_games[self.game_combobox.current()]
            self.db_session.delete(game)
            self.db_session.commit()
            self.db_load_games()

    def db_get_setting(self, name, fallback):
        setting = (self.db_session.query(SettingModel).filter(
            SettingModel.name == name).first())
        if setting:
            return setting.value
        return fallback

    def db_store_setting(self, name, value):
        setting = (self.db_session.query(SettingModel).filter(
            SettingModel.name == name).first())
        if setting:
            setting.value = value
        else:
            setting = SettingModel(name=name, value=str(value))
        self.db_session.add(setting)
        self.db_session.commit()

    def play_move_sound(self, undo=False):
        """Plays a sound for a moving piece."""
        threading.Thread(
            target=playsound,
            args=("src/audio/move_" +
                  ("2" if (undo and not self.game.white_to_move) or
                   (not undo and self.game.white_to_move) else "1") +
                  ".mp3", ),
            daemon=True,
        ).start()

    def update_theme(self, event=None):
        """Stores the selected theme and updates the board, if necessary."""
        theme = self.theme.get()
        self.db_store_setting("theme", theme)
        if hasattr(self, "game"):
            colors = ["#542E1D", "#EFD8B0"]
            if theme == "Dark":
                colors = ["#9C9C9C", "#4A4A4A"]
            self.board_frame.tile_colors = colors
            self.board_frame.draw_board()

    def on_game_update(self):
        game_over_previously = "to move" not in self.status_label["text"]
        text = ""

        if self.game.check and not self.game.checkmate:
            text += "Check. "

        if self.game.white_to_move:
            text += "White to move."
        else:
            text += "Black to move."

        if self.game.checkmate:
            text = "Checkmate."
            if not self.game.white_to_move:
                text += " White wins."
            else:
                text += " Black wins."
        elif self.game.stalemate:
            text = "Stalemate. Draw."
        elif self.game.draw:
            text = "Draw."

        self.status_label["text"] = text

        move_log = ""
        for i in range(len(self.game.an_moves)):
            if i % 2 == 0:
                move_log += str(i // 2 + 1) + ". "
            move_log += self.game.an_moves[i]
            if i % 2 == 0:
                move_log += " "
            else:
                move_log += "\n"

        if self.game.checkmate or self.game.stalemate or self.game.draw:
            move_log = move_log[0:len(move_log) - 1] + " "
            if self.game.checkmate:
                if self.game.white_to_move:
                    move_log += "0-1"
                else:
                    move_log += "1-0"
            else:
                move_log += "1/2-1/2"

        self.moves_text.config(state=tk.NORMAL)
        self.moves_text.delete(1.0, tk.END)
        self.moves_text.insert(1.0, move_log)
        self.moves_text.config(state=tk.DISABLED)
        self.moves_text.yview(tk.END)

        if not self.game.draw and True in self.game.can_claim_draw:
            self.draw_btn.grid()
        else:
            self.draw_btn.grid_remove()

        if hasattr(self.game, "ai") and self.game.white_to_move:
            self.board_frame.draw_pieces()

        moves_length = len(self.game.an_moves)
        if self.enable_sounds.get(
        ) and self.previous_moves_length != moves_length:
            undo = self.previous_moves_length > moves_length
            if hasattr(self.game, "ai") and undo and not game_over_previously:
                self.play_move_sound(not undo)
            self.play_move_sound(undo)
            self.previous_moves_length = moves_length

    def on_promotion_piece_selected(self):
        if hasattr(self, "game"):
            self.game.board.promotion_piece = self.promotion_piece.get()

    def start_game(self, view_mode=False):
        if not hasattr(self, "game"):
            self.previous_moves_length = 0
            if view_mode:
                self.active_pgn = re.findall(
                    "((?!-)[a-zA-Z0-]+[0-9]?\w+(?!\.)=?[N|B|R|Q]?)(?![^{]*})(?![^[]*])",
                    self.pgn_text.get(1.0, tk.END),
                )
                if not self.active_pgn:
                    return
                self.active_pgn_index = 0
                self.previous_move_btn.configure(state=tk.DISABLED)
                self.next_move_btn.configure(state=tk.NORMAL)
                self.view_control_btn_frame.grid()
                self.tabs.select(self.tabs_game)
            else:
                self.promotion_piece_selection_frame.grid()
                self.save_game_btn.grid()

            self.game = Game(
                on_update=self.on_game_update,
                ai_difficulty=self.ai_difficulty.get()
                if not view_mode else -1,
            )
            self.game.board.promotion_piece = self.promotion_piece.get()
            self.board_dimension = self.game.board.width * self.board_tile_width
            self.board_window = tk.Toplevel(master=self)
            x = self.master.winfo_x() - self.board_dimension - 4
            y = self.master.winfo_y()
            self.board_window.geometry(
                "%dx%d+%d+%d" %
                (self.board_dimension, self.board_dimension, x, y))
            self.board_window.resizable(False, False)
            self.board_frame = BoardFrame(
                self.board_window,
                game=self.game,
                tile_width=self.board_tile_width,
                view_mode=view_mode,
            )
            self.update_theme()
            self.master.bind("<Configure>", self.board_window_follow)
            self.board_window.protocol("WM_DELETE_WINDOW",
                                       self.on_board_window_close)

            self.start_frame.grid_remove()
            self.status_frame.grid()
            self.on_game_update()

    def claim_draw(self):
        if hasattr(self, "game"):
            if self.game.claim_draw():
                self.board_frame.deselect_tile()
                self.draw_btn.grid_remove()

    def next_move(self):
        n = len(self.active_pgn)
        if self.active_pgn_index < n:
            self.game.move_piece_an(self.active_pgn[self.active_pgn_index])
            self.board_frame.draw_pieces()
            self.active_pgn_index += 1
            if self.active_pgn_index == n:
                self.next_move_btn.configure(state=tk.DISABLED)
            self.previous_move_btn.configure(state=tk.NORMAL)

    def previous_move(self):
        if self.active_pgn_index > 0:
            self.game.undo_move()
            self.board_frame.draw_pieces()
            self.active_pgn_index -= 1
            if self.active_pgn_index == 0:
                self.previous_move_btn.configure(state=tk.DISABLED)
            self.next_move_btn.configure(state=tk.NORMAL)

    def board_window_follow(self, event=None):
        x = self.master.winfo_x() - self.board_dimension - 4
        y = self.master.winfo_y()
        self.board_window.geometry("+%d+%d" % (x, y))

    def on_board_window_close(self):
        delattr(self, "game")
        self.master.unbind("<Configure>")
        self.board_window.destroy()
        self.start_frame.grid()
        self.status_frame.grid_remove()
        self.view_control_btn_frame.grid_remove()
        self.promotion_piece_selection_frame.grid_remove()
        self.save_game_btn.grid_remove()
        self.draw_btn.grid_remove()
Esempio n. 6
0
class App(Frame):
    def __init__(self, master,*args, **kwargs):
        Frame.__init__(self, master, *args, **kwargs)

        try:
            from covid import Covid
            self.C = Covid()
            self.covidInstalled = True
        except ModuleNotFoundError:
            self.covidInstalled =False

        self.Countries = None
        self.WorldData = None
        self.AllData = None

        self.ThreadRunning = False

        self.TopFrame = LabelFrame(self, text="Select World or Country", font="Consolas 10", fg="blue")
        self.TopFrame.pack(fill="x", pady=20, padx=5)
        self.BuildTop(self.TopFrame)

        self.BodyFrame = LabelFrame(self, text="Data", font="Consolas 10", fg="blue")
        self.BodyFrame.pack(pady=5, fill="both", padx=5)
        self.progressFrame = Frame(self.BodyFrame)
        self.progressFrame.pack(side = "top" ,fill = "x")
        self.progress = Progressbar(self.progressFrame , orient="horizontal", mode="indeterminate")
        self.LastUpdatedLabel = Label(self ,font = "Consolas 10 bold" ,bg="#ffd")
        self.LastUpdatedLabel.pack(side="right")


        self.ShowData(2)

    def BuildTop(self, master):

        self.RadioVar = IntVar(master)
        self.RadioVar.set(2)

        self.options = {"font": ("Consolas", 15), "cursor": "hand2"}

        # 22222222222222222222222222

        self.WorldRadioButton = Radiobutton(master, text="World Data", variable=self.RadioVar)
        self.WorldRadioButton.config(value=1, command=lambda: self.RadioButtonSelected(1), **self.options)

        self.CountryRadioButton = Radiobutton(master, text="Country Data", variable=self.RadioVar)
        self.CountryRadioButton.config(value=2, command=lambda: self.RadioButtonSelected(2), **self.options)

        # @@@@@@@@@@@@@@@@@@@@@@@@@@@@2

        self.WorldRadioButton.pack(side="left", padx=20)
        self.CountryRadioButton.pack(side="left")

        # $$$$$$$$$$$$$$$$$$$$$$$$$$$

        self.previousRadioSelected = 2

        # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!1

        self.CountryCombobox = Combobox(master, state="normal", **self.options)
        self.CountryCombobox.pack(side="left", padx=5)
        self.CountryCombobox.bind("<<ComboboxSelected>>", lambda evt: self.OnComboBoxItemSelected())

        popup = self.CountryCombobox.tk.eval("ttk::combobox::PopdownWindow %s" % self.CountryCombobox)
        self.CountryCombobox.tk.call('%s.f.l' % popup, 'configure', '-font',
                                     ("Consolas 13"))

        # ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

        breaker = Label(master, text="|", font="Consolas 25", fg="#bbb")
        breaker.pack(side="left")

        # *******************************

        self.RefreshBtn = Button(master, text="Refresh", font="Consolas 11", bd=1, cursor="hand2")
        self.RefreshBtn.config(command=self.refresh)
        self.RefreshBtn.pack(side='left')

    def RadioButtonSelected(self, flag):
        if (self.ThreadRunning):
            print("Busy...")
            self.RadioVar.set(1 if flag ==2 else 2)
            return

        if (flag == 1 and self.previousRadioSelected != 1):
            #print("World Selected")
            self.CountryCombobox.config(state="disable")
            self.ShowData(1)
            self.previousRadioSelected = 1
        elif (flag == 2 and self.previousRadioSelected != 2):
            #print("Country Selected")
            self.CountryCombobox.config(state="enable")
            self.ShowData(2)
            self.previousRadioSelected = 2

    def ShowData(self, flag):

        if (flag == 1):
            try:
                self.df.destroy()
                self.cf.destroy()
                self.breaker.destroy()
            except:
                pass
            self.df = DataField(self.BodyFrame, width="large")
            # Update Values Here
            # loading data
            if (self.WorldData == None):
                self.BodyFrame['text'] = "Loading Data ..."
                self.progress.pack(fill="x")
                self.progress.start(5)

                Th = thread(mode=thread.MODE_LOAD_WORLD_DATA, obj=self)
                Th.start()
            else:
                self.BodyFrame['text'] = "World Data"
                self.df.pack()
                self.df.config(self.WorldData)

            # data = C.get_status_by_country_id(27)
            # self.df.config(data)
            # self.progress.destroy()
            # self.df.pack()

        elif (flag == 2):
            try:
                self.df.destroy()
            except:
                pass

            self.cf = CountryField(self.BodyFrame)
            # Update Values Here
            # self.cf.pack(side="left" ,padx =7)

            self.breaker = Label(self.BodyFrame, bg="#000", height=16)
            # self.breaker.pack(side="left" ,padx =3)

            self.df = DataField(self.BodyFrame, width="normal")
            # Also Update Values Here
            # self.df.pack(side="left" ,padx = 7)

            if (self.AllData == None):
                self.BodyFrame['text'] = "Loading Data ..."
                self.progress.pack(fill="x")
                self.progress.start(5)
                Thr = thread(mode=thread.MODE_LOAD_ALL_DATA, obj=self)
                Thr.start()

                self.CountryCombobox.set("India")
            else:
                self.CountryCombobox["values"] = [x['country'] for x in self.AllData]
                countryData = None
                countryName = self.CountryCombobox.get()
                if (countryName not in self.CountryCombobox["values"]):
                    countryName = "India"
                    self.CountryCombobox.set("India")

                for x in self.AllData:
                    if (x['country'] == countryName):
                        countryData = x
                        break

                self.BodyFrame['text'] = "Country Wise Data (%s)" % countryName
                self.cf.config(countryData)
                self.df.config(countryData)

                self.cf.pack(side="left", padx=7)
                self.breaker.pack(side="left", padx=3)
                self.df.pack(side="left", padx=7)

    def OnComboBoxItemSelected(self):
        cur = self.CountryCombobox.get()
        data = None
        for z in self.AllData:
            if (z['country'] == cur):
                data = z
                break

        self.BodyFrame["text"] = "Country Wise Data (%s)" % cur
        self.df.config(data)
        self.cf.config(data)
        self.LastUpdatedLabel["text"] = "Last Update : %s"%self.formatTime(data["last_update"])

    def refresh(self):
        print("Refreshing ...")

        if (self.RadioVar.get() == 1):
            #print("World")
            self.BodyFrame['text'] = "Refreshing Data ..."
            self.progress.pack(fill="x")
            self.progress.start(5)

            Th = thread(mode=thread.MODE_LOAD_WORLD_DATA, obj=self)
            Th.start()

        elif (self.RadioVar.get() == 2):
            self.BodyFrame['text'] = "Refreshing Data ..."
            self.progress.pack(fill="x")
            self.progress.start(5)

            Thr = thread(mode=thread.MODE_LOAD_ALL_DATA, obj=self)
            Thr.start()

    def formatTime(self , timeStamp):

        timeStamp = int(int(timeStamp)/1000)
        date = datetime.datetime.fromtimestamp((timeStamp))
        if(date.day == datetime.datetime.today().day):
            time = "Today %02d:%02d "%(date.hour,date.minute)
        else:
            time = "%02d:%02d (%s/%s/%s) "%(date.hour ,date.minute ,date.day ,date.month ,date.year)
        return time
Esempio n. 7
0
class Application(Labelframe):
    """Contains data reffering to application"""
    def __init__(self, window, **kwargs):
        Labelframe.__init__(self, window, **kwargs)
        self.name_of_applicant_n_lab = Label(self, text="Wnioskodawcy (m)")
        self.name_of_applicant_n_lab.grid(row=0,
                                          column=0,
                                          padx=5,
                                          pady=5,
                                          sticky='e')
        self.name_of_applicant_n = Entry(self, width=40)
        self.name_of_applicant_n.grid(row=0,
                                      column=1,
                                      columnspan=3,
                                      padx=5,
                                      pady=5,
                                      sticky='w')

        self.name_of_applicant_g_lab = Label(self, text="Wnioskodawcy (d)")
        self.name_of_applicant_g_lab.grid(row=1,
                                          column=0,
                                          padx=5,
                                          pady=5,
                                          sticky='e')
        self.name_of_applicant_g = Entry(self, width=40)
        self.name_of_applicant_g.grid(row=1,
                                      column=1,
                                      columnspan=3,
                                      padx=5,
                                      pady=5,
                                      sticky='w')

        self.city_lab = Label(self, text="Miejscowość")
        self.city_lab.grid(row=3, column=0, padx=5, pady=5, sticky='e')
        self.city = Entry(self, width=20)
        self.city.grid(row=3,
                       column=1,
                       columnspan=2,
                       padx=5,
                       pady=5,
                       sticky='w')

        self.zip_code_lab = Label(self, text="Kod")
        self.zip_code_lab.grid(row=3, column=2, padx=5, pady=5, sticky='e')
        self.zip_code = Entry(self, width=7)
        self.zip_code.grid(row=3, column=3, padx=5, pady=5, sticky='w')

        self.address_lab = Label(self, text="Adres")
        self.address_lab.grid(row=4, column=0, padx=5, pady=5, sticky='e')
        self.address = Entry(self)
        self.address.grid(row=4,
                          column=1,
                          columnspan=2,
                          padx=5,
                          pady=5,
                          sticky='w')

        self.same = Button(self, text="Adres jak wyżej")
        self.same.grid(row=4, column=2, columnspan=2)

        self.application_subject_lab = Label(self, text="           Wniosek o")
        self.application_subject_lab.grid(row=6,
                                          column=0,
                                          padx=5,
                                          pady=5,
                                          sticky='e')
        self.application_subject = Combobox(self, width=40, values=application)
        self.application_subject.grid(row=6,
                                      column=1,
                                      columnspan=3,
                                      padx=5,
                                      pady=5)
        self.application_subject.bind('<<ComboboxSelected>>',
                                      self.choosed_subject)

        self.application_reason_lab = Label(self, text="Z uwagi na")
        self.application_reason_lab.grid(row=7,
                                         column=0,
                                         padx=5,
                                         pady=5,
                                         sticky='e')
        self.application_reason = Combobox(self,
                                           width=40,
                                           postcommand=self.get_reason,
                                           exportselection=False)
        self.application_reason.bind('<<ComboboxSelected>>',
                                     self.clear_all_selection)
        self.application_reason.grid(row=7,
                                     column=1,
                                     columnspan=3,
                                     padx=5,
                                     pady=5)
        self.application_reason2_lab = Label(self, text="Z uwagi na")
        self.application_reason2_lab.grid(row=8,
                                          column=0,
                                          padx=5,
                                          pady=5,
                                          sticky='e')
        self.application_reason2 = Combobox(self, width=40, values=reasons)
        self.application_reason2.bind('<<ComboboxSelected>>',
                                      self.clear_all_selection)
        self.application_reason2.grid(row=8,
                                      column=1,
                                      columnspan=3,
                                      padx=5,
                                      pady=5)

        self.timespan_lab = Label(self, text="Na okres")
        self.timespan_lab.grid(row=9, column=0, padx=5, pady=5, sticky='e')
        self.timespan = Combobox(self, values=timespan)
        self.timespan.bind('<<ComboboxSelected>>', self.clear_all_selection)
        self.timespan.grid(row=9, column=1, pady=5, padx=5, sticky='w')
        self.timespan_ind = Entry(self, width=18)
        self.timespan_ind.grid(row=9,
                               column=2,
                               columnspan=2,
                               padx=5,
                               pady=5,
                               sticky='w')

    def get_reason(self):
        if self.application_subject.get() == "kształcenie specjalne":
            self.application_reason['values'] = reasons[0:-2]
            self.application_reason2['values'] = reasons[0:-2]
            self.timespan_ind.config(state='disabled')
            self.timespan.config(state='active')
            self.application_reason2.config(state='active')
        if self.application_subject.get() in [
                "indywidualne roczne przygotowanie przedszkolne",
                "indywidualne nauczanie"
        ]:
            self.application_reason['values'] = reasons[-2:]
            self.timespan.config(state='disabled')
            self.timespan_ind.config(state='active')
            self.application_reason2.config(state='disabled')
        if self.application_subject.get() in [
                "zajęcia rewalidacyjno-wychowawcze indywidualne",
                "zajęcia rewalidacyjno-wychowawcze zespołowe"
        ]:
            self.application_reason['values'] = (reasons[3], )
            self.timespan.config(state='disabled')
            self.timespan_ind.config(state='disabled')
            self.application_reason2.config(state='disabled')
        if self.application_subject.get() == "wczesne wspomaganie rozwoju":
            self.application_reason['values'] = reasons[:9]
            self.timespan_ind.config(state='disabled')
            self.timespan.config(state='active')
            self.timespan['values'] = [timespan[4]]
            self.application_reason2.config(state='disabled')
        self.application_subject.select_clear()

    def clear_all_selection(self, event):
        self.application_subject.select_clear()
        self.application_reason.select_clear()
        self.application_reason2.select_clear()
        self.timespan.select_clear()

    def choosed_subject(self, event):
        actual_reason = self.application_reason.get()
        self.get_reason()
        supposed_reason = self.application_reason['values']
        if actual_reason not in supposed_reason:
            self.application_reason.delete(0, 'end')

    def insert_application_data(self, student):
        for entry, key in zip([
                self.name_of_applicant_n, self.name_of_applicant_g,
                self.zip_code, self.city, self.address,
                self.application_subject, self.application_reason,
                self.application_reason2, self.timespan, self.timespan_ind
        ], [
                'applicant_n', 'applicant_g', 'applicant_zipcode',
                'applicant_city', 'applicant_address', 'subject', 'reason',
                'reason2', 'timespan', 'timespan_ind'
        ]):
            entry.delete(0, 'end')
            entry.insert(0, student[key])

    def clear(self):
        for entry in [
                self.name_of_applicant_n, self.name_of_applicant_g,
                self.zip_code, self.city, self.address,
                self.application_subject, self.application_reason,
                self.application_reason2, self.timespan, self.timespan_ind
        ]:
            entry.delete(0, 'end')
Esempio n. 8
0
lbl_CompQty1 = Label(root, text="Quantity 1", width=8)
lbl_CompQty1.grid(row=2, column=5, padx=4)
lbl_CompQty1.config(font=labelfont)
lbl_CompUnits1 = Label(root, text="Units 1", width=8)
lbl_CompUnits1.grid(row=2, column=6, padx=4)
lbl_CompUnits1.config(font=labelfont)
lbl_Compound1 = Label(root, text="  Compound 1", width=10)
lbl_Compound1.grid(row=2, column=7, padx=4)
lbl_Compound1.config(font=labelfont)
#n=0
e_ElementQty1 = Entry(root, text="eeq1 ", width=8)
e_ElementQty1.grid(row=3, column=0, padx=4)
e_ElementQty1.config(font=entryfont, textvariable=eci_qty)
cb_Units1 = Combobox(root, values=unit_values, width=8)
cb_Units1.grid(row=3, column=1, padx=4)
cb_Units1.config(font=entryfont)
#, textvariable = n)  #, command=set_element1())
#elements = "Ac Ag Al Am Ar As At Au B Ba Be Bi Bk Br C Ca Cd Ce Cf Cl Cm Co Cr "
cb_Elements1 = Combobox(root, values=elements, width=8)
cb_Elements1.grid(row=3, column=2, padx=4)
cb_Elements1 = Combobox(root, command=set_element1(), textvariable=element1)
cb_Elements1.config(font=entryfont)
#element1 = cb_Elements1.get()
#element1 = Combobox(cb_Elements1.get())
e_Yield1 = Entry(root, text="Yield", width=8)
e_Yield1.grid(row=3, column=4, padx=4)
e_Yield1.config(font=entryfont)
e_CompoundQty1 = Entry(root, text="CompoundQty 1", width=8)
e_CompoundQty1.grid(row=3, column=5, padx=4)
e_CompoundQty1.config(font=entryfont)
cb_CompoundUnits1 = Combobox(root, values=unit_values, width=8)
Esempio n. 9
0
class retailPage(Frame):
    ''' the main page that actually branches into 2 seperate frames for buying and selling
        this frame provides the use with the
'''
    def __init__(self, parent, main, **kw):
        Frame.__init__(self, parent, **kw)
        self.main = main
        self.Head = Label(font=MED_FONT)

        self.retail_back_b = Button(text='BACK', command=self.back_fb)
        self.stock_name = StringVar()
        self.stock_name_ = ''
        self.stock_name_c = Combobox(textvariable=self.stock_name)
        self.stock_name_l = Label(text='Stock name: ')
        self.amount = Entry()
        self.amount_l = Label(text='Number of stocks :')

        self.check_avail_b = Button(text='Check')
        self.cost_l = Label(text='Cost: ')
        self.cost = Label()
        self.buy_stock_b = Button(text='BUY Stock')
        self.sellp_l = Label(text='Current Selling Price: ')
        self.profit_l = Label(text='PROFIT/LOSS')
        self.sell_stock_b = Button(text='SELL Stock')
        self.page = None

    def showItems(self, main):
        self.Head.grid(column=0, row=0, columnspan=2)
        self.Head.configure(text='logged in as %s' % main.present_user)
        if self.page == 'b':
            self.buy()
        elif self.page == 's':
            self.sell()

    def hideItems(self, main):
        self.Head.grid_forget()

    def buy(self):
        '''This function creates the buy window
'''
        self.retail_back_b.grid(column=1, row=5)
        self.retail_back_b.config(command=self.back_fb)
        self.stock_name_l.grid(column=0, row=1)
        self.stock_name_c.grid(column=1, row=1)
        self.stock_name_c.config(values=self.main.shares_dict.keys())
        self.amount_l.grid(column=0, row=2)
        self.amount.grid(column=1, row=2)
        self.check_avail_b.config(command=self.check_avail_buy)
        self.check_avail_b.grid(column=0, row=3)
        self.cost_l.grid(column=0, row=4, columnspan=2)
        self.buy_stock_b.config(command=self.buy_stock,
                                text='Buy Stock',
                                state='disabled')
        self.buy_stock_b.grid(column=0, row=5)

    def sell(self):
        '''This function creats the sell window'''
        self.retail_back_b.grid(column=1, row=6)
        self.retail_back_b.config(command=self.back_fs)
        self.check_avail_b.config(command=self.check_avail_sell)
        self.stock_name_l.grid(column=0, row=1)
        self.stock_name_c.grid(column=1, row=1)
        self.stock_name_c.config(values=self.main.shares_dict.keys())
        self.amount_l.grid(column=0, row=2)
        self.amount.grid(column=1, row=2)
        self.check_avail_b.grid(column=0, row=3)
        self.sellp_l.grid(column=0, row=4, columnspan=2)
        self.profit_l.grid(column=0, row=5, columnspan=2)
        self.sell_stock_b.config(command=self.sell_stock,
                                 state='disabled',
                                 text='Check')
        self.sell_stock_b.grid(column=0, row=6)

    def back_fb(self):
        '''Back from buy i.e. removes all the items needed to make buy'''
        self.retail_back_b.grid_forget()
        self.Head.grid(column=0, row=0, columnspan=2)
        self.stock_name_l.grid_forget()
        self.stock_name_c.grid_forget()
        self.amount_l.grid_forget()
        self.amount.grid_forget()
        self.check_avail_b.grid_forget()
        self.cost_l.grid_forget()
        self.buy_stock_b.grid_forget()
        self.buy_stock_b.config(state='disabled')

        self.main.show_frame(VIEW_STOCK, RETAIL_PAGE)
        self.stock_name.set('')
        self.amount.delete(0, END)

    def back_fs(self):
        ''' Back from sell i.e. removes all the items needed to make it sell window'''
        self.Head.grid(column=0, row=0, columnspan=2)
        self.retail_back_b.grid_forget()
        self.check_avail_b.grid_forget()
        self.stock_name_l.grid_forget()
        self.stock_name_c.grid_forget()
        self.amount_l.grid_forget()
        self.amount.grid_forget()
        self.sellp_l.grid_forget()
        self.profit_l.grid_forget()
        self.sell_stock_b.grid_forget()

        self.main.show_frame(VIEW_STOCK, RETAIL_PAGE)
        self.stock_name.set('')
        self.amount.delete(0, END)
        self.check_avail_b.grid_forget()

    def check_avail_buy(self):
        ''' Performs a check whether the number of shares requisted are available or not and then check whether the
            person has the required amounts of fund or not for the transaction to go through'''
        name = self.stock_name.get()
        l2 = self.main.accounts[self.main.present_user]

        if name in self.main.shares_dict.keys():
            li = self.main.shares_dict[name]
        else:
            self.stock_name.delete(0, END)
            showinfo(meassage='Enter a Valid Stock name')

        available_num = int(li['tot_amount']) - int(li['tot_sold'])
        req = int(self.amount.get())
        cost = req * int(li['cost'])

        if req < 0:
            showinfo(message='Enter a Valid amount')
        elif req > available_num:
            showinfo(message='Enter an amount less than ' + str(available_num))
        elif cost > int(l2['balance']):
            showinfo(message='You have only %s in you account' % l2['balance'])
        else:
            self.cost_l.config(text='Cost: \t' + li['cost'] + '*' + str(req) +
                               '=' + str(cost))
            self.buy_stock_b.config(state='normal')

    def check_avail_sell(self):
        ''' Performs a check whether the user has enough stocks to sell'''
        name = self.stock_name.get()
        if name in self.main.shares_dict.keys():
            li = self.main.shares_dict[name]
        else:
            self.stock_name.delete(0, END)
            showinfo(message='Enter a Valid Stock name')
        req = int(self.amount.get())
        if req < 0:
            showinfo(message='Please Enter a Valid amount')
            self.amount.delete(0, END)
        li = self.main.p_user_dict
        ok = False
        for i in li:
            if name == i['name']:
                ok = True
                buff = i

        if req > int(buff['tot_owned']):
            showinfo(message='You dont have that many stocks try less than ' +
                     buff['tot_owned'])
            self.amount.delete(0, END)
        cost = self.main.shares_dict[name]['cost']
        tot_cost = req * int(cost)
        try:
            spent = req * float(buff['money_spent']) / int(buff['tot_owned'])
        except:
            spent = 0
        pol = tot_cost - spent

        if pol >= 0:
            self.profit_l.config()
        elif pol < 0:
            self.profit_l.config()
        if req <= int(buff['tot_owned']):
            self.sellp_l.config(text='Current Selling Price: \t' + cost)
            self.profit_l.config(text="PROFIT-LOSS: \t" + str(pol))
            self.sell_stock_b.config(command=self.sell_stock,
                                     text='Sell Stock')
            showinfo(message=
                     'Everthing is ok, \nClicking Sell will execute the trade')
            self.sell_stock_b.config(state='normal')

    def buy_stock(self):
        '''Finally Executes the transaction and asks the user for conformation one last time'''
        name = self.stock_name.get()
        li = self.main.shares_dict[name]

        for i in range(len(self.main.p_user_dict)):
            if name == self.main.p_user_dict[i]['name']:
                index = i
        req = int(self.amount.get())
        tot_cost = req * int(li['cost'])
        self.main.shares_dict[name]['tot_sold'] = str(
            int(self.main.shares_dict[name]['tot_sold']) + req)
        self.main.p_user_dict[index]['tot_owned'] = str(
            int(self.main.p_user_dict[index]['tot_owned']) + req)
        self.main.p_user_dict[index]['money_spent'] = str(
            int(self.main.p_user_dict[index]['money_spent']) + tot_cost)
        self.main.users_dict[
            self.main.present_user][index] = self.main.p_user_dict[index]
        balance = int(self.main.accounts[self.main.present_user]['balance'])
        self.main.accounts[self.main.present_user]['balance'] = str(balance -
                                                                    tot_cost)
        self.cost_l.config(text='Cost: ')

        showinfo(
            message='You have just bought %s of the stock %s at the price %s' %
            (str(req), name, str(tot_cost)))
        self.stock_name.set('')
        self.main.show_frame(VIEW_STOCK, RETAIL_PAGE)
        self.back_fb()

    def sell_stock(self):
        '''Asks the user for conformation and then completes the transaction
        of selling, at this point the profit field is
        also updated'''
        name = self.stock_name.get()
        req = int(self.amount.get())

        li = self.main.p_user_dict
        for i in range(len(li)):
            if name == li[i]['name']:
                ok = True
                buff = i

        tot_cost = req * int(self.main.shares_dict[name]['cost'])
        try:
            spent = req * float(
                self.main.p_user_dict[buff]['money_spent']) / int(
                    self.main.p_user_dict[buff]['tot_owned'])
        except ZeroDivisionError:
            spent = 0
        self.main.shares_dict[name]['tot_sold'] = str(
            int(self.main.shares_dict[name]['tot_sold']) - req)
        self.main.p_user_dict[buff]['tot_owned'] = str(
            int(self.main.p_user_dict[buff]['tot_owned']) - req)
        pol = tot_cost - spent
        diff = int(self.main.p_user_dict[buff]['money_spent']) - tot_cost
        self.main.p_user_dict[buff]['money_spent'] = str(
            diff) if diff > 0 else '0'
        self.main.users_dict[self.main.present_user] = self.main.p_user_dict
        profit = int(self.main.accounts[self.main.present_user]['profit'])
        self.main.accounts[self.main.present_user]['profit'] = str(
            int(profit + pol))
        balance = int(self.main.accounts[self.main.present_user]['balance'])
        self.main.accounts[self.main.present_user]['balance'] = str(balance +
                                                                    tot_cost)
        self.retail_back_b.grid_forget()
        self.profit_l.config(text='PROFIT/LOSS: ')
        self.sellp_l.config(text='Current selling price: ')
        self.main.show_frame(VIEW_STOCK, RETAIL_PAGE)
        self.back_fs()
Esempio n. 10
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)
Esempio n. 11
0
    def new_entry(self):
        # sprawdzam czy mam wiecej niz 1 wpis i moge wyliczać stan licznikow
        count = Woda.fetchone(self)

        # pola do wpisywania danych
        data_odczytu = tk.Entry(self.frame2, width=5)
        data_odczytu.config(font=("Courier", 8))
        data_odczytu.grid(row=5, column=1, padx=4, sticky='WE')

        rok = tk.Entry(self.frame2, width=5)
        rok.config(font=("Courier", 8))
        rok.grid(row=5, column=2, padx=4, sticky='WE')

        choices = [
            'Grudzień/Styczeń', 'Luty/Marzec', 'Kwiecień/Maj',
            'Czerwiec/Lipiec', 'Sierpień/Wrzesień', 'Październik/Listopad'
        ]
        # variable = StringVar(self.root)
        #
        # variable.set('Grudzień/Styczeń')
        miesiace = Combobox(self.frame2, width=5, values=choices)
        miesiace.current(0)
        miesiace.config(font=("Courier", 8))
        miesiace.grid(row=5, column=3, padx=4, sticky='WE')

        ldom = tk.Entry(self.frame2, width=5)
        ldom.config(font=("Courier", 8))
        ldom.grid(row=5, column=4, padx=4, sticky='WE')

        lgora = tk.Entry(self.frame2, width=5)
        lgora.config(font=("Courier", 8))
        lgora.grid(row=5, column=5, padx=4, sticky='WE')

        lgabinet = tk.Entry(self.frame2, width=5)
        lgabinet.config(font=("Courier", 8))
        lgabinet.grid(row=5, column=6, padx=4, sticky='WE')

        if count[0] == 0:
            self.gora = tk.Entry(self.frame2, width=5)
            self.gora.config(font=("Courier", 8))
            self.gora.grid(row=5, column=7, padx=4, sticky='WE')

            self.gabinet = tk.Entry(self.frame2, width=5)
            self.gabinet.config(font=("Courier", 8))
            self.gabinet.grid(row=5, column=8, padx=4, sticky='WE')

            self.dol = tk.Entry(self.frame2, width=5)
            self.dol.config(font=("Courier", 8))
            self.dol.grid(row=5, column=9, padx=4, sticky='WE')

            self.dom = tk.Entry(self.frame2, width=5)
            self.dom.config(font=("Courier", 8))
            self.dom.grid(row=5, column=10, padx=4, sticky='WE')

            confirm_button = Button(
                self.frame2,
                text="ZAPISZ",
                command=lambda: self.submit(data_odczytu, rok, miesiace, ldom,
                                            lgora, lgabinet))
        else:
            confirm_button = Button(
                self.frame2,
                text="ZAPISZ",
                command=lambda: self.submit(data_odczytu, rok, miesiace, ldom,
                                            lgora, lgabinet))
        confirm_button.grid(row=5, column=11)

        # modify entry
        modify_button = tk.Button(self.frame2,
                                  text='NR ID DO ZMIANY',
                                  width=14,
                                  command=lambda: self.change_entry('water'))
        modify_button.config(font=("Courier", 8))
        modify_button.grid(row=18, column=1, sticky='WE', padx=4)

        self.modify_entry = tk.Entry(self.frame2, text='ZMIEŃ', width=6)
        self.modify_entry.config(font=("Courier", 8))
        self.modify_entry.grid(row=18, column=0, sticky='WE', padx=4)
Esempio n. 12
0
eDto.config(width=2)

lCdad = Label(framePropiedad,
              text="Ciudad",
              padx=5,
              pady=15,
              bg="#B2DFDB",
              fg="#000000")
lCdad.grid(column=0, row=2)

ciudades = ('Mar del Plata', 'Batan', 'Santa Clara', 'Miramar', 'Necochea')

eCdad = Combobox(framePropiedad, state='readonly', values=ciudades)
eCdad.current(0)
eCdad.grid(column=1, row=2, padx=5, pady=15)
eCdad.config(foreground="#e0f2f1", background="#e0f2f1")

#frame para tipo de propiedad

frameTipo = Frame(frameDatos)
frameTipo.pack(fill="both")
frameTipo.config(padx=10, pady=25, bg="#B2DFDB", relief=RAISED, borderwidth=1)

tipo = IntVar()
tipo.set(1)
casa = Radiobutton(frameTipo,
                   text="Casa",
                   value=1,
                   variable=tipo,
                   bg="#B2DFDB",
                   fg="#000000")
Esempio n. 13
0
class FormAsistencias(Curso, Form):

    def __init__(self):
        Curso.__init__(self)
        Form.__init__(self)

        self.id_curso = None
        self.set_title("Asistencias")

        fieldsFrame = Frame(self.root, padding=10)
        fieldsFrame.grid(row=0, column=0, padx=10, pady=10)

        lbl_date = Label(fieldsFrame, text="Seleccione la fecha:", width=20)
        lbl_date.grid(row=0, column=0, columnspan=20)

        self.date = StringVar()
        self.cb_date = Combobox(fieldsFrame, textvariable=self.date, width=36,
                                state="readonly")
        self.cb_date.grid(row=1, column=0, columnspan=36, pady=(5,10))

        lbl_inscriptos = Label(fieldsFrame, text="Seleccione los inscriptos que asistieron:", width=40)
        lbl_inscriptos.grid(row=2, column=0, columnspan=40)

        self.listaPersonas = Listbox(fieldsFrame, highlightthickness=0, selectmode="extended", 
                                     height=25, width=40)
        self.listaPersonas.grid(row=3, column=0, columnspan=40, pady=(5,10))

        btn_aceptar = Button(fieldsFrame, text="Aceptar", width=16,
                             command=lambda: self.update_asistencia())
        btn_aceptar.grid(row=4, column=0, columnspan=16)
        
        btn_cancelar = Button(fieldsFrame, text="Cancelar", width=16,
                              command=self.hide)
        btn_cancelar.grid(row=4, column=26, columnspan=16)

    def update_asistencia(self):
        asistieron = self.listaPersonas.curselection()
        inscriptos = [item.strip().split(" ")[0] for item in self.listaPersonas.get(0, 'end')]
        date = self.date.get()
        curso = self.id_curso

        for index, inscripto in enumerate(inscriptos):
            super().update_asistencia(date, inscripto, curso, (True if index in asistieron else False))

        self.hide()

    def get_all(self):
        return self.get_asistencias(self.id_curso)

    def show(self, id_curso):
        self.id_curso = id_curso

        values = self.get_dates(self.id_curso)
        self.cb_date.config(values=values)
        self.cb_date.current(0)

        data = self.get_miembros(self.id_curso)["cursantes"]["data"]
        
        for i, row in enumerate(list(data)):
            iD, name = row[0], f"{row[1]}, {row[2]}".upper()
            self.listaPersonas.insert(i, "   {:>4d}       {:<40s}".format(iD, name))

        super().show()

    def hide(self):
        self.listaPersonas.delete(0, 'end')

        super().hide()
Esempio n. 14
0
def existing_bill(bill_to_edit):
    bloc_root_buttons()
    window_bill_update = Toplevel()
    x = main_window_of_gui.winfo_x()
    y = main_window_of_gui.winfo_y()
    w = main_window_of_gui.winfo_width()
    h = main_window_of_gui.winfo_height()
    window_bill_update.geometry("%dx%d+%d+%d" % (w, h, x, y))
    window_bill_update.title("Editer une facture existente")
    window_bill_update.wm_attributes("-topmost", 1)
    label_work_selection = Label(window_bill_update,
                                 text="Type de travaux :",
                                 width=15)
    label_work_selection.grid(column=0, row=0, pady=5)
    combo_work_selection = Combobox(window_bill_update,
                                    values=LIST_TYPE_OF_WORK)
    combo_work_selection.grid(column=1, row=0, columnspan=2, pady=5)
    combo_work_selection.set(bill_to_edit.work_type)
    combo_work_selection.config(state="disabled")
    label_company_selection = Label(window_bill_update,
                                    text="Nom de l'entreprise :",
                                    width=15)
    label_company_selection.grid(column=0, row=1, pady=5)
    combo_company_selection = Combobox(window_bill_update,
                                       values=LIST_OF_COMPANIES)
    combo_company_selection.grid(column=1, row=1, columnspan=2, pady=5)
    combo_company_selection.set(bill_to_edit.company_name)
    combo_company_selection.config(state="disabled")
    label_price = Label(window_bill_update, text="Prix :", width=15)
    label_price.grid(column=0, row=2, pady=5)
    entry_price = Entry(window_bill_update, width=23)
    entry_price.grid(column=1, row=2, columnspan=2, pady=5)
    entry_price.insert(0, bill_to_edit.price)
    label_start_date = Label(window_bill_update,
                             text="Date de debut :",
                             width=15)
    label_start_date.grid(column=0, row=3, pady=5)
    entry_start_date = Entry(window_bill_update, width=23)
    entry_start_date.insert(0, bill_to_edit.start_date)
    entry_start_date.grid(column=1, row=3, columnspan=2, pady=5)
    label_end_date = Label(window_bill_update, text="Date de fin :", width=15)
    label_end_date.grid(column=0, row=4, pady=5)
    entry_end_date = Entry(window_bill_update, width=23)
    entry_end_date.insert(0, bill_to_edit.end_date)
    entry_end_date.grid(column=1, row=4, columnspan=2, pady=5)
    label_status = Label(window_bill_update,
                         text="Etat du payment :",
                         width=15)
    label_status.grid(column=0, row=5, pady=5)
    var_payment_status = StringVar()
    var_payment_status.set(bill_to_edit.payment_status)
    dropdown_payment_status = OptionMenu(window_bill_update,
                                         var_payment_status,
                                         *LIST_payment_STATUS)
    dropdown_payment_status.grid(column=1, row=5, columnspan=2, pady=5)
    dropdown_payment_status.config(width=18)
    label_comment = Label(window_bill_update, text="Commentaires :", width=15)
    label_comment.grid(column=3, row=0, pady=5)
    text_comment = Text(window_bill_update, width=60, height=10)
    text_comment.grid(column=3, row=1, rowspan=5, pady=5)
    text_comment.insert(END, bill_to_edit.comment)
    row_placement = bill_to_edit.row_placement
    data_entries = [
        combo_work_selection, combo_company_selection, text_comment,
        entry_start_date, entry_end_date, entry_price, var_payment_status,
        row_placement
    ]
    button_confirm_bill_update = Button(
        window_bill_update,
        text="Confirmer",
        width=10,
        height=3,
        command=lambda: confirm_bill_update(data_entries, window_bill_update))
    button_confirm_bill_update.grid(column=0, row=8, pady=5)
    button_cancel_bill_update = Button(
        window_bill_update,
        text="Annuler",
        width=10,
        height=3,
        command=lambda: cancel_current_window(window_bill_update))
    button_cancel_bill_update.grid(column=2, row=8, pady=5)
    button_cancel_bill_update.bind(
        "<Destroy>", toplevel_was_closed
    )  # if bind on toplevel, the destruction of all widgets in toplevel trigers the function
Esempio n. 15
0
class Movie_app:
    def __init__(self):
        self.win=Tk()
        self.win.title(" VIP视频破解工具")
        self.creat_res()
        self.creat_radiores()
        self.config()
        self.page=1
        self.p=Pro()
        self.win.resizable(0,0) #防止用户调整尺寸
        curWidth = 600
        curHight = 520
        # 获取屏幕宽度和高度
        scn_w, scn_h = self.win.maxsize()
        # 计算中心坐标
        cen_x = (scn_w - curWidth) / 2
        cen_y = (scn_h - curHight) / 2
        # 设置窗口初始大小和位置
        size_xy = '%dx%d+%d+%d' % (curWidth, curHight, cen_x, cen_y)
        self.win.geometry(size_xy)
        self.win.mainloop()


    def creat_res(self):
        #Menu菜单
        menu = tk.Menu(self.win)
        self.win.config(menu = menu)
        moviemenu = tk.Menu(menu,tearoff = 0)
        menu.add_cascade(label = '友情链接', menu = moviemenu)
        downmenu = tk.Menu(menu,tearoff = 0)
        #各个网站链接
        moviemenu.add_command(label = '网易公开课',command = lambda :webbrowser.open('http://open.163.com/'))
        moviemenu.add_command(label = '腾讯视频',command = lambda :webbrowser.open('http://v.qq.com/'))
        moviemenu.add_command(label = '搜狐视频',command = lambda :webbrowser.open('http://tv.sohu.com/'))
        moviemenu.add_command(label = '芒果TV',command = lambda :webbrowser.open('http://www.mgtv.com/'))
        moviemenu.add_command(label = '爱奇艺',command = lambda :webbrowser.open('http://www.iqiyi.com/'))
        moviemenu.add_command(label = 'PPTV',command = lambda :webbrowser.open('http://www.bilibili.com/'))
        moviemenu.add_command(label = '优酷',command = lambda :webbrowser.open('http://www.youku.com/'))
        moviemenu.add_command(label = '乐视',command = lambda :webbrowser.open('http://www.le.com/'))
        moviemenu.add_command(label = '土豆',command = lambda :webbrowser.open('http://www.tudou.com/'))
        moviemenu.add_command(label = 'A站',command = lambda :webbrowser.open('http://www.acfun.tv/'))
        moviemenu.add_command(label = 'B站',command = lambda :webbrowser.open('http://www.bilibili.com/'))

        self.temp=StringVar()#url地址
        self.temp2=StringVar()
        self.search=StringVar()#搜索
        self.t1=StringVar()#通道
        self.t3=StringVar()#爱奇艺,优酷,PPTV
        self.La_title=Label(self.win,text="第三方视频地址:")
        self.La_way=Label(self.win,text="选择视频解码通道:")
        self.La_mc=Label(self.win,text="关键字搜索:")
        #控件内容设置
        self.numberChosen = Combobox(self.win,width=20)
        self.numberChosen['values']=('通道一','通道二','通道三','通道四','通道五','通道六','通道七','通道八','通道九','通道十')
        self.numberChosen.config(state='readonly')
        self.numberChosen.current(0)

        self.B_play=Button(self.win,text="播放▶")
        self.B_searchSimple=Button(self.win,text="关键字搜索")
        self.B_uppage=Button(self.win,text="上页")
        self.B_nextpage=Button(self.win,text="下页")
        self.B_search=Button(self.win,text="搜索全站")
        self.La_page=Label(self.win,bg="#BFEFFF")
        self.S_croll=Scrollbar(self.win)
        self.L_box=Listbox(self.win,bg="#BFEFFF",selectmode=SINGLE)
        self.E_address=Entry(self.win,textvariable=self.temp)
        self.E_search=Entry(self.win,textvariable=self.search)
        self.label_explain = Label(self.win, fg = 'red', font = ('楷体',12), text = '\n注意:支持大部分主流视频网站的视频播放!\n此软件仅用于交流学习,请勿用于任何商业用途!\n在上面输入框输入现在主流视频网站网页地址\n点击播放弹出浏览器可以解码播放')
        self.label_explain.place(x=10,y=90,width=360,height=90)
        self.La_title.place(x=1,y=50,width=90,height=30)
        self.E_address.place(x=100,y=50,width=200,height=30)
        self.B_play.place(x=310,y=50,width=60,height=30)
        self.La_way.place(x=10,y=10,width=100,height=30)
        self.numberChosen.place(x=120,y=10,width=180,height=30)
        self.E_search.place(x=90,y=200,width=160,height=30)
        self.B_searchSimple.place(x=280,y=200,width=80,height=30)
        self.La_mc.place(x=10,y=200,width=70,height=30)
        self.B_search.place(x=252,y=240,width=100,height=30)
        self.L_box.place(x=10,y=280,width=252,height=230)
        self.S_croll.place(x=260,y=280,width=20,height=230)
        self.B_uppage.place(x=10,y=240,width=50,height=30)
        self.B_nextpage.place(x=180,y=240,width=50,height=30)
        self.La_page.place(x=80,y=240,width=90,height=28)

    def creat_radiores(self):
        self.movie=StringVar()#电影
        self.S_croll2=Scrollbar()#分集
        self.La_pic=Label(self.win,bg="#E6E6FA")
        self.La_movie_message=Listbox(self.win,bg="#7EC0EE")
        self.R_movie=Radiobutton(self.win,text="电影",variable=self.movie,value="m")
        self.tv=Radiobutton(self.win,text="电视剧",variable=self.movie,value="t")
        self.zhongyi=Radiobutton(self.win,text="综艺",variable=self.movie,value="z")
        self.dongman=Radiobutton(self.win,text="动漫",variable=self.movie,value="d")
        self.jilupian=Radiobutton(self.win,text="排行榜",variable=self.movie,value="j")
        self.movie.set('m')
        self.B_view=Button(self.win,text="查看")
        self.B_info=Button(self.win,text="使用说明")
        self.B_clearbox=Button(self.win,text="清空列表")
        self.B_add=Button(self.win,text="打开浏览器观看")
        self.R_movie.place(x=290,y=280,width=80,height=30)
        self.B_view.place(x=290,y=430,width=70,height=30)
        self.B_add.place(x=370,y=255,width=100,height=30)
        self.B_clearbox.place(x=500,y=255,width=70,height=30)
        self.tv.place(x=290,y=310,width=80,height=30)
        self.zhongyi.place(x=290,y=340,width=80,height=30)
        self.dongman.place(x=290,y=370,width=80,height=30)
        self.jilupian.place(x=290,y=400,width=80,height=30)
        self.La_movie_message.place(x=370,y=290,width=200,height=220)
        self.La_pic.place(x=370,y=10,width=200,height=240)
        self.B_info.place(x=290,y=470,width=70,height=30)
        self.S_croll2.place(x=568,y=290,width=20,height=220)

    def show_info(self):
        msg="""
        1.输入视频播放地址,即可播放
          下拉选择可切换视频源
        2.选择视频网,选择电视剧或者电影,
          搜索全网后选择想要看得影片,点
          查看,在右方list里选择分集视频
          添加到播放列表里点选播放
        3.复制网上视频连接
          点击播放即可(VIP视频也可以免费播放)
        4.此软件仅用于交流学习
          请勿用于任何商业用途!
        5.此软件内容来源于互联网
          此软件不承担任何由于内容的合法性及
          健康性所引起的争议和法律责任。
        6.欢迎大家对此软件内容侵犯版权等
          不合法和不健康行为进行监督和举报
        """
        messagebox.showinfo(title="使用说明",message=msg)

    def config(self):
        self.t1.set(True)
        self.B_play.config(command=self.play_url_movie)
        self.B_search.config(command=self.search_full_movie)
        self.B_info.config(command=self.show_info)
        self.S_croll.config(command=self.L_box.yview)
        self.L_box['yscrollcommand']=self.S_croll.set
        self.S_croll2.config(command=self.La_movie_message.yview)
        self.La_movie_message['yscrollcommand']=self.S_croll2.set
        self.B_view.config(command=self.view_movies)
        self.B_add.config(command=self.add_play_list)
        self.B_clearbox.config(command=self.clear_lisbox2)
        self.B_uppage.config(command=self.uppage_)
        self.B_nextpage.config(command=self.nextpage_)
        self.B_searchSimple.config(command=self.searchSimple)

    def uppage_(self):
        print('---------上一页---------')
        self.page-=1
        print(self.page)
        if self.page<1:
            self.page=1
        self.search_full_movie()
    def nextpage_(self):
        print('----------下一页--------')
        self.page+=1
        print(self.page)
        self.search_full_movie()

    def clear_lisbox(self):
        self.L_box.delete(0,END)

    def clear_lisbox2(self):
        self.La_movie_message.delete(0,END)

    def search_full_movie(self):
        print("-----search----")
        self.La_page.config(text="当前页:{}".format(self.page))
        self.clear_lisbox()
        try:
            movie_url, movie_title, movie_src_pic=self.p.get_movie_res(self.t3.get(),self.movie.get(),self.page)
            self.movie_dic={}
            for i,j,k in zip(movie_title,movie_url,movie_src_pic):
                self.movie_dic[i]=[j,k]
            for title in movie_title:
                self.L_box.insert(END,title)
            print(self.movie_dic)
            return self.movie_dic
        except:
            messagebox.showerror(title='警告',message='请选择电影或者电视剧')

    def add_play_list(self):
        print('---------playlist----------')
        # print(self.movie_dic)
        if self.La_movie_message.get(self.La_movie_message.curselection())=="":
            messagebox.showwarning(title="警告",message='请在列表选择影片')
        else:
            print("电影名字:",self.La_movie_message.get(self.La_movie_message.curselection()))
            # self.temp.set('http://www.133kp.com' + self.new_more_dic[self.La_movie_message.get(self.La_movie_message.curselection())])
            webbrowser.open('http://www.133kp.com' + self.new_more_dic[self.La_movie_message.get(self.La_movie_message.curselection())])


    def view_pic(self,pic_url):
        print('--------viewpic---------')
        pa_url_check=r'//.+[.]jpg'
        if re.match(pa_url_check,pic_url):
            print("ok")
            pic_url="http:"+pic_url
        print(pic_url)
        data=requests.get(pic_url).content
        # data=urlopen(pic_url).read()
        io_data=io.BytesIO(data)
        self.img=Image.open(io_data)
        self.u=ImageTk.PhotoImage(self.img)
        self.La_pic.config(image=self.u)

    def view_movies(self):
        print("--------viewmovie----------")
        self.clear_lisbox2()
        cur_index=self.L_box.curselection()
        print(self.L_box.get(cur_index))
        self.new_more_dic=self.p.get_more_tv_urls(self.movie_dic[self.L_box.get(cur_index)][0],self.t3.get(),self.movie.get())
        print(self.new_more_dic)
        for i,fenji_url in self.new_more_dic.items():
            self.La_movie_message.insert(END, i)
        self.view_pic(self.movie_dic[self.L_box.get(self.L_box.curselection())][1])#加载图片

    def play_url_movie(self):
        print("--------ok-----------")
        # print(type(self.t1.get()),self.t1.get())
        if self.temp.get()=="":
            messagebox.showwarning(title="警告",message="请先输入视频地址")
        else:
            if self.numberChosen.get()!="":
                self.p.play_movie(self.temp.get(),self.numberChosen.get())
            else:
                messagebox.showwarning(title='警告',message='请选择通道')
    def searchSimple(self):
        if self.search.get()=="":
            messagebox.showwarning(title="警告",message="请先输入搜索关键字")
        else:    
            self.clear_lisbox()  
            url = 'https://www.133kp.com//index.php?m=vod-search&wd={}'.format(self.search.get())
            res=requests.get(url=url,headers=self.p.header).content.decode('utf-8')
            html=etree.HTML(res)
            movie_size=html.xpath('//input[@class="pagego"]/@size')
            list = [] 
            for s in range(0, int(movie_size[0])):
                url = 'https://www.133kp.com/vod-search-pg-{}-wd-{}.html'.format(s+1,self.search.get())
                list.append(self.p.simpleSearch(url)) 
            # movie_url, movie_title, movie_src_pic=self.p.simpleSearch(self.search.get())
            self.movie_dic={}
            i = 0
            for b in list:
                for i,j,k in zip(b[0],b[1],b[2]):
                    self.movie_dic[i]=[j,re.findall(r'[(](.*?)[)]', k)[0]]
                for title in b[0]:
                    self.L_box.insert(END,title)
            print(self.movie_dic)
Esempio n. 16
0
        def refresh():
            style.configure("Treeview",
                            font="calibri 17 bold",
                            rowheight=40,
                            anchor="center",
                            width=200,
                            fill='y')
            style.configure("Treeview.Heading", font="calibri 20 underline")
            t = Treeview(r,
                         height=height // 60,
                         style="Treeview",
                         cursor="hand2")
            t['columns'] = ('Id', 'Item', 'Price')
            t.column('Id', width=width // 9, anchor='center')
            t.column('Item', width=width // 3, anchor="center")
            t.column('Price', width=width // 7, anchor="center")
            t.column('#0', width=width // 5, anchor='center')
            t.heading('Id', text="Id")
            t.heading('Item', text="Items")
            t.heading('Price', text="Price")

            t.insert('', 'end', 'dailyExpenses', text="Daily Expenses")
            t.insert('', 'end', 'monthlyExpenses', text="Monthly Expenses")
            c = ['monthlyExpenses', 'dailyExpenses']
            cbL = Label(
                r,
                text="Select Month ",
                font="calibri 20 bold",
                bg=bg1,
            )
            cbL.place(x=width // 2.9, y=height // 15)
            cb = Combobox(r, width=15, font="calibri 20 bold")
            cb.config(state="readonly")
            cb['values'] = ("January", "February", "March", "April", "May",
                            "June", "July", "August", "Septembor", "October",
                            "Novembor", "Decembor")
            cb.place(x=width // 2.2, y=height // 15)
            cbButton = Button(r,
                              text="Show",
                              font="calibri 15 bold",
                              bd=0,
                              bg='yellow',
                              activebackground=bg1,
                              width=10,
                              command=lambda: getMonth(cb, t),
                              cursor="hand2")
            cbButton.place(x=width // 1.6, y=height // 15)

            for x in range(2):
                db.execute(
                    f"select * from expenses where boolean={x} and instr(date,'{today.year}-{self.globalVarforMonth}')>0"
                )
                a = db.fetchall()
                print(a)
                for i in a:
                    try:
                        t.insert(f'{c[x]}',
                                 'end',
                                 f'{i[2] + str(i[1])}',
                                 text=f"{i[2]}")
                        db.execute(
                            f"select id,item,price from expenses where boolean={x} and date=date('{i[2]}')"
                        )
                        a = db.fetchall()
                        for j in a:
                            t.insert(f'{i[2] + str(i[1])}',
                                     'end',
                                     values=(f"{j[0]}", f"{j[1]}", f"{j[2]}"))
                        db.execute(
                            f"select sum(price) from expenses where boolean={x} and date=date('{i[2]}')"
                        )
                        total = db.fetchone()
                        t.insert(f'{i[2] + str(i[1])}',
                                 'end',
                                 text="Total",
                                 values=("", '', total))
                    except:
                        pass
            db.execute(
                f"select sum(price) from expenses where boolean=1 and instr(date,'{today.year}-{self.globalVarforMonth}')>0"
            )
            total = db.fetchone()
            t.insert('dailyExpenses',
                     'end',
                     text="Total Daily Expenses",
                     values=("", '', total))
            db.execute(
                f"select sum(price) from expenses where boolean=0  and instr(date,'{today.year}-{self.globalVarforMonth}')>0"
            )
            total1 = db.fetchone()
            t.insert('monthlyExpenses',
                     'end',
                     text="Total Monthly Expenses",
                     values=("", '', total1))
            db.execute(
                f"select sum(price) from expenses where instr(date,'{today.year}-{self.globalVarforMonth}')>0"
            )
            allExpenses = db.fetchall()
            t.insert('',
                     'end',
                     text="All Expenses ",
                     values=("", "", allExpenses))
            t.place(x=width // 9, y=height // 6)
            delete_button1 = Button(r,
                                    text="delete",
                                    image=delete,
                                    bd=0,
                                    command=lambda: delete_button(t, r),
                                    activebackground=bg1,
                                    bg=bg1)
            delete_button1.place(x=width // 40, y=height // 3)

            update = Button(r,
                            image=updateExpenses,
                            bd=0,
                            activebackground=bg1,
                            bg=bg1,
                            command=lambda: updateButton(t, r, update))
            update.place(x=width // 40, y=height // 3.8)

            insert = Button(r,
                            text="delete",
                            image=insertExpenses,
                            bd=0,
                            command=lambda: insertFunc(insert, r, t),
                            activebackground=bg1,
                            bg=bg1)
            insert.place(x=width // 40, y=height // 5)
class billing:
    def __init__(self, frame):
        self.myframe = Toplevel(frame)
        self.myframe.title("Billing")
        self.myframe.geometry("%dx%d+%d+%d" % (1300, 600, 50, 50))
        self.myframe.option_add("*tearOff", False)

        # self.srno=1
        t1 = Label(self.myframe, text="Customer ID").place(x=50, y=50)
        t2 = Label(self.myframe, text="Customer Name").place(x=300, y=50)
        t3 = Label(self.myframe, text="Room No").place(x=50, y=80)
        t4 = Label(self.myframe, text="Room Type").place(x=300, y=80)
        t5 = Label(self.myframe, text="Category").place(x=50, y=110)
        t6 = Label(self.myframe, text="Item").place(x=300, y=110)
        t7 = Label(self.myframe, text="Quantity").place(x=50, y=140)

        self.e1 = Entry(self.myframe)  #For Customer ID
        self.e2 = Entry(self.myframe)  #For Customer Name
        self.e3 = Entry(self.myframe)  #For Room No
        self.e4 = Entry(self.myframe)  #For Room Type
        self.e5 = Entry(self.myframe)  # For Quantity

        # self.b1=Button(self.myframe,text="Fetching...")
        self.b2 = Button(self.myframe, text="Add Item")

        self.mycatselect = StringVar()
        self.myitemselect = StringVar()

        self.c1 = Combobox(self.myframe, textvariable=self.mycatselect)
        self.c1.set("Choose Category")

        self.c2 = Combobox(self.myframe, textvariable=self.myitemselect)
        self.c2.set("Choose Item")

        mytablearea = Frame(self.myframe, width=100, height=500)
        scrollbarx = Scrollbar(mytablearea, orient=HORIZONTAL)
        scrollbary = Scrollbar(mytablearea, orient=VERTICAL)
        self.mytable = ttk.Treeview(self.myframe,
                                    columns=('srno', 'Item_no', 'Item_Name',
                                             'Price', 'quantity', 'amount'),
                                    xscrollcommand=scrollbarx.set,
                                    yscrollcommand=scrollbary.set)

        scrollbarx.config(command=self.mytable.xview)
        scrollbary.config(command=self.mytable.yview)

        scrollbarx.pack(side=BOTTOM, fill=X)
        scrollbary.pack(side=RIGHT, fill=Y)
        #'srno','Item no','Item Name','Price','quantity','amount'
        self.mytable.heading("srno", text="Srno")
        self.mytable.heading("Item_no", text="Item No.")
        self.mytable.heading("Item_Name", text="Item Name")
        self.mytable.heading("Price", text="Price")
        self.mytable.heading("quantity", text="Quantity")
        self.mytable.heading("amount", text="Amount")

        self.mytable.column('#0', stretch=NO, minwidth=0, width=0)
        self.mytable.column('#1', stretch=NO, width=50)
        self.mytable.column('#2', stretch=NO, width=80)
        self.mytable.column('#3', stretch=NO, width=150)
        self.mytable.column('#4', stretch=NO, width=100)
        self.mytable.column('#5', stretch=NO, width=80)
        self.mytable.column('#6', stretch=NO, width=100)

        self.e1.place(x=130, y=50)  # For Customer ID
        self.e2.place(x=400, y=50)  # For Customer Name
        self.e3.place(x=130, y=80)  # For Room No
        self.e4.place(x=400, y=80)  # For Room Type
        self.e5.place(x=130, y=140)  # For Room Type

        self.c1.place(x=130, y=110)
        self.c2.place(x=400, y=110)

        # self.b1.place(x=550,y=50)
        self.b2.place(x=350, y=140)

        self.mytable.place(x=50, y=180)

        self.get_cat()
        self.e1.bind("<FocusOut>", lambda e: self.get_cus_info())
        self.c1.bind("<<ComboboxSelected>>", lambda e: self.get_items())
        self.c1.bind("<Enter>", lambda e: self.get_cat())
        self.b2.bind("<Enter>", lambda e: self.get_item_price())
        self.b2.bind("<Button-1>", lambda e: self.buyitems())

    def get_item_price(self):
        index = self.myitemselect.get().find(",")
        self.getid = self.myitemselect.get()[0:index]
        self.getname = self.myitemselect.get()[index + 1:]
        # self.srno=0
        try:
            mydb = pymysql.connect(host='localhost',
                                   user='******',
                                   password='',
                                   db='hotelmanagementdb')
            with mydb.cursor() as myconn:
                myconn.execute("select Price from items where item_no=%s",
                               (self.getid))
                myresult = myconn.fetchone()
                self.myprice = myresult[0]
                # self.srno=self.srno+1
        except Exception as ex:
            messagebox.showerror(
                "Database Error",
                "Error Occured during Fetching a Price of Item due To \n " +
                str(ex))

    def buyitems(self):

        mypurchase = []
        # print("Item no: "+self.getid)
        # print("Item name: " + self.getname)
        # print("Price: " + str(self.myprice))
        # print("Quantity: " + self.e5.get())
        total_amt = str(self.myprice * Decimal(self.e5.get()))
        mypurchase.append("")
        mypurchase.append(self.getid)
        mypurchase.append(self.getname)
        mypurchase.append(str(self.myprice))
        mypurchase.append(self.e5.get())
        mypurchase.append(total_amt)
        # print(mypurchase)
        self.mytable.insert('', END, values=mypurchase)

    def get_cus_info(self):
        myresult = []
        self.e2.config(state='normal')
        self.e3.config(state='normal')
        self.e4.config(state='normal')
        try:
            mydb = pymysql.connect(host='localhost',
                                   user='******',
                                   password='',
                                   db='hotelmanagementdb')
            with mydb.cursor() as myconn:
                myconn.execute(
                    "select customer_name,room_no,room_type from room_history where customer_id = %s",
                    (self.e1.get()))
                mydb.commit()
                myresult = myconn.fetchone()
                # print(myresult)
                self.e2.delete(0, END)
                self.e3.delete(0, END)
                self.e4.delete(0, END)

                self.e2.insert(0, myresult[0])
                self.e3.insert(0, myresult[1])
                self.e4.insert(0, myresult[2])

                self.e2.config(state='readonly')
                self.e3.config(state='readonly')
                self.e4.config(state='readonly')
        except Exception as e:
            messagebox.showerror("Database Error",
                                 "Error Occured Due To : " + str(e),
                                 parent=self.myframe)

    def get_cat(self):
        mycat = []
        try:
            mydb = pymysql.connect(host='localhost',
                                   user='******',
                                   password='',
                                   db='hotelmanagementdb')
            with mydb.cursor() as myconn:
                myconn.execute("select * from category")
                mydb.commit()
                myresult = myconn.fetchall()
                for i in range(len(myresult)):
                    mycat.append(str(myresult[i][0]) + "," + myresult[i][1])
                self.c1.config(values=mycat)
        except Exception as e:
            messagebox.showerror("Database Error",
                                 "Error Occured Due To : " + str(e),
                                 parent=self.myframe)

    def get_items(self):
        myitem = []
        index = self.mycatselect.get().find(",")
        getid = self.mycatselect.get()[index + 1:]
        try:
            # print(getid)
            mydb = pymysql.connect(host='localhost',
                                   user='******',
                                   password='',
                                   db='hotelmanagementdb')
            with mydb.cursor() as myconn:
                myconn.execute(
                    "select item_no,item_name from items where cat_name = %s",
                    (getid))
                mydb.commit()
                myresult = myconn.fetchall()
                for i in range(len(myresult)):
                    myitem.append(str(myresult[i][0]) + "," + myresult[i][1])
                myconn.close()
            self.c2.config(values=myitem)
        #
        except Exception as e:
            messagebox.showerror("Database Error",
                                 "Error Occured Due To : " + str(e),
                                 parent=self.myframe)
Esempio n. 18
0
class View:
    def __init__(self, controller, root):
        self.controller = controller
        self.container = root
        self.colours = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd',
                        '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf']
        self.queue = queue.Queue()
        self.container.title('Scatter Simulator')
        self.selected_spectrum = ''
        self._setup()
        
        self.s = tk.Style()
        self.s.theme_use('vista')
        self.s.configure("vista.TFrame", padding=100)
           
        #print(self.s.lookup('TFrame', 'font'))
        #print(tk.Style().lookup("TButton", "font"))

    def _setup(self):
        self._createWidgets()
        self._setupLayout()
        self._addTooltips()
           
    def _createWidgets(self):
        """ This function instantiates all of the widgets.
        
        Parameters
        ----------
        None
        
        Returns
        -------
        None
        """
        self.bcolor = 'grey'
        self.bthickness = 0
        self.axis_label_fontsize = 12
        self.axis_tick_font = 8
        
        ''' Frames are leveled in a heirarchy
         a frame embedded into another frame will have a name like f1_1_2
        '''
        ''' f1 : left highest-level frame
        controls frame
        contains the user controls for loading, saving files, for changing 
        parameters of simulation, and for running simulation'''
        frame1_padding = 10
        self.f1 = tk.Frame(self.container, 
                           width=300, height=600, 
                           padding=frame1_padding)
        # f2 : middle highest-level frame
        # XPS spectra Frame
        # contains the plot of the XPS spectra, and the list of spectra
        self.f2 = tk.Frame(self.container, 
                           width=400,height=600, 
                           padding=frame1_padding)
        # f3 : right highest-level frame
        # Loss function Frame
        # contains plot of loss function, and loss functions table
        self.f3 = tk.Frame(self.container,
                           width=400,height=600, 
                           padding=frame1_padding)
        # f3_1
        # Loss function figure frame
        self.f3_1 = tk.Frame(self.f3, 
                             width=400,height=100, 
                             padding=frame1_padding)
        # f1_1
        # Loss buttons frame
        self.f1_1 = tk.Frame(self.f1, 
                             width=400,height=600, 
                             padding=frame1_padding)
        self.step2_label = tk.Label(self.f1_1, 
                                    text='1. Scatterers',
                                    font=("Helvetica", 12))
        # f1_1 
        # load spectra frame
        self.f1_2 = tk.Frame(self.f1,
                             width=400,height=200, 
                             padding=frame1_padding)
        self.step1_label = tk.Label(self.f1_2, 
                                    text='2. Spectra',
                                    font=("Helvetica", 12))
        self.btn1 = tk.Button(self.f1_2, 
                              text = "Load spectrum", 
                              width = 15, 
                              command = self.loadSpectrum)
        self.btn2 = tk.Button(self.f1_2, 
                              text = "Build spectrum",
                              width = 15, 
                              command = self.addSynthSpec)
        self.export = tk.Button(self.f1_2,
                                text = 'Export',
                                width = 15)#,
                                #command = self.exportFile)
        self.export.bind("<Button-1>", self.exportPopUp)
        
        # f1_3
        # Parameter inputs frame
        self.f1_3 = tk.Frame(self.f1, 
                             width=300, height=500, 
                             padding=frame1_padding)
        self.step3_label = tk.Label(self.f1_3, 
                                    text='3. Parameters',
                                    font=("Helvetica", 12))

        # f1_3_1
        # Parameters subframe
        self.f1_3_1 = tk.Frame(self.f1_3, width=300, height=500)
        self.inputs_frame = InputsFrame(self.f1_3_1)

        # f1_3_2
        # Variants subframe
        self.f1_3_2 = tk.Frame(self.f1_3, width=300, height=30)
                
        # f1_4
        # run simulation frame
        self.f1_4 = tk.Frame(self.f1, width=300, height=500)
        
        # f2_1
        # spectra table frame
        self.f2_1 = tk.Frame(self.f2)
        
        # Run simulation
        self.step4_label = tk.Label(self.f1_4, 
                                    text='4. Simulation',
                                    font=("Helvetica", 12))
        self.scatter_btn = tk.Button(self.f1_4, text = "Scatter", 
                                     command = self.controller.scatterSpectrum, 
                                     width=15)
        self.unscatter_btn = tk.Button(self.f1_4, 
                                       text = "Un-scatter", 
                                       command = self.controller.unScatterSpectrum,
                                       width=15)    
        self.bulk = IntVar()
        self.bulk_chk = tk.Checkbutton(self.f1_4, 
                                       text="Bulk spectrum", 
                                       variable=self.bulk)
        
        # Figure for XPS spectra
        x = []
        y = []
        params = {'xlabel':'Energy [eV]', 'ylabel': 'Intensity [cts./sec.]',
               'title':'Spectra', 'colours':self.colours}
        self.fig1 = Figure(self.f2,x,y,params)
        
        # Loss function figure (Figure2)
        params = {'xlabel':'Energy [eV]', 'ylabel':'Probability', 
               'title':'Loss Function', 'colours':self.colours}
        self.fig2 = Figure(self.f3, x,y,params)

        self.figures = [self.fig1, self.fig2]

        # XPS spectra table
        
        spec_table_params = {'table_name':'spectra', 
                             'on_double_click':'visibility',
                  'columns':[{'name':'Nr.', 
                              'width':50},
                             {'name':'Type',
                              'width':125,
                              'popup_choices':['none',
                                               'Scattered',
                                               'Unscattered']
                              },
                             {'name':'Visibility',
                              'width':120,
                              'popup_choices':['visible', 'hidden']},
                             {'name':'Edit',
                              'width':45,
                              'link':'edit'}
                             ]
                  }
        
        loss_table_params = {'table_name':'loss_function', 
                             'on_double_click':'edit',
                             'colour_keys':False,
                             'columns':[
                                     {'name':'Nr.', 'width':50},
                                     {'name':'Type','width':350}]
                             }
             
        self.spectra_table = Table(self.container,
                                   self.controller, 
                                   self.f2_1, spec_table_params)
        
        self.loss_function_table = Table(self.container,
                                         self.controller,
                                         self.f3_1, loss_table_params)
        
        self.tables = [self.spectra_table, self.loss_function_table]

        # Normalize spectra box
        self.normalize = IntVar()
        self.normalize.set(0)
        
        self.normalize_chk = tk.Checkbutton(self.f2_1, 
                                            text="Normalize", 
                                            variable=self.normalize, 
                                            command = lambda: 
                                                self.controller.changeNormalization(self.normalize.get()))
        

        # Load file of loss functions
        self.btn3 = tk.Button(self.f1_1, text="Load scatterers",
                              width=15, command=self.loadScatterers)

        # Select loss function (from loaded file)
        self.load_loss_frame = tk.Frame(self.f1_1, width=400,height=600)
        self.load_loss_label = tk.Label(self.load_loss_frame, 
                                        text='Select scatterer')
        self.selected_scatterer = StringVar()
        self.scatterer_choices = []
        self.cbox = Combobox(self.load_loss_frame, width=13, 
                             textvariable = self.selected_scatterer,
                             values=self.scatterer_choices)
        self.cbox.bind("<<ComboboxSelected>>", self.setCurrentScatterer)

        # Build loss function
        self.btn4 = tk.Button(self.f1_1, 
                              text = "New scatterer", 
                              width=15, 
                              command = self.newScatterer)
        # Save loss function
        self.btn5 = tk.Button(self.f1_1, 
                              text = "Save scatterer", 
                              width=15, 
                              command = self.saveScatterers)
        


        ''' This is the button for adding a new component to the loss function.
        '''
        self.add_comp_btn = tk.Label(self.f3_1, 
                                     text = "+ Add component", 
                                     relief ='raised')
        self.add_comp_btn.bind('<Button-1>', 
                               self.addComponent)
        
    def _setupLayout(self):
        self.f1.pack(side=LEFT, fill=None, anchor="nw")
        self.f1_1.pack(side=TOP, expand=False, fill=Y, anchor='center')
        self.step1_label.pack(side=TOP)
        self.f1_2.pack(side=TOP, expand=False, fill=Y, anchor='center')
        self.step2_label.pack(side=TOP)
        
        self.f1_3.pack(side=TOP, fill = None, anchor='center')
        self.step3_label.pack(side=TOP)
        self.f1_3_1.pack(side=TOP)
        self.f1_3_2.pack(side=TOP)
        
        self.f1_4.pack(side=TOP, fill = None, anchor='center')
        self.step4_label.pack(side=TOP)
        self.scatter_btn.pack(side=TOP)
        self.unscatter_btn.pack(side=TOP)
        self.bulk_chk.pack(side=TOP)
        
        self.f2.pack(side=LEFT, fill=Y, anchor='n')
        self.btn1.pack(side=TOP, fill = None)
        self.btn2.pack(side=TOP, fill = None)
        
        self.export.pack(side=TOP, fill = None)
        
        self.f2_1.pack(side=TOP, fill=Y, anchor='ne')
        self.spectra_table.table.pack(side=TOP, anchor="ne", pady=10, padx=15)
        self.normalize_chk.pack(side=TOP, anchor="ne", padx=15)
        
        self.f3.pack(side=LEFT, fill = None, anchor='n')
        self.btn3.pack(side=TOP)
        self.load_loss_frame.pack(side=TOP)
        self.load_loss_label.pack(side=TOP)
        self.cbox.pack(side=TOP)
        self.btn4.pack(side=TOP)
        self.btn5.pack(side=TOP)
        
        self.f3_1.pack(side=TOP, anchor="ne")
        self.loss_function_table.table.pack(side=TOP, anchor="ne", padx=5)
        self.add_comp_btn.pack(side=TOP, anchor="se", pady=10, padx=5)
        
    def _addTooltips(self):
        tool_tips = [[self.btn3, "This will load scatterers from a file."],
                     [self.btn4, "Create a new scatterer. \nGive it a name. \nThen build your own Loss Function"],
                     [self.btn5, "Save the scatterer you built"],
                     [self.btn1, "Load a measured spectrum"],
                     [self.btn2, "Create your own spectrum"],
                     [self.export, "Save the simulated spectra to Vamas or Excel."],
                     [self.step3_label, '''Here you can enter the parameters used in the simulation algorithm.
P is the pressure in mbar.
D is the distance between the sample and the detector.
Inel.X is the inelastic scattering cross section in nm^2
El.X is the eleastic scattering cross section.
f(Decay) are decay factors. A value of 1 means no decay.'''],
                      [self.scatter_btn, "Run the calculation to simulate inelastic scattering."],
                      [self.bulk_chk, '''Checking this box will configure the calculation to simulate the bulk signal.
In this case, P and D have no effect.'''],
                      [self.normalize_chk, '''Checking this box will normalize all spectra.'''],
                      [self.unscatter_btn, '''Run the calculation to remove inelastic scattering signal.''']
                     ]
        
        for t in tool_tips:
            CreateToolTip(t[0], self.controller.thread_pool_executer, t[1])

    def addVariantChoices(self, params):
        """ This function make radio buttons for each of the algorithm
        variants."""
        self.variant = StringVar()
        for p in params:
            tk.Radiobutton(self.f1_3_2, 
                           text=str(p), 
                           variable=self.variant, 
                           command = self.toggleVariant, 
                           value=p).pack(side=LEFT)
        
    def toggleVariant(self):
        """ This function tells the controller when the choice of Algorithm
        has changed."""
        new_var = self.variant.get()
        self.controller.toggleVariant(new_var)
        
    def buildAlgorithmFrame(self, params):
        """ This method is called by the controller.
        """
        self.inputs_frame.buildFrame(params)
    
    def loadSpectrum(self):
        file = filedialog.askopenfilename(initialdir = self.controller.datapath)
        if file:
            self.controller.loadFile(file)
            self.controller.datapath = (file.rsplit('/',maxsplit = 1)[0])
            
    def callSpecSelector(self, table_params, fig_params):
        self.specselector = SpecSelector(self.controller,
                                         table_params, 
                                         fig_params)

    def loadScatterers(self):
        def getFile():
            self.file = filedialog.askopenfilename(initialdir=self.controller.datapath,
                                              title='Select loss function file',
                                              filetypes=[('json', '*.json')])
        
        threading.Thread(target=getFile()).start()
        self.controller.loadScatterers(self.file)
        
    def setCurrentScatterer(self, event):
        label = self.selected_scatterer.get()
        self.controller.setCurrentScatterer(label)
        
    def exportPopUp(self, event):
        """
        This creates a PopUp menu on the export button.

        Parameters
        ----------
        event : event

        Returns
        -------
        None.

        """
        choices = self.controller.getExportFormats()  
        popup = PopUpMenu(self.container, choices, self.exportFile)
        popup.pop(event)
        
    def exportFile(self, file_format):
        """
        This is the callback function that is used in the file export PopUp
        menu.

        Parameters
        ----------
        file_format : STRING
            A key that identifies the desired export file format.

        Returns
        -------
        None.

        """
        file = filedialog.asksaveasfilename(initialdir=self.controller.datapath,
                                    title='Save as')
        self.controller.export(file, file_format)
        
    def saveScatterers(self):
        file = filedialog.asksaveasfilename(initialdir=self.controller.datapath,
                                            title='Save as',
                                            filetypes=[('json', '*.json')])
        
        self.controller.saveScatterers(file)
        
    def updateScattererChoices(self, choices):
        self.cbox.set('')
        self.scatterer_choices = choices
        self.cbox.config(values=self.scatterer_choices)

    def noScatterer(self):
        tkinter.messagebox.showerror('Error',
                                     'Please select an Unscattered spectrum and a Loss Function')
        
    def removeSpectrum(self, event):
        selected_item = self.spectra_table.selection()
        cur_item = self.spectra_table.item(selected_item[0])['values'][0]
        self.spectra_table.delete(selected_item[0])
        self.controller.removeSpectrum(cur_item)
        
    def removeLossComponent(self, event):
        selected_item = self.scatterers_table.selection()
        cur_item = self.scatterers_table.item(selected_item[0])['values'][0]
        self.scatterers_table.delete(selected_item[0])
        self.controller.removeLossComponent(cur_item)
        
    def addComponent(self, event):
        """ This function adds a new loss function component."""
        def setChoice(choice):
            self.controller.addComponent(choice)
        popup = Menu(self.container, tearoff=0)
        choices = self.controller.component_choices
        for i,j in enumerate(choices):
                '''This line below is a bit tricky. Needs to be done this way 
                because the i in the loop is only scoped for the loop, and 
                does not persist'''
                popup.add_command(command = lambda choice = choices[i]: 
                    setChoice(choice), label=j)
        popup.post(event.x_root, event.y_root)
        
    def addSynthSpec(self):
        """ This function calls the controller to tell it a new synthetic
        spectrum should be built.
        """
        self.selected_spectrum = len(self.spectra_table.table.get_children())-1
        self.controller.addSynthSpec()
        self.spectra_table.fillTable()
        
    def editSynthSpec(self, params):
        self.spec_builder = SpecBuilder(self.controller,params)
  
    def newScatterer(self):
        self.new_scatterer = newScatterer(self, self.controller)
Esempio n. 19
0
class AddBillDialog:
    def __init__(self, master):
        self.dialog = Toplevel(master)
        self.dialog.resizable(0, 0)
        self.dialog.title("Thêm hóa đơn")
        self.master = master
        self.headerID = "##"
        self.footerID = "##"
        self.tempPrice = IntVar()
        self.unitPrice = 0
        self.amountOfType = 0
        self.data = Database()
        self.listItem = self.data.getItemList()
        self.drawDialog(self.dialog)
        self.dialog.bind_all("<Escape>", self.onCancel)
        self.dialog.bind_all("<Return>", self.onAddBill)

    def drawDialog(self, dialog):
        layoutSetInfo = Frame(dialog)

        layoutMakeBill = Frame(layoutSetInfo, bd=0, highlightthickness=1)

        self.setBillInfo(layoutMakeBill)

        layoutMakeBill.pack(side=TOP, fill=BOTH, expand=True, pady=10)

        layoutButton = Frame(layoutSetInfo)
        btnAddBill = Button(layoutButton,
                            text="Thêm hóa đơn",
                            command=self.onAddBill)
        btnCancel = Button(layoutButton, text="Hủy", command=self.onCancel)

        btnAddBill.grid(row=0, column=0, columnspan=1)
        btnCancel.grid(row=0, column=1, columnspan=2)
        layoutButton.pack(side=TOP, fill=X, expand=True, pady=10)

        layoutSetInfo.pack(side=LEFT, expand=True, padx=10)

    def setBillInfo(self, parent):
        # Choose Object
        listNameItem = []
        for item in self.listItem:
            listNameItem.append(item.name)

        lblObject = Label(parent, text="Mặt hàng: ")
        self.comboObject = Combobox(parent, values=listNameItem)
        self.comboObject.bind(sequence="<<ComboboxSelected>>",
                              func=self.onChangeComboObjectValues)

        # Choose type of Object
        lblType = Label(parent, text="Loại hàng: ")
        self.comboType = Combobox(parent)
        self.comboType.bind(sequence="<<ComboboxSelected>>",
                            func=self.onChangeComboTypeValues)

        # Input amount of object
        lblAmount = Label(parent, text="Số lượng xuất: ")
        self.entryAmount = Spinbox(parent, textvariable=self.tempPrice)
        self.tempPrice.trace("w", self.onEntryChanged)

        # View The Id of Object
        lblIdTitle = Label(parent, text="ID: ")
        self.lblIdObject = Label(parent, text="##-##")

        # View The Price of one object
        lblPriceTitle = Label(parent, text="Thành giá: ")
        self.lblPrice = Label(parent, text=0)
        lblPriceUnit = Label(parent, text="VND")

        # Choose Date Make Bill
        lblChooseDateTitle = Label(parent, text="Ngày tạo: ")
        self.lblChooseDate = Label(
            parent,
            text=str(datetime.datetime.now().date().strftime("%d-%m-%Y")))

        # Add widgets into grid layout

        lblObject.grid(row=0, column=0, sticky="w", pady=5)
        self.comboObject.grid(row=0, column=1, columnspan=3, pady=5)
        self.comboObject.focus_set()

        lblType.grid(row=1, column=0, sticky="w", pady=5)
        self.comboType.grid(row=1, column=1, columnspan=3, pady=5)

        lblAmount.grid(row=2, column=0, sticky="w", pady=5)
        self.entryAmount.grid(row=2, column=1, columnspan=3, pady=5)

        lblIdTitle.grid(row=3, column=0, sticky="w", pady=5)
        self.lblIdObject.grid(row=3, column=1, sticky="w", pady=5)

        lblPriceTitle.grid(row=4, column=0, sticky="w", pady=5)
        self.lblPrice.grid(row=4, column=1, sticky="w", pady=5)
        lblPriceUnit.grid(row=4, column=3, sticky="w", pady=5)

        lblChooseDateTitle.grid(row=5, column=0, sticky="w", pady=5)
        self.lblChooseDate.grid(row=5, column=1, sticky="w", pady=5)

    def onAddBill(self):
        # sqlite3.IntegrityError
        if self.comboObject.current() == -1:
            messagebox.showwarning("Empty !!!!",
                                   message="Xin hãy chọn một mặt hàng")
            return

        if self.comboType.current() == -1:
            messagebox.showwarning("Empty !!!!",
                                   message="Xin hãy chọn một loại hàng")
            return

        if int(self.entryAmount.get()) > self.amountOfType:
            messagebox.showwarning("Too Large !!!!",
                                   message="Vượt quá số lượng còn lại")
            self.entryAmount.delete(0, END)
            self.entryAmount.insert(0, self.amountOfType)
            return

        if self.amountOfType == 0:
            messagebox.showwarning(
                "Empty !!!!",
                message="Loại hàng này đã hết!!! Xin hãy chọn loại hàng khác")
            return

        if int(self.entryAmount.get()) <= 0 and self.amountOfType != 0:
            messagebox.showwarning("Too Small !!!!",
                                   message="Số lượng xuất quá nhỏ")
            self.entryAmount.delete(0, END)
            self.entryAmount.insert(0, 0)
            return

        bill = BillInfoModel()
        bill.name = self.comboObject.get()
        bill.type = self.comboType.get()
        bill.id = self.lblIdObject["text"]
        bill.amount = int(self.entryAmount.get())
        bill.price = int(self.lblPrice["text"])
        bill.CreatedDate = self.lblChooseDate["text"]
        bill.CreatedTime = datetime.datetime.now().time().strftime("%H:%M:%S")
        bill.CreatedUser = self.master.userCreate

        self.data.insertBill(bill)
        if bill.amount == self.amountOfType:
            answer = messagebox.askquestion(
                "Empty",
                "Loại hàng hiện tại sẽ hết khi bạn xuất hóa đơn \nBạn có muốn xóa luôn loại hàng này không ?"
            )
            if answer == True:
                self.data.deleteType(self.footerID)
            elif answer == False:
                self.data.updateAmountOfType(self.footerID, 0)

        else:
            self.data.updateAmountOfType(self.footerID,
                                         self.amountOfType - bill.amount)

        self.master.addBillIntoTree(bill)
        self.master.treeBill.focus_set()
        self.dialog.destroy()

    def onCancel(self, event=None):
        self.dialog.destroy()

    def onChangeComboObjectValues(self, event=None):
        pos = self.comboObject.current()
        listNameType = []
        self.listType = self.listItem[pos].type
        for typeItem in self.listType:
            listNameType.append(typeItem.name)
        self.comboType.config(values=listNameType)
        self.headerID = self.listItem[pos].id
        self.onChangeID()

    def onChangeComboTypeValues(self, event=None):
        pos = self.comboType.current()
        self.footerID = self.listType[pos].idType
        amount = self.listType[pos].amount
        self.unitPrice = int(self.listType[pos].unitPrice)
        self.amountOfType = amount
        self.lblPrice["text"] = self.unitPrice
        self.onChangeID()

    def onEntryChanged(self, *args):
        temp = int(self.tempPrice.get() * self.unitPrice)
        self.lblPrice['text'] = temp
        # print(self.lblPrice['text'])

    def onChangeID(self):
        temp = self.headerID + "-" + self.footerID
        self.lblIdObject['text'] = temp
Esempio n. 20
0
class Notifier(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.text_clicked = False
        self.time_clicked = False
        self.running = False
        self.afterv = []
        self.max_tries = 5
        self.initUI()

    def initUI(self):
        # Establish frames
        self.pack(side="top", fill="both", expand=True)

        self.top_frame = Frame(self)
        self.bottom_frame = Frame(self)
        self.top_frame.pack(side="top", fill="both", expand=False)
        self.bottom_frame.pack(side="bottom", fill="both", expand=True)

        self.top_top_frame = Frame(self.top_frame)
        self.top_top_frame.pack(side="top", fill="both", expand=False)
        self.bottom_top_frame = Frame(self.top_frame)
        self.bottom_top_frame.pack(side="bottom", fill="both", expand=False)

        # Entry combo box

        self.cboxv = StringVar(self.top_top_frame)
        self.cbox = Combobox(self.top_top_frame, value=self.cboxv, width=40)
        self.cbox['values'] = ("all", "FreeGamesOnSteam", "funny", "news")
        self.cbox.current(0)
        self.cbox.bind("<Button-1>", self.text_callback)
        self.cbox.bind("<Tab>", self.time_callback)
        self.cbox.pack(side="left", padx=10, pady=10, expand=True)

        # Entry time box
        self.tentry = Entry(self.top_top_frame, width=8, foreground='gray')
        self.tentry.bind("<Button-1>", self.time_callback)
        self.tentry.insert(0, "Time(s)")
        self.tentry.pack(side="left", padx=10, pady=10, expand=True)

        # Category drop-down menu
        self.category = StringVar(self.top_top_frame)
        self.category.set("hot")  # default value

        self.omenu = OptionMenu(self.top_top_frame, self.category, "hot",
                                "new", "top", "controversial", "rising")
        self.omenu.pack(side="right", padx=10, pady=10, expand=True)

        # Limit drop-down menu
        self.limit = IntVar(self.top_top_frame)
        self.limit.set(5)  # default value

        self.lmenu = OptionMenu(self.top_top_frame, self.limit,
                                *list(range(10)))
        self.lmenu.pack(side="right", padx=10, pady=10, expand=True)

        # Scan button
        self.scanb = Button(self.bottom_top_frame,
                            text="Scan",
                            command=self.scan_subreddit)
        self.scanb.pack(side="left", padx=10, pady=10, expand=True)
        self.parent.bind("<Return>", lambda x: self.scan_subreddit())

        # Popup check
        self.checkvar = BooleanVar()
        self.check = Checkbutton(self.bottom_top_frame,
                                 text="Popup",
                                 variable=self.checkvar)
        self.check.pack(side="left", padx=10, pady=10, expand=True)

        # Continuous check
        self.contvar = BooleanVar()
        self.contb = Checkbutton(self.bottom_top_frame,
                                 text="Continuous",
                                 variable=self.contvar)
        self.contb.pack(side="left", padx=10, pady=10, expand=True)

        # Stop button
        self.stopb = Button(self.bottom_top_frame,
                            text="Stop",
                            command=self.stop_scanning,
                            state="disabled")
        self.stopb.pack(side="right", padx=10, pady=10, expand=True)
        self.parent.bind("<Escape>", lambda x: self.stop_scanning())

        # Results text box
        self.text = CustomText(self.bottom_frame, height=10, width=50)
        self.text.configure(state="disabled")
        self.text.pack(side="top", padx=10, pady=10, expand=True, fill="both")

    def text_callback(self, event=None):
        if not self.text_clicked:
            self.cbox.delete(0, "end")
            self.text_clicked = True

    def time_callback(self, event=None):
        if not self.time_clicked:
            self.tentry.delete(0, "end")
            self.tentry.config(foreground="black")
            self.time_clicked = True

    def scan_subreddit(self):
        self.running = True
        self.scanb.config(state="disabled")
        self.stopb.config(state="normal")
        self.omenu.config(state="disabled")
        self.lmenu.config(state="disabled")
        self.cbox.config(state="disabled")
        self.tentry.config(state="disabled")
        self.check.config(state="disabled")
        self.contb.config(state="disabled")

        self.parent.unbind("<Return>")
        # Clean text box
        self.text.config(state="normal")
        self.text.delete(1.0, 'end')
        self.text.config(state="disabled")

        # Get values from boxes
        sub_name = self.cbox.get()
        cat = self.category.get()
        self.slimit = self.limit.get()
        self.popup = self.checkvar.get()
        self.cont = self.contvar.get()

        try:
            subreddit = reddit.subreddit(sub_name)
        except Exception:
            self.text.tinsert("Error: insert a subreddit" + '\n')
            self.stop_scanning()
            return

        try:
            self.stime = max(0, int(self.tentry.get()))
        except Exception:
            self.text.tinsert("Error: time must be a number" + '\n')
            self.stop_scanning()
            return

        self.text.tinsert("Info: getting " + cat + " posts from /r/" +
                          sub_name + '\n')

        self.subcat = get_subreddit_cat(subreddit, cat)
        self.tries = 0
        self.done_trying = False
        self.started_managing = False
        self.done_managing = False
        self.submissions = None
        self.get_results()

    def stop_scanning(self):
        self.running = False
        self.scanb.config(state="normal")
        self.stopb.config(state="disabled")
        self.omenu.config(state="normal")
        self.lmenu.config(state="normal")
        self.cbox.config(state="normal")
        self.tentry.config(state="normal")
        self.check.config(state="normal")
        self.contb.config(state="normal")
        self.parent.bind("<Return>", lambda x: self.scan_subreddit())
        for a in self.afterv:
            self.parent.after_cancel(a)
        del self.afterv[:]

    def get_results(self):
        if self.running:
            now = time.time()
            if not self.done_trying:
                if self.tries < self.max_tries:
                    try:
                        self.submissions = [
                            x for x in self.subcat(limit=self.slimit)
                            if (now - x.created_utc) < self.stime
                        ]
                        self.done_trying = True
                    except Exception:
                        self.text.tinsert("Error: [" + nows() + "] try n. " +
                                          str(self.tries + 1) +
                                          ", cannot access subreddit" + '\n')
                        self.tries += 1
                        self.afterv.append(
                            self.parent.after(5000, self.get_results))
                else:
                    self.text.tinsert(
                        "Error: [" + nows() +
                        "] couldn't access subreddit. Stopping scan." + '\n')
                    self.stop_scanning()
                    self.done_trying = True
                self.tries = 0

            if self.done_trying:
                if not self.submissions:
                    if not self.started_managing:
                        self.text.tinsert("Info: [" + nows() +
                                          "] no results found"
                                          '\n')
                    self.done_managing = True
                else:
                    if not self.started_managing:
                        self.text.tinsert("Info: [" + nows() + "] " +
                                          str(len(self.submissions)) +
                                          " results found"
                                          '\n')
                        self.started_managing = True
                    s = self.submissions[0]
                    self.text.tinsert("Title: " + convert65536(s.title) + '\n')
                    self.text.tinsert("Url: " + s.url + '\n')
                    self.text.tinsert("Created: " + pretty_date(s) + '\n\n')
                    self.parent.update_idletasks()
                    if self.popup:
                        if sys.platform.startswith('win'):
                            import winsound
                            winsound.PlaySound("media/jamaica.wav",
                                               winsound.SND_FILENAME)
                        Dialog(self.parent, s.url, s.title)
                    self.submissions = self.submissions[1:]
                    self.afterv.append(
                        self.parent.after(1000, self.get_results))

                if self.done_managing:
                    if self.cont:
                        self.text.tinsert(
                            "Info: [" + nows() +
                            "] continuous mode, will check again in " +
                            str(self.stime) + " seconds\n\n")
                        self.afterv.append(
                            self.parent.after(self.stime * 1000,
                                              self.get_results))
                        self.done_trying = False
                        self.started_managing = False
                        self.done_managing = False
                    else:
                        self.text.tinsert("Info: [" + nows() +
                                          "] scanning finished"
                                          '\n')
                        self.stop_scanning()
Esempio n. 21
0
class additems:
    def __init__(self, frame):
        self.mywindow = Toplevel(frame)
        self.mywindow.wm_title("Add Items")
        self.mywindow.geometry("320x300")

        t1 = Label(self.mywindow, text="Category ")
        t2 = Label(self.mywindow, text="Item No. ")
        t3 = Label(self.mywindow, text="Item Name ")
        t4 = Label(self.mywindow, text="Price ")
        t5 = Label(self.mywindow, text="Quantity (opt) ")

        self.mycatchoice = StringVar()

        self.c1 = Combobox(self.mywindow, textvariable=self.mycatchoice)
        self.e1 = Entry(self.mywindow)
        self.e2 = Entry(self.mywindow)
        self.e3 = Entry(self.mywindow)
        self.e4 = Entry(self.mywindow)
        self.b1 = Button(self.mywindow, text="Add Item")

        self.c1.set("Choose Category ")

        t1.place(x=50, y=50)
        t2.place(x=50, y=80)
        t3.place(x=50, y=110)
        t4.place(x=50, y=140)
        t5.place(x=50, y=170)

        self.c1.place(x=150, y=50)
        self.e1.place(x=150, y=80)
        self.e2.place(x=150, y=110)
        self.e3.place(x=150, y=140)
        self.e4.place(x=150, y=170)

        self.b1.place(x=150, y=220)

        self.fetchcategory()

        self.e1.bind("<FocusIn>", lambda e: self.myfocusin(self.e1))
        self.e2.bind("<FocusIn>", lambda e: self.myfocusin(self.e2))
        self.e3.bind("<FocusIn>", lambda e: self.myfocusin(self.e3))
        self.e4.bind("<FocusIn>", lambda e: self.myfocusin(self.e4))

        self.e1.bind("<FocusOut>", lambda e: self.myfocusout(self.e1))
        self.e2.bind("<FocusOut>", lambda e: self.myfocusout(self.e2))
        self.e3.bind("<FocusOut>", lambda e: self.myfocusout(self.e3))
        self.e4.bind("<FocusOut>", lambda e: self.myfocusout(self.e4))

        self.b1.bind("<Enter>", lambda e: self.myenter(self.b1))
        self.b1.bind("<Leave>", lambda e: self.myleave(self.b1))
        self.b1.bind("<Button-1>", lambda e: self.myenter(self.b1))

    def myfocusin(self, obj):
        obj.config(bg="green", fg="white")

    def myfocusout(self, obj):
        obj.config(bg="white", fg="black")

    def myenter(self, obj):
        obj.config(bg="green", fg="white")

    def myleave(self, obj):
        obj.config(bg="red", fg="black")

    def fetchcategory(self):
        mycat = []
        try:
            mydb = pymysql.connect(host='localhost',
                                   user='******',
                                   password='',
                                   db='hotelmanagementdb')
            with mydb.cursor() as myconn:
                myconn.execute("select * from category")
                mydb.commit()
                myresult = myconn.fetchall()
                for i in range(len(myresult)):
                    mycat.append(str(myresult[i][0]) + "," + myresult[i][1])
                self.c1.config(values=mycat)
        except Exception as e:
            messagebox.showerror("Database Error ",
                                 "Error Ocured Due to : " + str(e),
                                 parent=self.mywindow)

    def myenter(self, obj):
        obj.config(bg="orange", fg="white")
        self.insertrecord()

    def insertrecord(self):
        index = self.mycatchoice.get().find(",")
        getid = self.mycatchoice.get()[index + 1:]

        try:
            mydb = pymysql.connect(host='localhost',
                                   user='******',
                                   password='',
                                   db='hotelmanagementdb')
            with mydb.cursor() as myconn:
                myconn.execute(
                    "insert into items(item_no,item_name,cat_name,Price,qty) values(%s,%s,%s,%s,%s)",
                    (self.e1.get(), self.e2.get(), getid, self.e3.get(),
                     self.e4.get()))
                mydb.commit()
                messagebox.showinfo("Database Information ",
                                    "Item Succesfully Inserted",
                                    parent=self.mywindow)

        except Exception as ex:
            messagebox.showerror("Database Error ",
                                 "Error Ocured Due to : " + str(ex),
                                 parent=self.mywindow)
Esempio n. 22
0
class App:
    def __init__(self, root):
        self.CURRENT_YEAR = datetime.now().year
        self.CURRENT_MONTH = datetime.now().month
        #self.CURRENT_MONTH = 7
        self.root = root
        self.root.minsize(400, 400)
        self.root.geometry("804x487+156+156")
        self.LABEL_FRAME_FONT = Font(family="consolas",
                                     size=10,
                                     slant='roman',
                                     underline=0,
                                     weight="bold")
        self.LABEL_FRAME_CONFIG = {
            'font': self.LABEL_FRAME_FONT,
            'fg': 'tomato'
        }

        # self.root.bind("<Button-1>" , lambda e:self.root.focus())

        self.initDateSelector()
        self.initFileSaver()
        self.initMainBody()
        self.initDirectory()
        self.db = DataBase(self.dbDir)
        self.setData()

        self.setDataToDateSelector()

        popup = self.MONTH_SELECTION_COMBOBOX.tk.eval(
            "ttk::combobox::PopdownWindow %s" % self.MONTH_SELECTION_COMBOBOX)
        self.MONTH_SELECTION_COMBOBOX.tk.call(
            '%s.f.l' % popup, 'configure', '-font',
            self.MONTH_SELECTION_COMBOBOX['font'])

    def initDirectory(self):
        self.MD = os.path.split(os.path.abspath(__file__))[0]

        if (not os.path.exists(os.path.join(self.MD, "Database"))):
            os.makedirs(os.path.join(self.MD, "Database"))

        self.dbDir = os.path.join(self.MD, "Database")

    def initDateSelector(self):
        #text = "Select Year And Month"
        self.DATE_SELECTION_FRAME = LabelFrame(self.root,
                                               text="",
                                               **self.LABEL_FRAME_CONFIG)
        self.DATE_SELECTION_FRAME.pack(side="top",
                                       anchor='nw',
                                       padx=5,
                                       pady=10,
                                       fill='x')

        self.YEAR_SELECTION_FRAME = LabelFrame(self.DATE_SELECTION_FRAME,
                                               text="Select Year",
                                               **self.LABEL_FRAME_CONFIG)
        self.YEAR_SELECTION_FRAME.pack(side='left', pady=2, padx=8)

        self.MONTH_SELECTION_FRAME = LabelFrame(self.DATE_SELECTION_FRAME,
                                                text="Select Month",
                                                **self.LABEL_FRAME_CONFIG)
        self.MONTH_SELECTION_FRAME.pack(side='left', pady=2, padx=8)

        self.YEAR_SELECTION_COMBOBOX = Combobox(self.YEAR_SELECTION_FRAME)
        self.YEAR_SELECTION_COMBOBOX.config(
            values=[str(x) for x in range(2010, self.CURRENT_YEAR + 1)],
            state="readonly")
        self.YEAR_SELECTION_COMBOBOX.config(font='consolas', width=10)
        self.YEAR_SELECTION_COMBOBOX.pack()
        self.YEAR_SELECTION_COMBOBOX.bind(
            "<<ComboboxSelected>>", lambda e: self.manageWhenYearChanged())

        self.MONTH_SELECTION_COMBOBOX = Combobox(self.MONTH_SELECTION_FRAME)
        self.MONTH_SELECTION_COMBOBOX.config(values=["All Months"] +
                                             [x for x in ALL_MONTHS.values()],
                                             state="readonly")
        self.MONTH_SELECTION_COMBOBOX.config(font="consolas", width=10)
        self.MONTH_SELECTION_COMBOBOX.pack(side='right')
        self.MONTH_SELECTION_COMBOBOX.bind(
            "<<ComboboxSelected>>", lambda e: self.manageWhenMonthChanged())

    def setDataToDateSelector(self):
        years = set()
        months = set()
        for x in self.CurData:
            years.add(x.dateCreated.year)
        self.YEAR_SELECTION_COMBOBOX.config(values=[x for x in years])
        print(years)

    def manageWhenYearChanged(self):
        pass

    def manageWhenMonthChanged(self, mode=0):
        if (self.MONTH_SELECTION_COMBOBOX.get() == self.PRE_MONTH_ON_COMBOBOX
                and mode != 1):
            print("NO Need")
            return
        self.PRE_MONTH_ON_COMBOBOX = self.MONTH_SELECTION_COMBOBOX.get()
        All_Story = self.db.getAll()
        tempStories = []

        if (self.MONTH_SELECTION_COMBOBOX.get() == "All Months"):
            for story in All_Story:
                if (str(story.dateCreated.year) ==
                        self.YEAR_SELECTION_COMBOBOX.get()):
                    tempStories.append(story)
        else:
            for story in All_Story:
                if (str(story.dateCreated.year)
                        == self.YEAR_SELECTION_COMBOBOX.get()
                        and ALL_MONTHS[story.dateCreated.month]
                        == self.MONTH_SELECTION_COMBOBOX.get()):
                    tempStories.append(story)

        print("Total = ", len(tempStories))

        self.CurData = tempStories
        self.LISTBOX.delete(0, END)
        for story in self.CurData:
            self.LISTBOX.insert(END, story.title)
        if (self.MONTH_SELECTION_COMBOBOX.get() == ALL_MONTHS[
                self.CURRENT_MONTH]):
            self.LISTBOX.insert(END, "Add a Story")
        self.EDITTEXT.delete("1.0", END)
        self.ToggleSaveMenuVisibility(False)

    def initMainBody(self):
        self.MAIN_BODY_FRAME = LabelFrame(self.root,
                                          text="",
                                          **self.LABEL_FRAME_CONFIG)
        self.MAIN_BODY_FRAME.pack(fill='both', expand=1)

        self.PANED_WINDOW_LIST_BOX = PanedWindow(self.MAIN_BODY_FRAME)
        self.PANED_WINDOW_LIST_BOX.pack(fill=BOTH, expand=1)

        self.LISTBOX_FRAME = LabelFrame(self.PANED_WINDOW_LIST_BOX,
                                        text="ListBox",
                                        **self.LABEL_FRAME_CONFIG)
        self.PANED_WINDOW_LIST_BOX.add(self.LISTBOX_FRAME)

        self.LISTBOX = Listbox(self.LISTBOX_FRAME)
        self.LISTBOX.config(font="consolas 12")
        self.LISTBOX.pack(expand=1, fill='both')
        self.LISTBOX.bind("<Double-1>", lambda e: self.onListBoxClick())
        #self.LISTBOX.insert(0 , "HEllo")

        self.PANED_WINDOW_EDITTEXT = PanedWindow(self.PANED_WINDOW_LIST_BOX,
                                                 orient=VERTICAL)
        self.PANED_WINDOW_LIST_BOX.add(self.PANED_WINDOW_EDITTEXT)

        self.EDITTEXT_FRAME = LabelFrame(self.PANED_WINDOW_EDITTEXT,
                                         text="EditText",
                                         **self.LABEL_FRAME_CONFIG)
        #"DejaVu Sans Mono"
        self.EDITTEXT = ScrolledText(self.EDITTEXT_FRAME,
                                     padx=5,
                                     pady=5,
                                     font=("Source code pro", "13"),
                                     wrap='word')
        self.EDITTEXT.pack(fill='both', expand=1)
        self.PANED_WINDOW_EDITTEXT.add(self.EDITTEXT_FRAME)

    def setData(self):
        self.YEAR_SELECTION_COMBOBOX.set(self.CURRENT_YEAR)
        self.MONTH_SELECTION_COMBOBOX.set(ALL_MONTHS[self.CURRENT_MONTH])
        self.PRE_MONTH_ON_COMBOBOX = self.MONTH_SELECTION_COMBOBOX.get()
        self.CurData = self.db.getAll()
        self.LastId = self.CurData[-1].id
        self.manageWhenMonthChanged(1)
        #self.LISTBOX.insert(END, "Add a Story")
        #return
        #for x in self.CurData:
        #    self.LISTBOX.insert(END , x.title)

    def onListBoxClick(self):
        self.LISTBOX_CUR_IND = self.LISTBOX.curselection()[0]
        self.LISTBOX_CUR_VAl = self.LISTBOX.get(self.LISTBOX_CUR_IND)
        print(self.LISTBOX_CUR_VAl)

        if (self.LISTBOX_CUR_VAl == self.LISTBOX.get(END)
                and self.MONTH_SELECTION_COMBOBOX.get() == ALL_MONTHS[
                    self.CURRENT_MONTH]):  #End Item Clicked [Adding new Story]
            date = datetime.now()
            #print(type(date))
            new = Story(
                "Story " + self.formatDate(date),
                "My Data",
                date,
                date,
            )
            self.db.addStory(new)
            self.LastId += 1
            self.LISTBOX.insert(self.LISTBOX_CUR_IND, new.title)
            #self.CurData.append(new)
            self.CurData.append(self.db.getStory(self.LastId))
            #self.CurData = self.db.getAll()
            self.LISTBOX.select_clear(END)
            self.LISTBOX.select_set(self.LISTBOX_CUR_IND)
            self.onListBoxClick()

        else:

            self.C_Story = self.CurData[self.LISTBOX_CUR_IND]
            print("Id = ", self.C_Story.id)
            self.EDITTEXT.delete("0.0", END)
            self.EDITTEXT.insert(END, self.C_Story.data)
            self.EDITTEXT.focus_force()
            self.ToggleSaveMenuVisibility(True)
            self.DATE_CREATED_LABEL.config(
                text=self.formatDate(self.C_Story.dateCreated))
            self.DATE_MODIFIED_LABEL.config(
                text=self.formatDate(self.C_Story.dateModified))
            self.TITLE_VAR.set(self.C_Story.title)

    def initFileSaver(self):
        self.SEPARATOR = Label(self.DATE_SELECTION_FRAME,
                               text="|",
                               font='consolas 25',
                               fg="#eab")
        self.SEPARATOR.pack(side='left')  #separator

        self.DATE_CREATED_FRAME = LabelFrame(self.DATE_SELECTION_FRAME,
                                             text="Date Created",
                                             **self.LABEL_FRAME_CONFIG)
        self.DATE_CREATED_FRAME.pack(side='left', padx=5)
        self.DATE_CREATED_LABEL = Label(self.DATE_CREATED_FRAME)
        #self.DATE_CREATED_LABEL.pack()
        #self.DATE_CREATED_LABEL.pack_forget()

        self.DATE_MODIFIED_FRAME = LabelFrame(self.DATE_SELECTION_FRAME,
                                              text="Date Modified",
                                              **self.LABEL_FRAME_CONFIG)
        self.DATE_MODIFIED_FRAME.pack(side='left', padx=5)
        self.DATE_MODIFIED_LABEL = Label(self.DATE_MODIFIED_FRAME)

        self.TITLE_FRAME = LabelFrame(self.DATE_SELECTION_FRAME,
                                      text="Title",
                                      **self.LABEL_FRAME_CONFIG)
        self.TITLE_FRAME.pack(side='left', padx=5)
        self.TITLE_VAR = StringVar(self.root)
        self.TITLE_ENTRY = Entry(self.TITLE_FRAME, textvariable=self.TITLE_VAR)

        self.SAVE_BTN = Button(self.DATE_SELECTION_FRAME,
                               text="Save",
                               bd=1,
                               cursor="hand2",
                               bg="#fff000",
                               font='consolas 14',
                               height=1)
        #self.SAVE_BTN.pack(side = 'left')
        self.SAVE_BTN.config(command=self.Save)

        #self.ToggleSaveMenuVisibility(True)

    def ToggleSaveMenuVisibility(self, flag):
        if (flag == True):
            #self.SEPARATOR.pack(side='left')
            self.DATE_CREATED_LABEL.pack()
            self.DATE_MODIFIED_LABEL.pack()
            self.TITLE_ENTRY.pack()
            self.SAVE_BTN.pack(side='left', padx=15)
        elif (flag == False):
            #self.SEPARATOR.pack_forget()
            self.DATE_CREATED_LABEL.pack_forget()
            self.DATE_MODIFIED_LABEL.pack_forget()
            self.TITLE_ENTRY.pack_forget()
            self.SAVE_BTN.pack_forget()

    def Save(self):
        self.C_Story.title = self.TITLE_VAR.get()
        self.C_Story.data = self.EDITTEXT.get('1.0', END)
        self.C_Story.dateModified = datetime.now()
        self.DATE_MODIFIED_LABEL.config(
            text=self.formatDate(self.C_Story.dateModified))

        self.LISTBOX.delete(self.LISTBOX_CUR_IND)
        self.LISTBOX.insert(self.LISTBOX_CUR_IND, self.C_Story.title)

        self.db.updateStory(self.C_Story)

    def formatDate(self, timestamp):
        #return str((timestamp.day))
        return "%d %s %d , %02d:%02d" % (timestamp.day, ALL_MONTHS[
            timestamp.month], timestamp.year, timestamp.hour, timestamp.minute)
Esempio n. 23
0
class student:
    def __init__(self):

        self.root = Tk("STUDENT INFO")
        self.root.configure(bg='sky blue')
        self.root.geometry("680x310")
        self.root.title("Student")

        self.lb_heading = Label(self.root,
                                text='ADD STUDENT',
                                padx=110,
                                width=15)
        Labelfont = (
            'Arial',
            20,
            'bold',
        )
        self.lb_heading.configure(foreground='black',
                                  background='sky blue',
                                  font=Labelfont)
        self.lb_heading.grid(row=0, column=1, columnspan=3)

        self.lb_rollno = Label(self.root,
                               text="Enter Rollno",
                               background='sky blue',
                               foreground='black').grid(row=1,
                                                        column=0,
                                                        sticky=(W))
        self.lb_studentname = Label(self.root,
                                    text="Enter Student name",
                                    background='sky blue',
                                    foreground='black').grid(row=2,
                                                             column=0,
                                                             sticky=(W))
        self.lb_course = Label(self.root,
                               text='Select Course',
                               background='sky blue',
                               foreground='black').grid(row=3,
                                                        column=0,
                                                        sticky=(W))
        self.lb_gen = Label(self.root,
                            text="Select Gender",
                            background='sky blue',
                            foreground='black').grid(row=4,
                                                     column=0,
                                                     sticky=(W))
        self.lb_mobileno = Label(self.root,
                                 text="Enter Mobileno ",
                                 background='sky blue',
                                 foreground='black').grid(row=5,
                                                          column=0,
                                                          sticky=(W))
        self.lb_pmobileno = Label(self.root,
                                  text="Parent Mobileno",
                                  background='sky blue',
                                  foreground='black').grid(row=6,
                                                           column=0,
                                                           sticky=(W))
        self.lb_fname = Label(self.root,
                              text='Enter Father Name',
                              background='sky blue',
                              foreground='black').grid(row=2,
                                                       column=2,
                                                       sticky=(E))
        self.lb_semester = Label(self.root,
                                 text="Select Semester",
                                 background='sky blue',
                                 foreground='black').grid(row=3,
                                                          column=2,
                                                          sticky=(E))
        self.lb_email = Label(self.root,
                              text="Enter Email",
                              background='sky blue',
                              foreground='black').grid(row=4,
                                                       column=2,
                                                       sticky=(E))
        self.lb_address = Label(self.root,
                                text="Enter Address",
                                background='sky blue',
                                foreground='black').grid(row=5,
                                                         column=2,
                                                         sticky=(E))
        self.lb_paddress = Label(self.root,
                                 text="Enter Permanent Address",
                                 background='sky blue',
                                 foreground='black').grid(row=6,
                                                          column=2,
                                                          sticky=(E))

        self.tb_roll = Entry(self.root)
        self.tb_sname = Entry(self.root)
        self.cb_course = Combobox(self.root)

        db = connection()
        cr = db.conn.cursor()
        s = "select coursename from courses"
        cr.execute(s)
        p = cr.fetchall()
        lst_cname = []
        for i in range(0, len(p)):
            lst_cname.append(p[i][0])

        self.cb_course.config(values=tuple(lst_cname))
        self.cb_gen = Combobox(self.root,
                               values=('Female', 'Male'),
                               state='readonly')
        self.cb_sem = Combobox(self.root, state='readonly')

        self.lst_sem = []
        for i in range(1, 11):
            self.lst_sem.append(i)

        self.cb_sem.config(values=tuple(self.lst_sem))
        self.tb_mobile = Entry(self.root)
        self.tb_pmobile = Entry(self.root)
        self.tb_fname = Entry(self.root)
        self.tb_email = Entry(self.root)
        self.tb_address = Entry(self.root)
        self.tb_paddress = Entry(self.root)

        self.tb_roll.grid(row=1,
                          column=1,
                          padx=(5),
                          pady=(5),
                          sticky=(N, E, W))
        self.tb_sname.grid(row=2,
                           column=1,
                           padx=(5),
                           pady=(5),
                           sticky=(N, E, W))
        self.cb_course.grid(row=3,
                            column=1,
                            padx=(5),
                            pady=(5),
                            sticky=(N, E, W))
        self.cb_gen.grid(row=4, column=1, padx=(5), pady=(5), sticky=(N, E, W))
        self.tb_mobile.grid(row=5,
                            column=1,
                            padx=(5),
                            pady=(5),
                            sticky=(N, E, W))
        self.tb_pmobile.grid(row=6,
                             column=1,
                             padx=(5),
                             pady=(5),
                             sticky=(N, E, W))
        self.tb_fname.grid(row=2,
                           column=3,
                           padx=(5),
                           pady=(5),
                           sticky=(N, E, W))
        self.cb_sem.grid(row=3, column=3, padx=(5), pady=(5), sticky=(N, E, W))
        self.tb_email.grid(row=4,
                           column=3,
                           padx=(5),
                           pady=(5),
                           sticky=(N, E, W))
        self.tb_address.grid(row=5,
                             column=3,
                             padx=(5),
                             pady=(5),
                             sticky=(N, E, W))
        self.tb_paddress.grid(row=6,
                              column=3,
                              padx=(5),
                              pady=(5),
                              sticky=(N, E, W))

        self.bt1 = Button(self.root,
                          text="submit",
                          command=self.test,
                          width=15,
                          bg='white',
                          fg='black',
                          padx=10).grid(row=8, column=2, sticky=(S), pady=15)

        self.root.mainloop()

    def test(self):

        self.x = int(self.tb_email.get().count("@"))
        self.d = int(self.tb_email.get().count("."))

        if self.tb_roll.get() == "" or self.tb_sname.get(
        ) == "" or self.cb_course.get() == "" or self.cb_gen.get(
        ) == "" or self.cb_sem.get() == "" or self.tb_mobile.get(
        ) == "" or self.tb_pmobile.get() == "" or self.tb_fname.get(
        ) == "" or self.cb_sem.get() == "" or self.tb_email.get(
        ) == "" or self.tb_address.get() == "" or self.tb_paddress.get() == "":
            showerror("", "Cannot Leave any field blank", parent=self.root)

        elif self.tb_mobile.get().isalpha() == True:
            showerror("", "Mobile number not valid")

        elif self.tb_pmobile.get().isalpha() == True:
            showerror("", "Mobile number not valid")

        elif self.x != 1 or self.tb_email.get() == "" or self.d != 1:
            showerror("", "Wrong Email", parent=self.root)

        else:
            db = connection()
            cr = db.conn.cursor()
            query = "insert into student values(null,'" + self.tb_roll.get(
            ) + "','" + self.tb_sname.get() + "','" + self.tb_fname.get(
            ) + "','" + self.cb_gen.get() + "','" + self.cb_course.get(
            ) + "','" + self.cb_sem.get() + "','" + self.tb_mobile.get(
            ) + "','" + self.tb_address.get() + "','" + self.tb_email.get(
            ) + "','" + self.tb_pmobile.get() + "','" + self.tb_paddress.get(
            ) + "')"
            cr.execute(query)
            db.conn.commit()
            showinfo("Success", "Student added successfully")
Esempio n. 24
0
    def __init__(self, master):
        Frame.__init__(self, master)

        pane = PanedWindow(orient=HORIZONTAL)

        leftFrame = LabelFrame(text="Liste des rapports de visite")

        # NUMERO
        tbNum = Entry(leftFrame, width=24)
        tbNum.insert(0, '12')  # Hydrater avec les propriétés du rapport
        tbNum.config(state='readonly')
        
        Label(leftFrame,
              text='Numéro de rapport : ').grid(row=0, column=0, sticky=SE)
        tbNum.grid(row=0, column=1, sticky=SE, pady=5)

        # PRATICIEN
        cbbPraticien = Combobox(leftFrame,
                                width=22,
                                values=['Alice', 'Bob', 'Charlie', 'Donald'])
        cbbPraticien.set('Alice')  # Hydrater avec les propriétés du rapport
        cbbPraticien.config(state='disabled')
        
        Label(leftFrame, text='Praticien : ').grid(row=1, column=0, sticky=SE)
        cbbPraticien.grid(row=1, column=1, sticky=SE, pady=5)

        # DATE
        tbDate = Entry(leftFrame, width=24)
        tbDate.insert(0, '16/12/2014')  # Hydrater avec les propriétés du rapport
        tbDate.config(state='readonly')
        
        Label(leftFrame, text='Date : ').grid(row=2, column=0, sticky=SE)
        tbDate.grid(row=2, column=1, sticky=SE, pady=5)

        # MOTIF
        cbbMotif = Combobox(leftFrame, width=22, values=[
            'Visite régulière',
            'Demande',
            'Nouveau produit'])
        cbbMotif.set('Visite régulière')  # Hydrater avec les propriétés du rapport
        cbbMotif.config(state='disabled')
        
        Label(leftFrame, text='Combo : ').grid(row=3, column=0, sticky=SE)
        cbbMotif.grid(row=3, column=1, sticky=SE, pady=5)

        pane.add(leftFrame)

        # BILAN
        rightFrame = LabelFrame(text="Bilan : ")
        txtBilan = Text(rightFrame, height=6, width=64)
        txtBilan.insert(0, 'Bla blabla bla.')
        txtBilan.config(state='disabled')
        
        txtBilan.grid(row=4, column=1, pady=5)

        # ECHANTILLONS
        # TODO

        pane.add(rightFrame)

        pane.grid(row=0, column=0)
Esempio n. 25
0
class PCRLibrarianApp(Tk):
    """
    Main window for thePCR Librarian app
    """
    def __init__(self):
        super(PCRLibrarianApp, self).__init__()

        # Screen metrics
        sw = self.winfo_screenwidth()
        sh = self.winfo_screenheight()

        # TODO Position and size main window
        self.title("PCR Librarian")

        # ttk theme
        # s = ttk.Style()
        # s.theme_use('classic')
        self.background_color = "#ffffff"
        self.highlight_color = "#e0e0e0"

        # Create window widgets
        self._create_widgets(sw, sh)

        # Size the main window according to its contents
        self.update()
        w = self.winfo_width()
        h = self.winfo_height()
        # Centered
        x = int((sw - w) / 2)
        y = int((sh - h) / 2)
        # width x height + x + y
        geo = "{0}x{1}+{2}+{3}".format(w, h, x, y)
        self.geometry(geo)
        # self.resizable(width=True, height=True)
        self.resizable(width=True, height=False)

        # Handle app exit
        self.protocol("WM_DELETE_WINDOW", self._on_close)

        # Restore last used directory
        self._set_directory(Configuration.get_last_recent())

    def _create_widgets(self, sw, sh):
        """
        Create the UI widgets
        :param sw: Screen width
        :param sh: Screen height
        :return:
        """
        MIN_WIDTH = 100

        # Create a menu bar for the current OS
        self._create_menu()

        # Control/widget experimentation
        self.config(padx=10)
        self.config(pady=10)

        # Around control map directory widgets
        self._ctrl_frame = LabelFrame(master=self,
                                      padx=10,
                                      pady=10,
                                      text="Control Map Directory")
        self._ctrl_frame.grid(row=0, column=0, sticky="ew")

        # Container for action buttons
        self._button_frame = Frame(master=self, bd=5, padx=5, pady=5)
        self._button_frame.grid(row=2, column=0, pady=5)

        self.columnconfigure(0, weight=1, minsize=MIN_WIDTH)
        self._ctrl_frame.columnconfigure(0, weight=1)

        # Control frame row tracker
        r = 0

        # Directory entry
        self._ent_directory = Entry(master=self._ctrl_frame, width=MIN_WIDTH)
        self._ent_directory.grid(row=r, column=0, sticky="ew")
        r += 1

        # Frame for directory widgets
        self._fr_dir = Frame(master=self._ctrl_frame)

        # Select a directory
        self._btn_dir_button = Button(master=self._fr_dir,
                                      text="Select Control Map Directory",
                                      command=self._on_select_directory)
        self._btn_dir_button.grid(row=0, column=0, padx=5, pady=5)

        # Recently used directories
        self._cb_recent_dirs = Combobox(master=self._fr_dir,
                                        width=50,
                                        values=Configuration.get_recent())
        self._cb_recent_dirs.grid(row=0, column=1, padx=5, pady=5)
        self._cb_recent_dirs.bind("<<ComboboxSelected>>",
                                  self._on_recent_directory)

        self._fr_dir.grid(row=r, column=0, padx=10)
        r += 1

        # Control map file listbox with scrollbar
        self._lb_frame = LabelFrame(self._ctrl_frame,
                                    text="Control Map Files",
                                    pady=5,
                                    padx=5)
        self._lb_scrollbar = Scrollbar(self._lb_frame, orient=tkinter.VERTICAL)
        self._lb_filelist = Listbox(master=self._lb_frame, width=100)
        self._lb_scrollbar.config(command=self._lb_filelist.yview)
        self._lb_scrollbar.pack(side=tkinter.RIGHT, fill=tkinter.Y)
        self._lb_filelist.pack()
        self._lb_frame.grid(row=r, column=0, pady=5)
        r += 1

        # Action buttons are inside the button frame on one row

        self._btn_receive_current_button = Button(
            master=self._button_frame,
            text="Receive Current Map",
            state=tkinter.DISABLED,
            command=self._on_receive_current_map)
        self._btn_receive_current_button.grid(row=0, column=0, padx=5)

        self._btn_receive_all_button = Button(
            master=self._button_frame,
            text="Receive All Maps",
            state=tkinter.DISABLED,
            command=self._on_receive_all_maps)
        self._btn_receive_all_button.grid(row=0, column=1, padx=5)

        self._btn_send_button = Button(master=self._button_frame,
                                       text="Send Control Map Files",
                                       state=tkinter.DISABLED,
                                       command=self._on_send)
        self._btn_send_button.grid(row=0, column=2, padx=5)

        self._btn_quit_button = Button(master=self._button_frame,
                                       text="Quit",
                                       command=self._on_close)
        self._btn_quit_button.grid(row=0, column=3, padx=5)

        # MIDI in/out ports listboxes
        self._lb_midiports_frame = LabelFrame(self,
                                              text="MIDI Ports",
                                              pady=5,
                                              padx=5)

        self._lbl_inports = Label(master=self._lb_midiports_frame, text="In")
        self._lb_midiin_ports = Listbox(master=self._lb_midiports_frame,
                                        width=30,
                                        height=5,
                                        selectmode=tkinter.SINGLE,
                                        exportselection=0)
        self._lbl_inports.grid(row=0, column=0)
        self._lb_midiin_ports.grid(row=1, column=0, padx=5, pady=5)

        self._lbl_outports = Label(master=self._lb_midiports_frame, text="Out")
        self._lb_midiout_ports = Listbox(master=self._lb_midiports_frame,
                                         width=30,
                                         height=5,
                                         selectmode=tkinter.SINGLE,
                                         exportselection=0)
        self._lbl_outports.grid(row=0, column=1)
        self._lb_midiout_ports.grid(row=1, column=1, padx=5, pady=5)

        self._lb_midiports_frame.grid(row=1, column=0, pady=5)

        # Populate midin ports listbox
        self._in_ports = get_midiin_ports()
        for p in self._in_ports:
            self._lb_midiin_ports.insert(tkinter.END, p)

        # Populate midout ports listbox
        self._out_ports = get_midiout_ports()
        for p in self._out_ports:
            self._lb_midiout_ports.insert(tkinter.END, p)

        # Minimize the height of the ports listboxes
        max_height = max(len(self._in_ports), len(self._out_ports))
        self._lb_midiin_ports.config(height=max_height)
        self._lb_midiout_ports.config(height=max_height)

        # Default midi port selections
        self._lb_midiin_ports.select_set(0)
        self._lb_midiout_ports.select_set(0)

        # Status bar
        self._v_statusbar = StringVar(value="Select control map directory")
        self._lbl_statusbar = Label(master=self,
                                    textvariable=self._v_statusbar,
                                    bd=5,
                                    relief=tkinter.RIDGE,
                                    anchor=tkinter.W)
        self._lbl_statusbar.grid(row=3, column=0, pady=5, padx=5, sticky="ew")

        # Put the focus in the directory text box
        self._ent_directory.focus_set()

    def _create_menu(self):
        # will return x11 (Linux), win32 or aqua (macOS)
        gfx_platform = self.tk.call('tk', 'windowingsystem')

        # App menu bar
        self._menu_bar = Menu(self)

        if gfx_platform == "aqua":
            # macOS app menu covering things specific to macOS X
            self._appmenu = Menu(self._menu_bar, name='apple')
            self._appmenu.add_command(label='About PCR Librarian',
                                      command=self._show_about)
            self._appmenu.add_separator()
            self._menu_bar.add_cascade(menu=self._appmenu,
                                       label='PCRLibrarian')

            self.createcommand('tk::mac::ShowPreferences',
                               self._show_preferences)

            filemenu = Menu(self._menu_bar, tearoff=0)
            filemenu.add_command(label="Clear recent directories list",
                                 command=self._on_clear_recent)
            self._menu_bar.add_cascade(label="File", menu=filemenu)
        elif gfx_platform in ["win32", "x11"]:
            # Build a menu for Windows or Linux
            filemenu = Menu(self._menu_bar, tearoff=0)
            filemenu.add_command(label="Clear recent directories list",
                                 command=self._on_clear_recent)
            filemenu.add_separator()
            filemenu.add_command(label="Exit", command=self._on_close)
            self._menu_bar.add_cascade(label="File", menu=filemenu)

            helpmenu = Menu(self._menu_bar, tearoff=0)
            helpmenu.add_command(label="About", command=self._show_about)
            self._menu_bar.add_cascade(label="Help", menu=helpmenu)

        self.config(menu=self._menu_bar)

    def _set_statusbar(self, text):
        """
        Update the status bar
        :param text:
        :return:
        """
        self._v_statusbar.set(text)
        # Force the widget to update now
        self._lbl_statusbar.update()

    def _on_recent_directory(self, event=None):
        directory = self._cb_recent_dirs.get()
        self._set_directory(directory)

        self._set_statusbar("Ready")

    def _on_select_directory(self):
        """
        Select a directory as the source or target of control map(s)
        :return:
        """
        directory = filedialog.askdirectory(
            initialdir=os.getcwd(), title="Select source/target directory")
        self._set_directory(directory)

        self._set_statusbar("Ready")

    def _on_clear_recent(self):
        Configuration.clear_recent()
        self._cb_recent_dirs.config(values=Configuration.get_recent())

    def _set_directory(self, directory):
        if directory:
            Configuration.set_recent(directory)

            self._ent_directory.delete(0, tkinter.END)
            self._ent_directory.insert(0, directory)

            self._load_files()

            self._btn_receive_current_button["state"] = tkinter.NORMAL
            self._btn_receive_all_button["state"] = tkinter.NORMAL

            self._fill_files_listbox()
            self._cb_recent_dirs.config(values=Configuration.get_recent())

    def _on_send(self):
        """
        Send control map(s). Sends all .syx files from selected directory.
        :return:
        """
        selected_port = self._lb_midiout_ports.curselection()
        dlg = SendDlg(self,
                      title="Send Control Map Sysex Files",
                      port=selected_port[0],
                      files=self._files)

    def _on_receive_current_map(self):
        self._set_statusbar("Ready to receive current control map")
        self._on_receive_control_maps(ReceiveDlg.SINGLE)

    def _on_receive_all_maps(self):
        self._set_statusbar("Ready to receive all 15 control maps")
        self._on_receive_control_maps(ReceiveDlg.ALL)

    def _on_receive_control_maps(self, count):
        # Delete existing .syx files
        self._delete_existing_files()

        selected_port = self._lb_midiin_ports.curselection()
        # Modal dialog box for receiving sysex messages from PCR
        dlg = ReceiveDlg(self,
                         title="Receive Current Control Map",
                         port=selected_port[0],
                         dir=self._ent_directory.get(),
                         control_map=count)

        dlg.begin_modal()

        if dlg.result:
            self._set_statusbar("Current control map(s) received")
        else:
            self._set_statusbar("Canceled")
        self._load_files()
        self._fill_files_listbox()

        del dlg

    def _delete_existing_files(self):
        """
        Delete existing .syx files
        :return:
        """
        for file in self._files:
            os.remove(file)
        self._files.clear()
        self._fill_files_listbox()

    def _load_files(self):
        """
        Load all of the .syx files in the selected directory
        :return:
        """
        self._files = []
        directory = self._ent_directory.get()
        self._files.extend(
            sorted([
                os.path.join(directory, fn) for fn in os.listdir(directory)
                if fn.lower().endswith('.syx')
            ]))
        if len(self._files) >= 50:
            self._btn_send_button["state"] = tkinter.NORMAL
        else:
            self._btn_send_button["state"] = tkinter.DISABLED

    def _fill_files_listbox(self):
        """
        Load the files listbox with all of the .syx files in the selected diretory
        :return:
        """
        self._lb_filelist.delete(0, tkinter.END)
        for f in self._files:
            self._lb_filelist.insert(tkinter.END, f)

    def _on_close(self):
        """
        App is closing. Warn user if unsaved changes.
        :return:
        """
        print(self._ent_directory.get())
        # Save the directory setting?
        Configuration.set_last_recent(self._ent_directory.get())
        # Essentially, this terminates the app by destroying the main window
        self.destroy()
        return True

    def _show_about(self):
        about_text = \
            "© 2020 by Dave Hocker\n" + \
            "\n" + \
            "Source: https://github.com/dhocker/pcr_librarian\n" + \
            "License: GNU General Public License v3\n" + \
            "as published by the Free Software Foundation, Inc. "

        # Locate logo image file
        cwd = os.path.realpath(
            os.path.abspath(
                os.path.split(inspect.getfile(inspect.currentframe()))[0]))
        if os.path.exists(cwd + "/pcr_librarian.gif"):
            image_path = cwd + "/pcr_librarian.gif"
        elif os.path.exists(cwd + "/resources/pcr_librarian.gif"):
            image_path = cwd + "/resources/pcr_librarian.gif"
        else:
            image_path = "pcr_librarian.gif"

        # This is a modal message box
        mb = TextMessageBox(self,
                            title="About PCR Librarian",
                            text=about_text,
                            heading="PCR Librarian {}".format(app_version()),
                            image=image_path,
                            width=150,
                            height=110,
                            orient=tkinter.HORIZONTAL)
        mb.show()
        self.wait_window(window=mb)

    def _show_preferences(self):
        tkinter.messagebox.showinfo("Preferences for PCR Librarian",
                                    "None currently defined")
Esempio n. 26
0
class adm_showusers:
    def __init__(self, frame):
        self.myframe = Toplevel(frame)
        self.myframe.wm_title("Employee's List")
        self.myframe.option_add("*tearOff", False)
        self.myframe.geometry("900x500")

        t1 = Label(self.myframe, text="Sort By : ")

        self.mysortby = StringVar()

        self.sortby = Combobox(self.myframe, textvariable=self.mysortby)
        self.sortby.config(values=('Name (A to Z)', 'Name (Z to A)',
                                   'Emp ID (1 to 9)', 'Emp ID (9 to 1)'))
        self.sortby.set("Sorted By")

        self.mysearchby = StringVar()

        self.searchby = Combobox(self.myframe, textvariable=self.mysearchby)
        self.searchby.config(values=('Name', 'Empid', 'Phone Number',
                                     'User type'))
        self.searchby.set("Search By")

        self.e1 = Entry(self.myframe)

        b1 = Button(self.myframe, text="Search")

        mytablearea = Frame(self.myframe, width=800, height=600)
        scrollbarx = Scrollbar(mytablearea, orient=HORIZONTAL)
        scrollbary = Scrollbar(mytablearea, orient=VERTICAL)
        self.mytable = ttk.Treeview(self.myframe,
                                    columns=('empid', 'ename', 'dob',
                                             'address', 'gender', 'phone',
                                             'email', 'doj'),
                                    xscrollcommand=scrollbarx.set,
                                    yscrollcommand=scrollbary.set)

        scrollbarx.config(command=self.mytable.xview)
        scrollbary.config(command=self.mytable.yview)

        scrollbarx.pack(side=BOTTOM, fill=X)
        scrollbary.pack(side=RIGHT, fill=Y)

        self.mytable.heading("empid", text="Employee ID")
        self.mytable.heading("ename", text="Employee Name")
        self.mytable.heading("dob", text="Date of Birth")
        self.mytable.heading("address", text="Address")
        self.mytable.heading("gender", text="Gender")
        self.mytable.heading("phone", text="Phone no")
        self.mytable.heading("email", text="Email ID")
        self.mytable.heading("doj", text="Date Of Joining")

        self.mytable.column('#0', stretch=NO, minwidth=0, width=0)
        self.mytable.column('#1', stretch=NO, width=40)
        self.mytable.column('#2', stretch=NO, width=80)
        self.mytable.column('#3', stretch=NO, width=80)
        self.mytable.column('#4', stretch=NO, width=150)
        self.mytable.column('#5', stretch=NO, width=50)
        self.mytable.column('#6', stretch=NO, width=80)
        self.mytable.column('#7', stretch=NO, width=120)
        self.mytable.column('#8', stretch=NO, width=50)

        self.sortby.bind("<<ComboboxSelected>>",
                         lambda e: self.mysortfunc(self.sortby))
        b1.bind("<Button-1>", lambda e: self.mysearchfunc(self.searchby))

        self.searchby.place(x=50, y=50)
        self.e1.place(x=200, y=50)
        b1.place(x=350, y=50)

        t1.place(x=400, y=50)
        self.sortby.place(x=480, y=50)
        self.mytable.place(x=50, y=100)
        self.fetch_record()

    def fetch_record(self):
        try:
            myresult = []
            mydb = pymysql.connect(host='localhost',
                                   user='******',
                                   password='',
                                   db='hotelmanagementdb')
            with mydb.cursor() as myconn:
                myconn.execute("select * from users")
                myresult = myconn.fetchall()
                self.mytable.delete(*self.mytable.get_children())
                try:
                    if len(myresult) > 0:
                        for myrow in myresult:
                            self.mytable.insert('', END, values=(myrow))
                    else:
                        messagebox.showinfo("No Result",
                                            "No Records found",
                                            parent=self.myframe)
                except Exception as e:
                    messagebox.showerror(
                        "Table Error ",
                        "Record Cann't Inserted in Tabledue to  : " + str(e),
                        parent=self.myframe)
        except Exception as e:
            traceback.print_exc()
            messagebox.showerror("Database Error ",
                                 "Error Occured Due to : " + str(e),
                                 parent=self.myframe)

    def mysortfunc(self, obj):
        self.sorted_record()

    def mysearchfunc(self, obj):
        self.search_record()

    def search_record(self):
        try:

            mydb = pymysql.connect(host='localhost',
                                   user='******',
                                   password='',
                                   db='hotelmanagementdb')
            with mydb.cursor() as myconn:
                # ('Name', 'Empid', 'Phone Number', 'User type')
                if self.mysearchby.get() == 'Name':
                    myconn.execute("select * from users where ename like %s",
                                   (self.e1.get() + "%"))
                elif self.mysortby.get() == 'Empid':
                    myconn.execute("select * from users where empid like %s",
                                   (self.e1.get() + "%"))
                elif self.mysortby.get() == 'Phone Number':
                    myconn.execute("select * from users where phone like %s",
                                   (self.e1.get() + "%"))
                elif self.mysortby.get() == 'User type':
                    myconn.execute(
                        "select * from users where usertype like %s",
                        (self.e1.get() + "%"))

                myresult = myconn.fetchall()
                self.mytable.delete(*self.mytable.get_children())
                try:
                    if len(myresult) > 0:
                        for myrow in myresult:
                            self.mytable.insert('', END, values=(myrow))
                    else:
                        messagebox.showinfo("No Result",
                                            "No Records found",
                                            parent=self.myframe)
                except Exception as e:
                    messagebox.showerror(
                        "Table Error ",
                        "Record Cann't Inserted in Tabledue to  : " + str(e),
                        parent=self.myframe)
        except Exception as e:
            traceback.print_exc()
            messagebox.showerror("Database Error ",
                                 "Error Occured Due to : " + str(e),
                                 parent=self.myframe)

    def sorted_record(self):
        try:
            myresult = []
            mydb = pymysql.connect(host='localhost',
                                   user='******',
                                   password='',
                                   db='hotelmanagementdb')
            with mydb.cursor() as myconn:

                if self.mysortby.get() == 'Name (A to Z)':
                    myconn.execute("select * from users order by ename")
                elif self.mysortby.get() == 'Name (Z to A)':
                    myconn.execute("select * from users order by ename desc")
                elif self.mysortby.get() == 'Emp ID (1 to 9)':
                    myconn.execute("select * from users order by empid")
                elif self.mysortby.get() == 'Emp ID (9 to 1)':
                    myconn.execute("select * from users order by empid desc")

                myresult = myconn.fetchall()
                self.mytable.delete(*self.mytable.get_children())
                try:
                    if len(myresult) > 0:
                        for myrow in myresult:
                            self.mytable.insert('', END, values=(myrow))
                    else:
                        messagebox.showinfo("No Result",
                                            "No Records found",
                                            parent=self.myframe)
                except Exception as e:
                    messagebox.showerror(
                        "Table Error ",
                        "Record Cann't Inserted in Tabledue to  : " + str(e),
                        parent=self.myframe)
        except Exception as e:
            traceback.print_exc()
            messagebox.showerror("Database Error ",
                                 "Error Occured Due to : " + str(e),
                                 parent=self.myframe)
class bookroom:
    def __init__(self, frame):
        self.myframe = Toplevel(frame)
        self.myframe.wm_title(" Booking Room ")
        self.myframe.geometry("700x250")

        t1 = Label(self.myframe, text="Customer Id ")
        t2 = Label(self.myframe, text="Customer Name ")
        t3 = Label(self.myframe, text="Room Type ")
        t4 = Label(self.myframe, text="Room No. ")
        t5 = Label(self.myframe, text="Check In ")
        t6 = Label(self.myframe, text="Check Out ")
        t7 = Label(self.myframe, text="Advance Payment ")

        self.e1 = Entry(self.myframe)
        self.e2 = Entry(self.myframe)
        self.e3 = Entry(self.myframe)

        self.myroomtype = StringVar()
        self.c1 = Combobox(self.myframe, textvariable=self.myroomtype)
        self.c1.config(values=('Single', 'Double', 'Triple', 'Quad', 'Queen',
                               'King', 'Twin', 'Double-Double', 'Studio'))

        self.myroomno = StringVar()
        self.c2 = Combobox(self.myframe, textvariable=self.myroomno)

        self.check_in = DateEntry(self.myframe,
                                  width=12,
                                  background='darkblue',
                                  foreground='white',
                                  borderwidth=2)
        self.check_out = DateEntry(self.myframe,
                                   width=12,
                                   background='darkblue',
                                   foreground='white',
                                   borderwidth=2)

        self.b1 = Button(self.myframe, text="Book Room", bg="red", fg="white")

        t1.place(x=50, y=50)
        t2.place(x=380, y=50)
        t3.place(x=50, y=80)
        t4.place(x=380, y=80)
        t5.place(x=50, y=110)
        t6.place(x=380, y=110)
        t7.place(x=50, y=140)

        self.e1.place(x=200, y=50)
        self.e2.place(x=480, y=50)
        self.c1.place(x=200, y=80)
        self.c2.place(x=480, y=80)
        self.check_in.place(x=200, y=110)
        self.check_out.place(x=480, y=110)
        self.e3.place(x=200, y=140)

        self.b1.place(x=200, y=190)

        self.e1.bind("<FocusIn>", lambda e: self.getnormal())
        self.e1.bind("<FocusOut>", lambda e: self.get_cus_info())
        self.c1.bind("<<ComboboxSelected>>", lambda e: self.get_roomno())
        self.b1.bind("<Button-1>", lambda e: self.booking_room())

    def getnormal(self):
        self.e2.config(state="normal")

    def get_roomno(self):
        myno = []
        try:
            mydb = pymysql.connect(host='localhost',
                                   user='******',
                                   password='',
                                   db='hotelmanagementdb')
            with mydb.cursor() as mycon:
                mycon.execute(
                    "select room_no from room where status=%s and room_type=%s",
                    ("Available", self.myroomtype.get()))
                myresult = mycon.fetchall()
                mydb.commit()
                if len(myresult) > 0:
                    for i in range(len(myresult)):
                        myno.append(str(myresult[i][0]))
                self.c2.config(values=myno)
        except Exception as e:
            messagebox.showerror("Database Error",
                                 "Error Occured Due to " + str(e))

    def get_cus_info(self):
        try:
            self.e2.delete(0, END)
            mydb = pymysql.connect(host='localhost',
                                   user='******',
                                   password='',
                                   db='hotelmanagementdb')
            with mydb.cursor() as mycon:
                mycon.execute(
                    "select customer_name from customer where customer_id=%s",
                    (self.e1.get()))
                myresult = mycon.fetchone()
                mydb.commit()
                if len(myresult) > 0:
                    self.e2.insert(0, str(myresult[0]))
                    self.e2.config(state="readonly")
        except Exception as e:
            messagebox.showerror("Database Error",
                                 "Error Occured Due to " + str(e))

    def booking_room(self):
        try:
            mydb = pymysql.connect(host='localhost',
                                   user='******',
                                   password='',
                                   db='hotelmanagementdb')
            with mydb.cursor() as myconn:
                # customer_id,checkin,checkout,adv_amt,status
                # room_no,customer_id,customer_name,check_in,check_out,advance_payment
                myconn.execute(
                    "update room set status=%s where room_no =%s and room_type=%s",
                    ("Book", self.myroomno.get(), self.myroomtype.get()))
                try:
                    myconn.execute(
                        "insert into room_history values(%s,%s,%s,%s,%s,%s,%s)",
                        (self.myroomno.get(), self.myroomtype.get(),
                         self.e1.get(), self.e2.get(),
                         self.check_in.get_date(), self.check_out.get_date(),
                         self.e3.get()))
                except Exception as ex:
                    messagebox.showerror(
                        "Database Error",
                        "Error Occured in Room History Table due to \n" +
                        str(ex))
                mydb.commit()
                messagebox.showinfo(
                    "Room Booked", " Room No. " + self.myroomno.get() +
                    "  Booked To " + self.e2.get() + "\n from : " +
                    str(self.check_in.get_date()) + "  to : " +
                    str(self.check_out.get_date()))
        except Exception as e:
            messagebox.showerror("Database Error",
                                 "Error Occured Due to " + str(e))
Esempio n. 28
0
 def callback(combobox: ttk.Combobox):
     """Reduce the displayed values to substring matches to the user's input."""
     text = combobox.get()
     combobox.config(values=sorted(list(n for n in names if text in n)))
class Nse:
    def __init__(self, window: Tk):
        self.seconds = 60
        self.stdout = sys.stdout
        self.stderr = sys.stderr
        self.previous_date = None
        self.previous_time = None
        self.first_run = True
        self.stop = False
        self.logging = False
        self.dates = [""]
        self.indices = ["NIFTY", "BANKNIFTY", "NIFTYIT"]
        self.headers = {
            'user-agent':
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, '
            'like Gecko) '
            'Chrome/80.0.3987.149 Safari/537.36',
            'accept-language':
            'en,gu;q=0.9,hi;q=0.8',
            'accept-encoding':
            'gzip, deflate, br'
        }
        self.url_oc = "https://www.nseindia.com/option-chain"
        self.session = requests.Session()
        self.cookies = {}
        self.login_win(window)

    def get_data(self, event=None):
        if self.first_run:
            return self.get_data_first_run()
        else:
            return self.get_data_refresh()

    def get_data_first_run(self):
        request = None
        response = None
        self.index = self.index_var.get()
        try:
            url = f"https://www.nseindia.com/api/option-chain-indices?symbol={self.index}"
            request = self.session.get(self.url_oc,
                                       headers=self.headers,
                                       timeout=5)
            self.cookies = dict(request.cookies)
            response = self.session.get(url,
                                        headers=self.headers,
                                        timeout=5,
                                        cookies=self.cookies)
        except Exception as err:
            print(request)
            print(response)
            print(err, "1")
            messagebox.showerror(
                title="Error",
                message="Error in fetching dates.\nPlease retry.")
            self.dates.clear()
            self.dates = [""]
            self.date_menu.config(values=tuple(self.dates))
            self.date_menu.current(0)
            return
        if response is not None:
            try:
                json_data = response.json()
            except Exception as err:
                print(response)
                print(err, "2")
                json_data = {}
        else:
            json_data = {}
        if json_data == {}:
            messagebox.showerror(
                title="Error",
                message="Error in fetching dates.\nPlease retry.")
            self.dates.clear()
            self.dates = [""]
            try:
                self.date_menu.config(values=tuple(self.dates))
                self.date_menu.current(0)
            except TclError as err:
                print(err, "3")
            return
        self.dates.clear()
        for dates in json_data['records']['expiryDates']:
            self.dates.append(dates)
        try:
            self.date_menu.config(values=tuple(self.dates))
            self.date_menu.current(0)
        except TclError as err:
            print(err, "4")

        return response, json_data

    def get_data_refresh(self):
        request = None
        response = None
        try:
            url = f"https://www.nseindia.com/api/option-chain-indices?symbol={self.index}"
            response = self.session.get(url,
                                        headers=self.headers,
                                        timeout=5,
                                        cookies=self.cookies)
            if response.status_code == 401:
                self.session.close()
                self.session = requests.Session()
                url = f"https://www.nseindia.com/api/option-chain-indices?symbol={self.index}"
                request = self.session.get(self.url_oc,
                                           headers=self.headers,
                                           timeout=5)
                self.cookies = dict(request.cookies)
                response = self.session.get(url,
                                            headers=self.headers,
                                            timeout=5,
                                            cookies=self.cookies)
                print("reset cookies")
        except Exception as err:
            print(request)
            print(response)
            print(err, "5")
            try:
                self.session.close()
                self.session = requests.Session()
                url = f"https://www.nseindia.com/api/option-chain-indices?symbol={self.index}"
                request = self.session.get(self.url_oc,
                                           headers=self.headers,
                                           timeout=5)
                self.cookies = dict(request.cookies)
                response = self.session.get(url,
                                            headers=self.headers,
                                            timeout=5,
                                            cookies=self.cookies)
                print("reset cookies")
            except Exception as err:
                print(request)
                print(response)
                print(err, "6")
                return
        if response is not None:
            try:
                json_data = response.json()
            except Exception as err:
                print(response)
                print(err, "7")
                json_data = {}
        else:
            json_data = {}
        if json_data == {}:
            return

        return response, json_data

    def login_win(self, window: Tk):
        self.login = window
        self.login.title("NSE")
        window_width = self.login.winfo_reqwidth()
        window_height = self.login.winfo_reqheight()
        position_right = int(self.login.winfo_screenwidth() / 2 -
                             window_width / 2)
        position_down = int(self.login.winfo_screenheight() / 2 -
                            window_height / 2)
        self.login.geometry("260x90+{}+{}".format(position_right,
                                                  position_down))

        self.index_var = StringVar()
        self.index_var.set(self.indices[0])
        self.dates_var = StringVar()
        self.dates_var.set(self.dates[0])

        index_label = Label(self.login, text="Index: ", justify=LEFT)
        index_label.grid(row=0, column=0, sticky=N + S + W)
        self.index_menu = Combobox(self.login,
                                   textvariable=self.index_var,
                                   values=self.indices)
        self.index_menu.config(width=15)
        self.index_menu.grid(row=0, column=1, sticky=N + S + E)
        date_label = Label(self.login, text="Expiry Date: ", justify=LEFT)
        date_label.grid(row=1, column=0, sticky=N + S + E)
        self.date_menu = Combobox(self.login, textvariable=self.dates_var)
        self.date_menu.config(width=15)
        self.date_menu.grid(row=1, column=1, sticky=N + S + E)
        self.date_get = Button(self.login,
                               text="Refresh",
                               command=self.get_data)
        self.date_get.grid(row=1, column=2, sticky=N + S + E)
        sp_label = Label(self.login, text="Strike Price: ")
        sp_label.grid(row=2, column=0, sticky=N + S + E)
        self.sp_entry = Entry(self.login, width=18)
        self.sp_entry.grid(row=2, column=1, sticky=N + S + E)
        start_btn = Button(self.login, text="Start", command=self.start)
        start_btn.grid(row=2, column=2, sticky=N + S + E + W)
        self.sp_entry.focus_set()
        self.get_data()

        def focus_widget(event, mode: int):
            if mode == 1:
                self.get_data()
                self.date_menu.focus_set()
            elif mode == 2:
                self.sp_entry.focus_set()

        self.index_menu.bind('<Return>',
                             lambda event, a=1: focus_widget(event, a))
        self.index_menu.bind("<<ComboboxSelected>>", self.get_data)
        self.date_menu.bind('<Return>',
                            lambda event, a=2: focus_widget(event, a))
        self.sp_entry.bind('<Return>', self.start)

        self.login.mainloop()

    def start(self, event=None):
        self.expiry_date = self.dates_var.get()
        if self.expiry_date == "":
            messagebox.showerror(
                title="Error",
                message=
                "Incorrect Expiry Date.\nPlease enter correct Expiry Date.")
            return
        try:
            self.sp = int(self.sp_entry.get())
            self.login.destroy()
            self.main_win()
        except ValueError as err:
            print(err, "8")
            messagebox.showerror(
                title="Error",
                message=
                "Incorrect Strike Price.\nPlease enter correct Strike Price.")

    def change_state(self, event=None):

        if not self.stop:
            self.stop = True
            self.options.entryconfig(self.options.index(0),
                                     label="Start   (Ctrl+X)")
            messagebox.showinfo(title="Stopped",
                                message="Scraping new data has been stopped.")
        else:
            self.stop = False
            self.options.entryconfig(self.options.index(0),
                                     label="Stop   (Ctrl+X)")
            messagebox.showinfo(title="Started",
                                message="Scraping new data has been started.")

            self.main()

    def export(self, event=None):
        sheet_data = self.sheet.get_sheet_data()

        try:
            with open("NSE-Option-Chain-Analyzer.csv", "a", newline="") as row:
                data_writer = csv.writer(row)
                data_writer.writerows(sheet_data)

            messagebox.showinfo(
                title="Export Complete",
                message=
                "Data has been exported to NSE-Option-Chain-Analyzer.csv.")
        except Exception as err:
            print(err, "9")
            messagebox.showerror(
                title="Export Failed",
                message="An error occurred while exporting the data.")

    def log(self, event=None):
        if not self.logging:
            streamtologger.redirect(
                target="nse.log",
                header_format="[{timestamp:%Y-%m-%d %H:%M:%S} - {level:5}] ")
            self.logging = True
            self.options.entryconfig(self.options.index(2),
                                     label="Logging: On   (Ctrl+L)")
            messagebox.showinfo(title="Started",
                                message="Debug Logging has been enabled.")
        elif self.logging:
            sys.stdout = self.stdout
            sys.stderr = self.stderr
            streamtologger._is_redirected = False
            self.logging = False
            self.options.entryconfig(self.options.index(2),
                                     label="Logging: Off   (Ctrl+L)")
            messagebox.showinfo(title="Stopped",
                                message="Debug Logging has been disabled.")

    def links(self, link: str, event=None):

        if link == "developer":
            webbrowser.open_new("https://github.com/VarunS2002/")
        elif link == "readme":
            webbrowser.open_new(
                "https://github.com/VarunS2002/Python-NSE-Option-Chain-Analyzer/blob/master/README.md/"
            )
        elif link == "license":
            webbrowser.open_new(
                "https://github.com/VarunS2002/Python-NSE-Option-Chain-Analyzer/blob/master/LICENSE/"
            )
        elif link == "releases":
            webbrowser.open_new(
                "https://github.com/VarunS2002/Python-NSE-Option-Chain-Analyzer/releases/"
            )
        elif link == "sources":
            webbrowser.open_new(
                "https://github.com/VarunS2002/Python-NSE-Option-Chain-Analyzer/"
            )

        self.info.attributes('-topmost', False)

    def about_window(self) -> Toplevel:
        self.info = Toplevel()
        self.info.title("About")
        window_width = self.info.winfo_reqwidth()
        window_height = self.info.winfo_reqheight()
        position_right = int(self.info.winfo_screenwidth() / 2 -
                             window_width / 2)
        position_down = int(self.info.winfo_screenheight() / 2 -
                            window_height / 2)
        self.info.geometry("250x150+{}+{}".format(position_right,
                                                  position_down))
        self.info.attributes('-topmost', True)
        self.info.grab_set()
        self.info.focus_force()

        return self.info

    def about(self, event=None):
        self.info = self.about_window()
        self.info.rowconfigure(0, weight=1)
        self.info.rowconfigure(1, weight=1)
        self.info.rowconfigure(2, weight=1)
        self.info.rowconfigure(3, weight=1)
        self.info.rowconfigure(4, weight=1)
        self.info.columnconfigure(0, weight=1)
        self.info.columnconfigure(1, weight=1)

        heading = Label(self.info,
                        text="NSE-Option-Chain-Analyzer",
                        relief=RIDGE,
                        font=("TkDefaultFont", 10, "bold"))
        heading.grid(row=0, column=0, columnspan=2, sticky=N + S + W + E)
        version_label = Label(self.info, text="Version:", relief=RIDGE)
        version_label.grid(row=1, column=0, sticky=N + S + W + E)
        version_val = Label(self.info, text="3.5", relief=RIDGE)
        version_val.grid(row=1, column=1, sticky=N + S + W + E)
        dev_label = Label(self.info, text="Developer:", relief=RIDGE)
        dev_label.grid(row=2, column=0, sticky=N + S + W + E)
        dev_val = Label(self.info,
                        text="Varun Shanbhag",
                        fg="blue",
                        cursor="hand2",
                        relief=RIDGE)
        dev_val.bind("<Button-1>",
                     lambda click, link="developer": self.links(link, click))
        dev_val.grid(row=2, column=1, sticky=N + S + W + E)
        readme = Label(self.info,
                       text="README",
                       fg="blue",
                       cursor="hand2",
                       relief=RIDGE)
        readme.bind("<Button-1>",
                    lambda click, link="readme": self.links(link, click))
        readme.grid(row=3, column=0, sticky=N + S + W + E)
        licenses = Label(self.info,
                         text="License",
                         fg="blue",
                         cursor="hand2",
                         relief=RIDGE)
        licenses.bind("<Button-1>",
                      lambda click, link="license": self.links(link, click))
        licenses.grid(row=3, column=1, sticky=N + S + W + E)
        releases = Label(self.info,
                         text="Releases",
                         fg="blue",
                         cursor="hand2",
                         relief=RIDGE)
        releases.bind("<Button-1>",
                      lambda click, link="releases": self.links(link, click))
        releases.grid(row=4, column=0, sticky=N + S + W + E)
        sources = Label(self.info,
                        text="Sources",
                        fg="blue",
                        cursor="hand2",
                        relief=RIDGE)
        sources.bind("<Button-1>",
                     lambda click, link="sources": self.links(link, click))
        sources.grid(row=4, column=1, sticky=N + S + W + E)

        self.info.mainloop()

    def close(self, event=None):
        ask_quit = messagebox.askyesno(
            "Quit",
            "All unsaved data will be lost.\nProceed to quit?",
            icon='warning',
            default='no')
        if ask_quit:
            self.session.close()
            self.root.destroy()
            sys.exit()
        elif not ask_quit:
            pass

    def main_win(self):
        self.root = Tk()
        self.root.focus_force()
        self.root.title("NSE-Option-Chain-Analyzer")
        self.root.protocol('WM_DELETE_WINDOW', self.close)
        window_width = self.root.winfo_reqwidth()
        window_height = self.root.winfo_reqheight()
        position_right = int(self.root.winfo_screenwidth() / 3 -
                             window_width / 2)
        position_down = int(self.root.winfo_screenheight() / 3 -
                            window_height / 2)
        self.root.geometry("815x510+{}+{}".format(position_right,
                                                  position_down))
        self.root.rowconfigure(0, weight=1)
        self.root.columnconfigure(0, weight=1)

        menubar = Menu(self.root)
        self.options = Menu(menubar, tearoff=0)
        self.options.add_command(label="Stop   (Ctrl+X)",
                                 command=self.change_state)
        self.options.add_command(label="Export to CSV   (Ctrl+S)",
                                 command=self.export)
        self.options.add_command(label="Logging: Off   (Ctrl+L)",
                                 command=self.log)
        self.options.add_separator()
        self.options.add_command(label="About   (Ctrl+M)", command=self.about)
        self.options.add_command(label="Quit   (Ctrl+Q)", command=self.close)
        menubar.add_cascade(label="Menu", menu=self.options)
        self.root.config(menu=menubar)

        self.root.bind('<Control-s>', self.export)
        self.root.bind('<Control-l>', self.log)
        self.root.bind('<Control-x>', self.change_state)
        self.root.bind('<Control-m>', self.about)
        self.root.bind('<Control-q>', self.close)

        top_frame = Frame(self.root)
        top_frame.rowconfigure(0, weight=1)
        top_frame.columnconfigure(0, weight=1)
        top_frame.pack(fill="both", expand=True)

        output_columns = ('Time', 'Value', 'Call Sum\n(in K)',
                          'Put Sum\n(in K)', 'Difference\n(in K)',
                          'Call Boundary\n(in K)', 'Put Boundary\n(in K)',
                          'Call ITM', 'Put ITM')
        self.sheet = tksheet.Sheet(top_frame,
                                   column_width=85,
                                   align="center",
                                   headers=output_columns,
                                   header_font=("TkDefaultFont", 9, "bold"),
                                   empty_horizontal=0,
                                   empty_vertical=20,
                                   header_height=35)
        self.sheet.enable_bindings(
            ("toggle_select", "drag_select", "column_select", "row_select",
             "column_width_resize", "arrowkeys", "right_click_popup_menu",
             "rc_select", "copy", "select_all"))
        self.sheet.grid(row=0, column=0, sticky=N + S + W + E)

        bottom_frame = Frame(self.root)
        bottom_frame.rowconfigure(0, weight=1)
        bottom_frame.rowconfigure(1, weight=1)
        bottom_frame.rowconfigure(2, weight=1)
        bottom_frame.rowconfigure(3, weight=1)
        bottom_frame.rowconfigure(4, weight=1)
        bottom_frame.columnconfigure(0, weight=1)
        bottom_frame.columnconfigure(1, weight=1)
        bottom_frame.columnconfigure(2, weight=1)
        bottom_frame.columnconfigure(3, weight=1)
        bottom_frame.columnconfigure(4, weight=1)
        bottom_frame.columnconfigure(5, weight=1)
        bottom_frame.columnconfigure(6, weight=1)
        bottom_frame.columnconfigure(7, weight=1)
        bottom_frame.pack(fill="both", expand=True)

        oi_ub_label = Label(bottom_frame,
                            text="Open Interest Upper Boundary",
                            relief=RIDGE,
                            font=("TkDefaultFont", 10, "bold"))
        oi_ub_label.grid(row=0, column=0, columnspan=4, sticky=N + S + W + E)
        max_call_oi_sp_label = Label(bottom_frame,
                                     text="Strike Price:",
                                     relief=RIDGE,
                                     font=("TkDefaultFont", 9, "bold"))
        max_call_oi_sp_label.grid(row=1, column=0, sticky=N + S + W + E)
        self.max_call_oi_sp_val = Label(bottom_frame, text="", relief=RIDGE)
        self.max_call_oi_sp_val.grid(row=1, column=1, sticky=N + S + W + E)
        max_call_oi_label = Label(bottom_frame,
                                  text="OI (in K):",
                                  relief=RIDGE,
                                  font=("TkDefaultFont", 9, "bold"))
        max_call_oi_label.grid(row=1, column=2, sticky=N + S + W + E)
        self.max_call_oi_val = Label(bottom_frame, text="", relief=RIDGE)
        self.max_call_oi_val.grid(row=1, column=3, sticky=N + S + W + E)
        oi_lb_label = Label(bottom_frame,
                            text="Open Interest Lower Boundary",
                            relief=RIDGE,
                            font=("TkDefaultFont", 10, "bold"))
        oi_lb_label.grid(row=0, column=4, columnspan=4, sticky=N + S + W + E)
        max_put_oi_sp_label = Label(bottom_frame,
                                    text="Strike Price:",
                                    relief=RIDGE,
                                    font=("TkDefaultFont", 9, "bold"))
        max_put_oi_sp_label.grid(row=1, column=4, sticky=N + S + W + E)
        self.max_put_oi_sp_val = Label(bottom_frame, text="", relief=RIDGE)
        self.max_put_oi_sp_val.grid(row=1, column=5, sticky=N + S + W + E)
        max_put_oi_label = Label(bottom_frame,
                                 text="OI (in K):",
                                 relief=RIDGE,
                                 font=("TkDefaultFont", 9, "bold"))
        max_put_oi_label.grid(row=1, column=6, sticky=N + S + W + E)
        self.max_put_oi_val = Label(bottom_frame, text="", relief=RIDGE)
        self.max_put_oi_val.grid(row=1, column=7, sticky=N + S + W + E)

        oi_label = Label(bottom_frame,
                         text="Open Interest:",
                         relief=RIDGE,
                         font=("TkDefaultFont", 9, "bold"))
        oi_label.grid(row=2, column=0, columnspan=2, sticky=N + S + W + E)
        self.oi_val = Label(bottom_frame, text="", relief=RIDGE)
        self.oi_val.grid(row=2, column=2, columnspan=2, sticky=N + S + W + E)
        pcr_label = Label(bottom_frame,
                          text="PCR:",
                          relief=RIDGE,
                          font=("TkDefaultFont", 9, "bold"))
        pcr_label.grid(row=2, column=4, columnspan=2, sticky=N + S + W + E)
        self.pcr_val = Label(bottom_frame, text="", relief=RIDGE)
        self.pcr_val.grid(row=2, column=6, columnspan=2, sticky=N + S + W + E)
        call_exits_label = Label(bottom_frame,
                                 text="Call Exits:",
                                 relief=RIDGE,
                                 font=("TkDefaultFont", 9, "bold"))
        call_exits_label.grid(row=3,
                              column=0,
                              columnspan=2,
                              sticky=N + S + W + E)
        self.call_exits_val = Label(bottom_frame, text="", relief=RIDGE)
        self.call_exits_val.grid(row=3,
                                 column=2,
                                 columnspan=2,
                                 sticky=N + S + W + E)
        put_exits_label = Label(bottom_frame,
                                text="Put Exits:",
                                relief=RIDGE,
                                font=("TkDefaultFont", 9, "bold"))
        put_exits_label.grid(row=3,
                             column=4,
                             columnspan=2,
                             sticky=N + S + W + E)
        self.put_exits_val = Label(bottom_frame, text="", relief=RIDGE)
        self.put_exits_val.grid(row=3,
                                column=6,
                                columnspan=2,
                                sticky=N + S + W + E)
        call_itm_label = Label(bottom_frame,
                               text="Call ITM:",
                               relief=RIDGE,
                               font=("TkDefaultFont", 9, "bold"))
        call_itm_label.grid(row=4,
                            column=0,
                            columnspan=2,
                            sticky=N + S + W + E)
        self.call_itm_val = Label(bottom_frame, text="", relief=RIDGE)
        self.call_itm_val.grid(row=4,
                               column=2,
                               columnspan=2,
                               sticky=N + S + W + E)
        put_itm_label = Label(bottom_frame,
                              text="Put ITM:",
                              relief=RIDGE,
                              font=("TkDefaultFont", 9, "bold"))
        put_itm_label.grid(row=4, column=4, columnspan=2, sticky=N + S + W + E)
        self.put_itm_val = Label(bottom_frame, text="", relief=RIDGE)
        self.put_itm_val.grid(row=4,
                              column=6,
                              columnspan=2,
                              sticky=N + S + W + E)

        self.root.after(100, self.main)

        self.root.mainloop()

    def get_dataframe(self):
        try:
            response, json_data = self.get_data()
        except TypeError:
            return
        if response is None or json_data is None:
            return

        pandas.set_option('display.max_rows', None)
        pandas.set_option('display.max_columns', None)
        pandas.set_option('display.width', 400)

        df = pandas.read_json(response.text)
        df = df.transpose()

        ce_values = [
            data['CE'] for data in json_data['records']['data']
            if "CE" in data and str(
                data['expiryDate'].lower() == str(self.expiry_date).lower())
        ]
        pe_values = [
            data['PE'] for data in json_data['records']['data']
            if "PE" in data and str(
                data['expiryDate'].lower() == str(self.expiry_date).lower())
        ]
        underlying_stock = ce_values[0]['underlying']
        points = pe_values[0]['underlyingValue']
        ce_data = pandas.DataFrame(ce_values)
        pe_data = pandas.DataFrame(pe_values)
        ce_data_f = ce_data.loc[ce_data['expiryDate'] == self.expiry_date]
        pe_data_f = pe_data.loc[pe_data['expiryDate'] == self.expiry_date]
        if ce_data_f.empty:
            messagebox.showerror(
                title="Error",
                message=
                "Invalid Expiry Date.\nPlease restart and enter a new Expiry Date."
            )
            self.change_state()
            return
        columns_ce = [
            'openInterest', 'changeinOpenInterest', 'totalTradedVolume',
            'impliedVolatility', 'lastPrice', 'change', 'bidQty', 'bidprice',
            'askPrice', 'askQty', 'strikePrice'
        ]
        columns_pe = [
            'strikePrice', 'bidQty', 'bidprice', 'askPrice', 'askQty',
            'change', 'lastPrice', 'impliedVolatility', 'totalTradedVolume',
            'changeinOpenInterest', 'openInterest'
        ]
        ce_data_f = ce_data_f[columns_ce]
        pe_data_f = pe_data_f[columns_pe]
        merged_inner = pandas.merge(left=ce_data_f,
                                    right=pe_data_f,
                                    left_on='strikePrice',
                                    right_on='strikePrice')
        merged_inner.columns = [
            'Open Interest', 'Change in Open Interest', 'Traded Volume',
            'Implied Volatility', 'Last Traded Price', 'Net Change',
            'Bid Quantity', 'Bid Price', 'Ask Price', 'Ask Quantity',
            'Strike Price', 'Bid Quantity', 'Bid Price', 'Ask Price',
            'Ask Quantity', 'Net Change', 'Last Traded Price',
            'Implied Volatility', 'Traded Volume', 'Change in Open Interest',
            'Open Interest'
        ]
        return merged_inner, df['timestamp'][
            'records'], underlying_stock, points

    def set_values(self):
        self.root.title(
            f"NSE-Option-Chain-Analyzer - {self.underlying_stock} - {self.expiry_date} - {self.sp}"
        )

        self.max_call_oi_val.config(text=self.max_call_oi)
        self.max_call_oi_sp_val.config(text=self.max_call_oi_sp)
        self.max_put_oi_val.config(text=self.max_put_oi)
        self.max_put_oi_sp_val.config(text=self.max_put_oi_sp)

        red = "#e53935"
        green = "#00e676"
        default = "SystemButtonFace"

        if self.call_sum >= self.put_sum:
            self.oi_val.config(text="Bearish", bg=red)
        else:
            self.oi_val.config(text="Bullish", bg=green)
        if self.put_call_ratio >= 1:
            self.pcr_val.config(text=self.put_call_ratio, bg=green)
        else:
            self.pcr_val.config(text=self.put_call_ratio, bg=red)

        def set_itm_labels(call_change: float, put_change: float) -> str:
            label = "No"
            if put_change > call_change:
                if put_change >= 0:
                    if call_change <= 0:
                        label = "Yes"
                    elif put_change / call_change > 1.5:
                        label = "Yes"
                else:
                    if put_change / call_change < 0.5:
                        label = "Yes"
            if call_change <= 0:
                label = "Yes"
            return label

        call = set_itm_labels(call_change=self.p5, put_change=self.p4)

        if call == "No":
            self.call_itm_val.config(text="No", bg=default)
        else:
            self.call_itm_val.config(text="Yes", bg=green)

        put = set_itm_labels(call_change=self.p7, put_change=self.p6)

        if put == "No":
            self.put_itm_val.config(text="No", bg=default)
        else:
            self.put_itm_val.config(text="Yes", bg=red)

        if self.call_boundary <= 0:
            self.call_exits_val.config(text="Yes", bg=green)
        elif self.call_sum <= 0:
            self.call_exits_val.config(text="Yes", bg=green)
        else:
            self.call_exits_val.config(text="No", bg=default)
        if self.put_boundary <= 0:
            self.put_exits_val.config(text="Yes", bg=red)
        elif self.put_sum <= 0:
            self.put_exits_val.config(text="Yes", bg=red)
        else:
            self.put_exits_val.config(text="No", bg=default)

        output_values = [
            self.str_current_time, self.points, self.call_sum, self.put_sum,
            self.difference, self.call_boundary, self.put_boundary,
            self.call_itm, self.put_itm
        ]
        self.sheet.insert_row(values=output_values)

        last_row = self.sheet.get_total_rows() - 1

        if self.first_run or self.points == self.old_points:
            self.old_points = self.points
        elif self.points > self.old_points:
            self.sheet.highlight_cells(row=last_row, column=1, bg=green)
            self.old_points = self.points
        else:
            self.sheet.highlight_cells(row=last_row, column=1, bg=red)
            self.old_points = self.points
        if self.first_run or self.old_call_sum == self.call_sum:
            self.old_call_sum = self.call_sum
        elif self.call_sum > self.old_call_sum:
            self.sheet.highlight_cells(row=last_row, column=2, bg=red)
            self.old_call_sum = self.call_sum
        else:
            self.sheet.highlight_cells(row=last_row, column=2, bg=green)
            self.old_call_sum = self.call_sum
        if self.first_run or self.old_put_sum == self.put_sum:
            self.old_put_sum = self.put_sum
        elif self.put_sum > self.old_put_sum:
            self.sheet.highlight_cells(row=last_row, column=3, bg=green)
            self.old_put_sum = self.put_sum
        else:
            self.sheet.highlight_cells(row=last_row, column=3, bg=red)
            self.old_put_sum = self.put_sum
        if self.first_run or self.old_difference == self.difference:
            self.old_difference = self.difference
        elif self.difference > self.old_difference:
            self.sheet.highlight_cells(row=last_row, column=4, bg=red)
            self.old_difference = self.difference
        else:
            self.sheet.highlight_cells(row=last_row, column=4, bg=green)
            self.old_difference = self.difference
        if self.first_run or self.old_call_boundary == self.call_boundary:
            self.old_call_boundary = self.call_boundary
        elif self.call_boundary > self.old_call_boundary:
            self.sheet.highlight_cells(row=last_row, column=5, bg=red)
            self.old_call_boundary = self.call_boundary
        else:
            self.sheet.highlight_cells(row=last_row, column=5, bg=green)
            self.old_call_boundary = self.call_boundary
        if self.first_run or self.old_put_boundary == self.put_boundary:
            self.old_put_boundary = self.put_boundary
        elif self.put_boundary > self.old_put_boundary:
            self.sheet.highlight_cells(row=last_row, column=6, bg=green)
            self.old_put_boundary = self.put_boundary
        else:
            self.sheet.highlight_cells(row=last_row, column=6, bg=red)
            self.old_put_boundary = self.put_boundary
        if self.first_run or self.old_call_itm == self.call_itm:
            self.old_call_itm = self.call_itm
        elif self.call_itm > self.old_call_itm:
            self.sheet.highlight_cells(row=last_row, column=7, bg=green)
            self.old_call_itm = self.call_itm
        else:
            self.sheet.highlight_cells(row=last_row, column=7, bg=red)
            self.old_call_itm = self.call_itm
        if self.first_run or self.old_put_itm == self.put_itm:
            self.old_put_itm = self.put_itm
        elif self.put_itm > self.old_put_itm:
            self.sheet.highlight_cells(row=last_row, column=8, bg=red)
            self.old_put_itm = self.put_itm
        else:
            self.sheet.highlight_cells(row=last_row, column=8, bg=green)
            self.old_put_itm = self.put_itm

        if self.sheet.get_yview()[1] >= 0.9:
            self.sheet.see(last_row)
            self.sheet.set_yview(1)
        self.sheet.refresh()

    def main(self):
        if self.stop:
            return

        try:
            df, current_time, self.underlying_stock, self.points = self.get_dataframe(
            )
        except TypeError:
            self.root.after((self.seconds * 1000), self.main)
            return

        self.str_current_time = current_time.split(" ")[1]
        current_date = datetime.datetime.strptime(
            current_time.split(" ")[0], '%d-%b-%Y').date()
        current_time = datetime.datetime.strptime(
            current_time.split(" ")[1], '%H:%M:%S').time()
        if self.first_run:
            self.previous_date = current_date
            self.previous_time = current_time
        elif current_date > self.previous_date:
            self.previous_date = current_date
            self.previous_time = current_time
        elif current_date == self.previous_date:
            if current_time > self.previous_time:
                self.previous_time = current_time
            else:
                self.root.after((self.seconds * 1000), self.main)
                return

        call_oi_list = []
        for i in range(len(df)):
            int_call_oi = int(df.iloc[i, [0]][0])
            call_oi_list.append(int_call_oi)
        call_oi_index = call_oi_list.index(max(call_oi_list))
        self.max_call_oi = round(max(call_oi_list) / 1000, 1)

        put_oi_list = []
        for i in range(len(df)):
            int_put_oi = int(df.iloc[i, [20]][0])
            put_oi_list.append(int_put_oi)
        put_oi_index = put_oi_list.index(max(put_oi_list))
        self.max_put_oi = round(max(put_oi_list) / 1000, 1)

        total_call_oi = sum(call_oi_list)
        total_put_oi = sum(put_oi_list)
        try:
            self.put_call_ratio = round(total_put_oi / total_call_oi, 2)
        except ZeroDivisionError:
            self.put_call_ratio = 0

        self.max_call_oi_sp = df.iloc[call_oi_index]['Strike Price']
        self.max_put_oi_sp = df.iloc[put_oi_index]['Strike Price']

        try:
            index = int(df[df['Strike Price'] == self.sp].index.tolist()[0])
        except IndexError as err:
            print(err, "10")
            messagebox.showerror(
                title="Error",
                message=
                "Incorrect Strike Price.\nPlease enter correct Strike Price.")
            self.root.destroy()
            return

        a = df[['Change in Open Interest']][df['Strike Price'] == self.sp]
        b1 = a.iloc[:, 0]
        c1 = b1.get(index)
        b2 = df.iloc[:, 1]
        c2 = b2.get((index + 1), 'Change in Open Interest')
        b3 = df.iloc[:, 1]
        c3 = b3.get((index + 2), 'Change in Open Interest')
        if isinstance(c2, str):
            c2 = 0
        if isinstance(c3, str):
            c3 = 0
        self.call_sum = round((c1 + c2 + c3) / 1000, 1)
        if self.call_sum == -0:
            self.call_sum = 0.0
        self.call_boundary = round(c3 / 1000, 1)

        o1 = a.iloc[:, 1]
        p1 = o1.get(index)
        o2 = df.iloc[:, 19]
        p2 = o2.get((index + 1), 'Change in Open Interest')
        p3 = o2.get((index + 2), 'Change in Open Interest')
        self.p4 = o2.get((index + 4), 'Change in Open Interest')
        o3 = df.iloc[:, 1]
        self.p5 = o3.get((index + 4), 'Change in Open Interest')
        self.p6 = o3.get((index - 2), 'Change in Open Interest')
        self.p7 = o2.get((index - 2), 'Change in Open Interest')
        if isinstance(p2, str):
            p2 = 0
        if isinstance(p3, str):
            p3 = 0
        if isinstance(self.p4, str):
            self.p4 = 0
        if isinstance(self.p5, str):
            self.p5 = 0
        self.put_sum = round((p1 + p2 + p3) / 1000, 1)
        self.put_boundary = round(p1 / 1000, 1)
        self.difference = round(self.call_sum - self.put_sum, 1)
        if self.p5 == 0:
            self.call_itm = 0.0
        else:
            self.call_itm = round(self.p4 / self.p5, 1)
            if self.call_itm == -0:
                self.call_itm = 0.0
        if isinstance(self.p6, str):
            self.p6 = 0
        if isinstance(self.p7, str):
            self.p7 = 0
        if self.p7 == 0:
            self.put_itm = 0.0
        else:
            self.put_itm = round(self.p6 / self.p7, 1)
            if self.put_itm == -0:
                self.put_itm = 0.0

        if self.stop:
            return

        self.set_values()

        if self.first_run:
            self.first_run = False
        self.root.after((self.seconds * 1000), self.main)
        return

    @staticmethod
    def create_instance():
        master_window = Tk()
        Nse(master_window)
        master_window.mainloop()
Esempio n. 30
0
class Assist_Serial_Port():
    def __init__(self):
        self.BTL = [110, 300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 38400, 56000, 57600, 115200, 128000, 256000]  # 波特率下拉列表框内容
        self.JYW = ['NONE', 'ODD', 'EVEN', 'MARK', 'SPACE']  # 校验位下拉列表框内容
        self.SJW = [5, 6, 7, 8]  # 数据位下拉列表内容
        self.TZW = [1, 1.5, 2]  # 停止位下拉列表内容
        self.CKXX = self.read_serial_info()
        self.PZMC = ['串口号','波特率','校验位','数据位','停止位']
        self.serial_res_hex_bzw = False  # 接收数据框内容显示hex标志位
        self.serial_sen_hex_bzw = False  # 发送数据框内容显示hex标志位
        self.radiobutton_sen_ascii_click_count = 1  # 设置发送ASCII单选框点击次数为0
        self.radiobutton_sen_hex_click_count = 0  # 设置发送HEX单选框点击次数为0

        self.root = Tk(className='串口调试助手')  # 创建一个主窗体,并命名为‘串口调试助手’
        self.root.protocol('WM_DELETE_WINDOW',self.close_window)  # 实现点击窗口关闭按钮,调用self.close_window方法,关闭已经打开的串口,销毁窗口
        self.root.geometry('630x580')  # 设置窗体大小
        self.root.minsize(width=630, height=435)  # 这两句语言限制窗口不能随意变化
        self.root.maxsize(width=630, height=435)

        self.lf = LabelFrame(self.root, text='串口设置')  # 创建标签容器,并且命名为‘串口设置’
        self.lf.grid(padx=8, pady=10,ipadx=3, ipady=5,row=1,column=1,sticky='n')  # 设置标签容器在窗口中的位置

        self.text_res_con = LabelFrame(master=self.root,text='接收设置')  # 创建标签容器,并命名为接收设置
        self.text_res_con.grid(row=1,column=1,sticky='s')  # 设置标签容器在窗口中的位置

        self.text_sen_con = LabelFrame(master=self.root,text='发送设置')  # 创建标签容器,并命名为接收设置
        self.text_sen_con.grid(padx=8, pady=10,row=2,column=1,sticky='nesw')  # 设置标签容器在窗口中的位置

        self.data_rec = LabelFrame(self.root, text='数据日志')  # 创建标签容器,并且命名为‘数据日志’
        self.data_rec.grid(ipadx=3, ipady=5,row=1, column=2, sticky='e')  # 设置标签容器在窗口中的位置

        self.y_scroll = Scrollbar(self.data_rec)  # 创建接收文本框的Y轴下拉框
        self.y_scroll.pack(side=RIGHT,fill=Y)  # 确定位置

        self.result_text = Text(master=self.data_rec,height=22,width=66,yscrollcommand=self.y_scroll.set) # 创建一个多文本组件,用来显示接收的串口信息,并且配置关联滚轴
        self.result_text.pack(side=RIGHT,fill=Y)  # 设置多文本组件在窗口中的位置
        self.y_scroll.config(command=self.result_text.yview)  # 让文本框和滚轴关联起来

        self.data_sen = LabelFrame(self.root, text='数据发送')  # 创建标签容器,并且命名为‘数据日志’
        self.data_sen.grid(ipadx=3, ipady=5,row=2, column=2, sticky='w')  # 设置标签容器在窗口中的位置

        self.send_text = Text(master=self.data_sen,height=6,width=60)  # 创建一个发送文本框
        self.send_text.grid(row=1,column=1,sticky='n')  # 设置标签容器在窗口中的位置

        self.button_send = Button(self.data_sen,text='发送消息',command=self.button_send_serial_click,width=7)  # 创建一个发送文本框
        self.button_send.grid(row=1,column=2,sticky='NSEW')  # 设置串口打开按钮的位置

    '''关闭串口工具窗口触发的函数'''
    def close_window(self):
        ans = messagebox.askyesno('警告',message='确定关闭窗口?')
        print(ans,'ans')
        if ans:
            try:
                self.thd.stop()  # 停止读取串口线程
                '''确保串口会被关掉,修复关掉串口立马更改波特率,显示错误的问题'''
                while self.ser.isOpen():
                    self.ser.close()  # 将串口实例关闭
            except:
                print('关闭窗口')
            self.root.destroy()
        else:
            return

    '''创建串口配置框架'''
    def serial_config_frame(self):
        for temp in enumerate(self.PZMC):
            '''生成标签组'''
            label_name = Label(self.lf, text=temp[1])  # 创建串口标签
            label_name.grid(padx=5,pady=6,column=1,row=temp[0] + 1)   # 设置标签在标签容器中的位置

            '''生成下拉列表框组'''
            if temp[0] == 0:
                self.combobox0 = Combobox(master=self.lf, values=self.CKXX, width=6, height=3,state='readonly')  # 创建下拉列表框
                self.combobox0.current(0)  # 设置下拉列表当前选中项
                self.combobox0.grid(column=2, row=1, sticky='e')  # 设置下拉列表框在标签容器中的位置
                self.combobox0.bind('<Button-1>',self.update_serial_info)
            elif temp[0] == 1:
                self.combobox1 = Combobox(master=self.lf, values=self.BTL, width=6, height=3,state='readonly')  # 创建下拉列表框
                self.combobox1.current(6)   # 设置下拉列表当前选中项
                self.combobox1.grid(column=2, row=2, sticky='e')  # 设置下拉列表框在标签容器中的位置
            elif temp[0] == 2:
                self.combobox2 = Combobox(master=self.lf, values=self.JYW, width=6, height=3,state='readonly')  # 创建下拉列表框
                self.combobox2.current(0)   # 设置下拉列表当前选中项
                self.combobox2.grid(column=2, row=3, sticky='e')  # 设置下拉列表框在标签容器中的位置
            elif temp[0] == 3:
                self.combobox3 = Combobox(master=self.lf, values=self.SJW, width=6, height=3,state='readonly')  # 创建下拉列表框
                self.combobox3.current(3)   # 设置下拉列表当前选中项
                self.combobox3.grid(column=2, row=4, sticky='e')  # 设置下拉列表框在标签容器中的位置
            else:
                self.combobox4 = Combobox(master=self.lf, values=self.TZW, width=6, height=3,state='readonly')  # 创建下拉列表框
                self.combobox4.current(0)   # 设置下拉列表当前选中项
                self.combobox4.grid(column=2, row=5, sticky='e')  # 设置下拉列表框在标签容器中的位置

        self.button_open_serial = Button(self.lf,text='打开串口',command=self.button_open_serial_click)  # 创建串口打开按钮
        self.button_open_serial.grid(row=6,columnspan=5,sticky='s')  # 设置串口打开按钮的位置

    '''串口单击按钮函数'''
    def button_open_serial_click(self):
        if self.button_open_serial['text'] == '打开串口':
            '''下面的try...except...else操作确定当串口被占用报错后,无法在重新打开串口'''
            try:
                self.open_serial_and_config()  # 打开串口
                self.thd = Thread_myself(target=self.serial_read_content)  # 新建线程对象,并且传入串口对象
                self.thd.start()  # 启动串口助手
            except Exception:
                self.button_open_serial['text'] = '打开串口'
                self.result_text.config(state=NORMAL)
                self.result_text.tag_config('text_error_tag', foreground='red')  # 设置插入文本样式
                self.result_text.insert('end','\r\n无法打开串口,请检查串口连接或者是否被占用...\r\n','text_error_tag')
                self.result_text.config(state=DISABLED)
                self.result_text.see(END)  # 文本框总是显示最新内容
            else:
                self.button_open_serial['text'] = '关闭串口'
                self.combobox0.config(state='disabled')  # 打开之后将所有下拉列表框禁用防止误操作
                self.combobox1.config(state='disabled')
                self.combobox2.config(state='disabled')
                self.combobox3.config(state='disabled')
                self.combobox4.config(state='disabled')
        else:
            self.button_open_serial['text'] = '打开串口'
            self.combobox0.config(state='readonly')
            self.combobox1.config(state='readonly')
            self.combobox2.config(state='readonly')
            self.combobox3.config(state='readonly')
            self.combobox4.config(state='readonly')
            try:
                self.thd.stop()  # 停止读取串口线程
                '''确保串口会被关掉,修复关掉串口立马更改波特率,显示错误的问题'''
                while self.ser.isOpen():
                    self.ser.close()  # 将串口实例关闭
            except:
                print('无聊')

    '''打开串口并配置'''
    def open_serial_and_config(self,timeout=5):
        if self.combobox2.get() == 'NONE':  # 判断校验位方式
            parity = 'N'
        elif self.combobox2.get() == 'ODD':
            parity = 'O'
        elif self.combobox2.get() == 'EVEN':
            parity = 'E'
        elif self.combobox2.get() == 'MARK':
            parity = 'M'
        else:
            parity = 'S'

        if self.combobox3.get() == '5':  # 判断数据然后配数据位
            bytesize = 5
        elif self.combobox3.get() == '6':
            bytesize = 6
        elif self.combobox3.get() == '7':
            bytesize = 7
        else:
            bytesize = 8

        if self.combobox4.get() == '1':  # 判断串口停止位
            stopbits = 1
        elif self.combobox4.get() == '1.5':
            stopbits = 1.5
        else:
            stopbits = 2

        '''创建一个串口实例'''
        self.ser = Serial(port=self.combobox0.get(),baudrate=self.combobox1.get(),parity=parity,bytesize=bytesize,stopbits=stopbits,timeout=timeout)
        self.ser.set_buffer_size(rx_size=4096)  # 设置输入缓存去为4096个字节
        self.ser.flushInput()  # 将输入缓存去清空
        print('波特率为%s' %self.ser.baudrate)

    '''读取设备串口信息,并返回串口列表'''
    def read_serial_info(self):
        serial_info = [temp.__getitem__(0) for temp in list_ports.comports()]
        print(serial_info)
        if serial_info:
            return serial_info
        else:
            serial_info = ['No Port!']
            return serial_info

    '''当下拉框被选中时更新串口列表信息'''
    def update_serial_info(self,*args):
        self.combobox0['values'] = self.read_serial_info()

    '''将发送文本框中的内容发送出去'''
    def button_send_serial_click(self):
        '''if逻辑是判断串口有没有打开,如果打开在发送数据,如果没有打开提示打开串口'''
        if self.button_open_serial['text']  == '打开串口':
            messagebox.showwarning('警告','请先打开串口!')
        else:
            try:
                '''判断发送的内容是HEX还是ASCII,根据方式的不同发送方式也不同'''
                if self.serial_sen_hex_bzw:  # HEX方式发送
                    content = self.send_text.get(1.0, 'end').strip()
                    self.ser.write(bytes.fromhex(content))  # HEX方式发送串口数据
                else:  # ASCII方式发送
                    content = self.send_text.get(1.0, 'end').strip().encode().hex()
                    self.ser.write(bytes.fromhex(content))  # ASCII方式发送串口数据
                if content.encode() == b'':
                    messagebox.showwarning('警告', '发送内容不能为空...')
            except Exception:
                messagebox.showerror('错误','请先打开串口...')

    '''串口接收设置'''
    def text_res_config(self):
        '''创建单选框ASCII并配置单选框'''
        self.radiobutton_res_variable = IntVar()  # 设置单选框variable变量,作用是规定value的数值类型
        self.radiobutton_res_dx_acci = Radiobutton(master=self.text_res_con)
        self.radiobutton_res_dx_acci.config(
            text = 'ASCII',  # 单选框名字
            variable = self.radiobutton_res_variable,  # 设置数值类型
            value = 1,  # 设置value数值,同一组单选框中数值必须不一样
            command = self.res_ascii_set  # 绑定单选框单击之后调用的函数
        )
        '''创建单选框HEX并配置单选框'''
        self.radiobutton_res_dx_hex = Radiobutton(master=self.text_res_con)
        self.radiobutton_res_dx_hex.config(
            text = 'HEX',  # 单选框名字
            variable = self.radiobutton_res_variable,  # 设置数值类型
            value = 2,  # 设置value数值,同一组单选框中数值必须不一样
            command = self.res_hex_set   # 绑定单选框单击之后调用的函数
        )
        self.radiobutton_res_variable.set(1)  # 设置那个单选框初始的时候为选中状态
        self.radiobutton_res_dx_acci.grid(padx=5,row=1, column=1, sticky='w')  # 封装ASCII单选框
        self.radiobutton_res_dx_hex.grid(padx=5,row=1,column=2,sticky='e')  # 封装HEX单选框
        self.button_clear_res = Button(master=self.text_res_con,text='清空接收',command=lambda:self.clear_text(self.result_text))  # 添加清空接手区按键
        self.button_clear_res.grid(row=2,sticky='s',columnspan=5,pady=7)  # 将清空按键打包

    '''串口发送设置'''
    def text_sen_config(self):
        '''创建单选框ASCII并配置单选框'''
        self.radiobutton_sen_variable = IntVar()  # 设置单选框variable变量,作用是规定value的数值类型
        self.button_sen_dx_acci = Radiobutton(master=self.text_sen_con)
        self.button_sen_dx_acci.config(
            text = 'ASCII',  # 单选框名字
            variable = self.radiobutton_sen_variable,  # 设置数值类型
            value = 1,  # 设置value数值,同一组单选框中数值必须不一样
            command = self.sen_ascii_set  # 绑定单选框单击之后调用的函数
        )
        '''创建单选框HEX并配置单选框'''
        self.button_sen_dx_hex = Radiobutton(master=self.text_sen_con)
        self.button_sen_dx_hex.config(
            text = 'HEX',  # 单选框名字
            variable = self.radiobutton_sen_variable,  # 设置数值类型
            value = 2,  # 设置value数值,同一组单选框中数值必须不一样
            command = self.sen_hex_set   # 绑定单选框单击之后调用的函数
        )
        self.radiobutton_sen_variable.set(1)  # 设置那个单选框初始的时候为选中状态
        self.button_sen_dx_acci.grid(padx=5,row=1, column=1, sticky='w')  # 封装ASCII单选框
        self.button_sen_dx_hex.grid(padx=5,row=1,column=2,sticky='e')  # 封装HEX单选框
        self.button_sen_clear_res = Button(master=self.text_sen_con,text='清空发送',command=lambda:self.clear_text(self.send_text))  # 添加清空接手区按键
        self.button_sen_clear_res.grid(row=2,sticky='s',columnspan=5,pady=7)  # 将清空按键打包

    '''清空文本空间内容'''
    def clear_text(self,object):
        print('清除')
        object.config(state=NORMAL)  # 设置text对象可以操作
        object.delete(1.0,'end')  # 清空text对象内容
        # object.config(state=DISABLED)  # 设置text对象不可用

    '''设置接收框ASCII转换标志位'''
    def res_ascii_set(self):
        self.serial_res_hex_bzw = False

    '''设置接收框HEX转换标志位'''
    def res_hex_set(self):
        self.serial_res_hex_bzw = True

    '''将发送文本框中的内容以ASCII方式显示'''
    def sen_ascii_set(self):
        self.radiobutton_sen_hex_click_count = 0  # 清零
        self.radiobutton_sen_ascii_click_count += 1  # 单击一次次数+1
        self.serial_sen_hex_bzw = False  # 设置HEX标志位为False
        if not self.serial_sen_hex_bzw and self.radiobutton_sen_ascii_click_count == 1:
            self.send_text.unbind('<Key>')
            self.send_text.unbind('<BackSpace>')
            self.send_text.unbind('<Control--V>')
            self.send_text.unbind('<Control--v>')
            self.send_text.unbind('<Control--C>')
            self.send_text.unbind('<Control--c>')
            self.send_text.config(state=NORMAL)
            send_content = self.send_text.get(1.0,'end').strip()  # 读取输入文本框中的内容
            send_content = ''.join(send_content.split())  # 将16进制的文本去掉空格
            '''实现输入的数据个数不是偶数时,对不成对的数据用0进行补位'''
            if len(send_content) % 2 == 0:
                send_content = [send_content[x * 2:x * 2 + 2] for x in range(len(send_content)//2)]  # 将内容分成2个字符的数组,如:['01','02']
            else:
                temp = send_content
                send_content = [send_content[x * 2:x * 2 + 2] for x in range(len(send_content) // 2)]
                send_content.append(temp[-1].zfill(2))  # 在最后一位前面补0
                send_content = ''.join(send_content)
                send_content = [send_content[x * 2:x * 2 + 2] for x in range(len(send_content) // 2)]  # 将内容分成2个字符的数组,如:['01','02']
                print(send_content, 'send_content')
            send_content = ''.join([chr(int(x,16)) for x in send_content])  # 将上面的数组中的每个元素转换成ASCII格式
            self.clear_text(self.send_text)  # 清空输入文本框内容
            self.send_text.insert('end',send_content.encode())  # 将转换好的内容插入到文本框中

    '''将发送文本框中的内容以HEX方式显示'''
    def sen_hex_set(self):
        self.radiobutton_sen_ascii_click_count = 0  # 清零
        self.radiobutton_sen_hex_click_count += 1  # 单击一次次数+1
        self.serial_sen_hex_bzw = True  # 设置HEX标志位为True
        if self.serial_sen_hex_bzw and self.radiobutton_sen_hex_click_count == 1:
            self.send_text.bind('<Key>',self.key_callback)
            self.send_text.bind('<BackSpace>',self.key_backspace_control_v_callback)
            self.send_text.bind('<Control--V>',self.key_backspace_control_v_callback)
            self.send_text.bind('<Control--v>', self.key_backspace_control_v_callback)
            self.send_text.bind('<Control--C>',self.key_backspace_control_v_callback)
            self.send_text.bind('<Control--c>', self.key_backspace_control_v_callback)
            send_content = self.send_text.get(1.0, 'end').strip()  # 读取输入文本框中的内容
            # send_content = ''.join(send_content.split())  # 将16进制的文本去掉空格
            send_content = send_content.encode().hex()  # 将输入框中的内容转换成16进制

            send_content = ''.join([send_content[x * 2:x * 2 + 2] for x in range(len(send_content) // 2)])  # 转换成16进制的数据进行格式化
            print(send_content, '+++++++++++++++')
            self.clear_text(self.send_text)  # 清空原来的输入框内容
            self.send_text.insert('end', send_content.encode().upper())  # 将转换好的内容插入到文本框中

    '''backspace、control-v、control-c键盘事件回调函数'''
    def key_backspace_control_v_callback(self,event):
        self.send_text.config(state=NORMAL)

    '''发送框绑定键盘事件回调函数'''
    def key_callback(self,event):
        if event.char not in 'abcdefABCDEF0123456789 ':
            self.send_text.config(state=DISABLED)
        else:
            self.send_text.config(state=NORMAL)

    '''类方法:读取串口内容'''
    def serial_read_content(self):
        try:
            '''判断显示方式,self.serial_hex_bzw = True时为16进制显示,self.serial_hex_bzw=False时为ascii显示'''
            if self.serial_res_hex_bzw:
                time_str = time.strftime('[%Y-%m-%d %H:%M:%S]') + '-->HEX\r\n'
                data_res_sum = self.ser.inWaiting()  # 读取输入缓存中有多少个字节数据
                if data_res_sum:
                    text_content = self.ser.read(data_res_sum).hex()  # 将缓存中的数据读取出来
                    text_content = ' '.join([text_content[x*2:x*2+2] for x in range(len(text_content)//2)]).upper()  # 转换成16进制的数据进行格式化,带空格
                    print(text_content,'转换格式之后的文本')
            else:
                time_str = time.strftime('[%Y-%m-%d %H:%M:%S]') + '-->ASCII\r\n'
                data_res_sum = self.ser.inWaiting()  # 读取输入缓存中有多少个字节数据
                if data_res_sum:
                    text_content = self.ser.read(data_res_sum).decode(encoding='utf-8',
                                                                           errors='replace')  # 将缓存中的数据读取出来
                    print('---------------------{}'.format(data_res_sum), text_content)
            time.sleep(0.5)
            if text_content:
                # print('sssssss')
                self.result_text.config(state=NORMAL)  # 打开文本框输入
                self.result_text.tag_config('text_head_tag', foreground='blue')  # 设置插入文本样式
                self.result_text.tag_config('text_tag',foreground='green')  # 设置插入文本样式
                self.result_text.insert('end','\r\n' + time_str + '\r\n','text_head_tag')  # 在文本框中插入数据
                self.result_text.insert('end',text_content + '\r\n','text_tag')  # 在文本框中插入数据
                self.result_text.config(state=DISABLED)  # 禁止文本框输入
                self.result_text.see(END)  # 文本框总是显示最新内容
                text_content = ''
        except Exception:
            print('F**k you!')

    '''运行软件'''
    def run(self):
        self.serial_config_frame()
        self.text_res_config()
        self.text_sen_config()
        self.root.mainloop()
Esempio n. 31
0
class Interface:

    window = Tk()
    window.config(padx=50, pady=50, bg=BACKGROUND)
    window.minsize(width=1400, height=500)
    window.title("Face Mask Detection Software")

    from_email_ent = Entry(width=20, bd=0, highlightcolor=BLUE)
    from_password_ent = Entry(width=20, show='*', bd=0, highlightcolor=BLUE)
    to_email_ent = Entry(width=20, bd=0, highlightcolor=BLUE)
    smtp_label = StringVar()

    progress_bar = Progressbar(window,
                               orient=HORIZONTAL,
                               length=100,
                               mode='determinate')
    info_text = Label(text="",
                      font=FONT_SMALL,
                      padx=20,
                      pady=20,
                      bg=BACKGROUND,
                      fg=DEEP_ORANGE)
    canvas = Canvas(width=300, height=300, bg=GREY_LIGHT, highlightthickness=0)
    timer_label = Label(text="",
                        font=FONT_SMALL,
                        padx=5,
                        pady=5,
                        bg=BACKGROUND,
                        fg=DEEP_ORANGE)

    canvas_image = PhotoImage(file='offenders/last_capture.png')
    auto_send_is_on = IntVar()
    count = 5

    def __init__(self):
        # Text
        self.selected_image = 'last_capture.png'
        title = Label(text="Face Mask Detection Software",
                      font=FONT_LARGE,
                      padx=10,
                      pady=10,
                      fg=GREY,
                      bg=BACKGROUND)
        please_choose_text = Label(text="Please Choose Detection Mode",
                                   font=FONT_MEDIUM,
                                   padx=5,
                                   pady=5,
                                   bg=BACKGROUND,
                                   fg=BLACK)
        email_setup_text = Label(text="Email Setup",
                                 font=FONT_MEDIUM,
                                 padx=5,
                                 pady=5,
                                 bg=BACKGROUND,
                                 fg=BLACK)
        from_email_text = Label(text="Sender Email: ",
                                font=FONT_SMALL,
                                padx=5,
                                pady=5,
                                bg=BACKGROUND,
                                fg=BLACK)
        camera_source_text = Label(text="Camera Source: ",
                                   font=FONT_SMALL,
                                   padx=5,
                                   pady=5,
                                   bg=BACKGROUND,
                                   fg=BLACK)
        space = Label(text="                           ",
                      font=FONT_SMALL,
                      padx=5,
                      pady=5,
                      bg=BACKGROUND,
                      fg=BLACK)
        password_text = Label(text="Password: "******"Please Upload or Provide File Directory",
            font=FONT_SMALL,
            padx=10,
            pady=10,
            fg=BLACK,
            bg=BACKGROUND)
        to_email_text = Label(text="Receiver Email: ",
                              font=FONT_SMALL,
                              padx=5,
                              pady=5,
                              bg=BACKGROUND,
                              fg=BLACK)
        target_detection_text = Label(text="Last Detection",
                                      font=FONT_MEDIUM,
                                      padx=5,
                                      pady=5,
                                      bg=BACKGROUND,
                                      fg=RED)
        smtp_server_text = Label(text="SMTP Server: ",
                                 font=FONT_SMALL,
                                 padx=5,
                                 pady=5,
                                 bg=BACKGROUND,
                                 fg=BLACK)

        #
        auto_send = Checkbutton(Interface.window,
                                text="automatically send email",
                                variable=Interface.auto_send_is_on,
                                onvalue=1,
                                offvalue=0,
                                bg=BACKGROUND)

        # Buttons
        send_bttn_image = PhotoImage(file='buttons/send.png')
        send_bttn = Button(
            image=send_bttn_image,
            highlightthickness=0,
            command=lambda: Notification.notify(image=self.selected_image),
            font=FONT_MEDIUM,
            bg=BACKGROUND,
            relief='raised',
            bd=0)

        # Radio Buttons
        self.radio_state = IntVar()
        webcam_radio_bttn = Radiobutton(text="Camera",
                                        value=0,
                                        variable=self.radio_state,
                                        command=self.radio_chosen,
                                        anchor='c',
                                        bg=BACKGROUND,
                                        fg=BLACK)
        image_radio_bttn = Radiobutton(text="Image",
                                       value=1,
                                       variable=self.radio_state,
                                       command=self.radio_chosen,
                                       anchor='c',
                                       bg=BACKGROUND,
                                       fg=BLACK)
        video_radio_bttn = Radiobutton(text="Video  ",
                                       value=2,
                                       variable=self.radio_state,
                                       command=self.radio_chosen,
                                       anchor='c',
                                       bg=BACKGROUND,
                                       fg=BLACK)

        # Entries, Buttons and Separator
        self.file_directory_ent = Entry(width=50, bd=0, highlightcolor=BLUE)
        upload_bttn_image = PhotoImage(file='buttons/upload.png')
        upload_bttn = Button(highlightthickness=0,
                             command=self.upload_file,
                             image=upload_bttn_image,
                             bg=BACKGROUND)
        sep = ttk.Separator(Interface.window, orient='vertical')
        start_bttn_image = PhotoImage(file='buttons/power.png')
        start_bttn = Button(image=start_bttn_image,
                            highlightthickness=0,
                            command=self.start,
                            font=FONT_MEDIUM,
                            bg=BACKGROUND,
                            relief='groove',
                            bd=0)

        # ComboBox
        smtp_combo = Combobox(Interface.window,
                              width=19,
                              textvariable=Interface.smtp_label)
        smtp_combo['values'] = ('Google:smtp.gmail.com',
                                'Outlook:smtp.live.com',
                                'Office365:smtp.office365.com',
                                'Yahoo:smtp.mail.yahoo.com',
                                'YahooPlus:plus.smtp.mail.yahoo.com',
                                'YahooUK:smtp.mail.yahoo.co.uk',
                                'Hotmail:smtp.live.com',
                                'AT&T:smtp.att.yahoo.com',
                                'O2UK:smtp.o2.co.uk')
        camera_src_label = StringVar()
        self.camera_combo = Combobox(Interface.window,
                                     width=5,
                                     textvariable=camera_src_label)
        self.camera_combo['values'] = ('0', '1', '2', '3')
        self.camera_combo.current(1)
        smtp_combo.current(0)
        browse_detections_bttn = Button(text="Browse Detections",
                                        command=self.browse_images,
                                        bg=BACKGROUND,
                                        highlightthickness=0)

        # Grid Setup
        title.grid(row=1, column=0, sticky='w', columnspan=3)
        please_choose_text.grid(row=2, column=0, sticky='w')
        self.file_directory_ent.grid(row=7, column=0, columnspan=2, sticky='w')
        please_upload_text.grid(row=6, column=0, sticky='w')
        upload_bttn.grid(row=7, column=2)
        sep.grid(row=0, column=7, rowspan=9, sticky='ns', padx=20)
        smtp_server_text.grid(row=5, column=5)
        webcam_radio_bttn.grid(row=3, column=0, sticky='w')
        image_radio_bttn.grid(row=5, column=0, sticky='w')
        video_radio_bttn.grid(row=5, column=1, sticky='w')
        email_setup_text.grid(row=2, column=5)
        camera_source_text.grid(row=3, column=1, sticky='w')
        space.grid(row=3, column=3)
        self.from_email_ent.grid(row=3, column=6)
        password_text.grid(row=4, column=5)
        from_email_text.grid(row=3, column=5)
        smtp_combo.grid(row=5, column=6)
        self.to_email_ent.grid(row=6, column=6)
        self.camera_combo.grid(row=3, column=2)
        to_email_text.grid(row=6, column=5)
        target_detection_text.grid(row=0, column=8, columnspan=2)
        start_bttn.grid(row=8, column=6, columnspan=2, padx=30, pady=30)

        Interface.info_text.grid(row=8, column=0, columnspan=3)
        Interface.from_password_ent.grid(row=4, column=6)
        browse_detections_bttn.grid(row=2, column=8, columnspan=2)
        auto_send.grid(row=3, column=8, columnspan=2)
        Interface.timer_label.grid(row=4, column=8, columnspan=2)
        send_bttn.grid(row=5, column=8, columnspan=2)
        Interface.canvas.grid(row=1, column=8, columnspan=2)
        Interface.progress_bar.grid(row=9, column=6, columnspan=2)

        Interface.window.mainloop()

    def radio_chosen(self):
        if self.radio_state.get() == 0:
            self.file_directory_ent.config(state='disabled')
            self.camera_combo.config(state='normal')
            self.camera_combo.focus()
        else:
            self.file_directory_ent.config(state='normal')
            self.file_directory_ent.focus()
            self.camera_combo.config(state='disabled')

    def upload_file(self):
        directory = filedialog.askopenfilename(
            title='Select a file to use for detections')
        self.file_directory_ent.focus()
        self.file_directory_ent.insert(0, directory)

    def browse_images(self):
        chosen_image_to_send = filedialog.askopenfilename(
            initialdir='/Face-Mask-Detection/offenders/last_capture.png',
            title='Images of Detections')
        if not chosen_image_to_send == '':
            p = chosen_image_to_send.split('/')
            self.selected_image = p[len(p) - 1]
            Interface.canvas_image = PhotoImage(
                file=f'offenders/{self.selected_image}')
            Interface.canvas.create_image(150,
                                          150,
                                          image=Interface.canvas_image)

    @staticmethod
    def timer_start():
        # Interface.count = 5
        Interface.window.after(1000, Interface.timer_start)
        Interface.update_timer_text(f'Sending email in  {Interface.count}s')
        Interface.count -= 1
        if Interface.count < 0:
            Interface.count = 5
            return True

    @staticmethod
    def update_progress_bar(value: int):
        """
        Updates the progress bar level visible on the interface
        :param value: Sets the value of the progress bar (int 0 - 100)
        """
        Interface.progress_bar['value'] = value
        Interface.window.update_idletasks()

    @staticmethod
    def update_info_text(text: str):
        """
        Updates the Info text visible on the interface to a specified string text
        :param text: Sets the text value of info text
        """
        Interface.info_text.config(text=text)
        Interface.window.update_idletasks()
        Interface.window.update()

    @staticmethod
    def update_timer_text(text: str):
        """
        Updates the timer text visible on the interface to a specified string text
        :param text: Sets the text value of info text
        """
        Interface.timer_label.config(text=text)
        Interface.window.update_idletasks()
        Interface.window.update()

    def start(self):
        """
        Starts detection base on user's choice. Triggered only when start button is clicked
        """
        from video_mask_detection import VideoMaskDetection
        Interface.update_progress_bar(10)
        if self.radio_state.get() == 0:
            video = VideoMaskDetection()
            video.start_video_stream(
                stream_source=int(self.camera_combo.get()))
        elif self.radio_state.get() == 1:
            from image_mask_detector import ImageMaskDetection
            image = ImageMaskDetection(
                image_path=self.file_directory_ent.get())
            image.start_mask_detections()
        elif self.radio_state.get() == 2:
            video = VideoMaskDetection()
            video.start_video_capture(path=self.file_directory_ent.get())
class TicketSales:
    #   CREATE A VARIABLE THAT'S GONNA CONTAIN THE result_string
    result_string = StringVar()

    def __init__(self, window):
        #   CREATE ALL THE NECESSARY WIDGETS
        self.cell_label = Label(window, text="Enter cellphone number")
        self.cell_label.place(x=10, y=10)
        self.cell_entry = Entry(window)
        self.cell_entry.place(x=200, y=10)

        self.ticket_category = Label(window, text="Select ticket category")
        self.ticket_category.place(x=10, y=50)
        self.category_combobox = Combobox(window,
                                          value=["Soccer", "Movie", "Theatre"],
                                          state="readonly")
        self.category_combobox.place(x=200, y=50)

        self.ticket_amount_label = Label(window,
                                         text="Number of tickets bought")
        self.ticket_amount_label.place(x=10, y=100)
        self.ticket_amount_entry = Entry(window)
        self.ticket_amount_entry.place(x=200, y=100)

        self.calculate_btn = Button(window,
                                    text="Calculate Ticket",
                                    command=self.calculate_pre_payment).place(
                                        x=10, y=150)
        self.clear_btn = Button(window,
                                text="Clear entries",
                                command=self.clear_entries).place(x=200, y=150)

        self.result_label = Label(window,
                                  text="",
                                  textvariable=self.result_string).place(x=10,
                                                                         y=200)

    #   FUNCTION WILL CALCULATE THE PAYABLE AMOUNT BY THE USER
    def calculate_pre_payment(self):
        from tkinter import messagebox

        #   GET THE VALUES FROM THE ENTRIES
        cell_number = self.cell_entry.get()
        ticket_amount = self.ticket_amount_entry.get()
        ticket_category = self.category_combobox.get()

        #   HERE, WE WILL DECIDE HOW MUCH THE ticket_price WILL BE BASED ON THE CHOSEN CATEGORY
        if ticket_category.lower() == "soccer":
            ticket_price = 40.00
        elif ticket_category.lower() == "movie":
            ticket_price = 75.00
        else:
            ticket_price = 100.00

        #   HERE, WE CALCULATE THE amount_payable BEFORE VAT
        amount_payable = float(ticket_amount) * ticket_price
        #   NOW, WE CALCULATE THE VALUE OF THE VAT
        vat = amount_payable * 0.15
        #   NOW, WE ADD THE TWO TOGETHER
        amount_payable = amount_payable + vat

        #   SHOW THE USER THE DETAILS OF THE TRANSACTION
        self.result_string.set("*************************************" + "\n" +
                               "Amount Payable: R" + str(amount_payable) +
                               "\n" + "Reservation for: " +
                               str(ticket_category) + " for: " +
                               str(ticket_amount) + " people" + "\n" +
                               "was done by: " + str(cell_number) + "\n" +
                               "*************************************")

    #   FUNCTION CLEARS ALL THE ENTRIES CONTENTS
    def clear_entries(self):
        #   CHANGE THE STATE OF THE category_combobox TO normal, SO WE CAN DELETE THE CONTENTS
        self.category_combobox.config(state="normal")
        self.cell_entry.delete(0, END)
        self.ticket_amount_entry.delete(0, END)
        self.category_combobox.delete(0, END)
        #   SET THE STATE BACK TO readonly
        self.category_combobox.config(state="readonly")