Example #1
0
class ClaimPage(Frame):
    def __init__(self, parent, controller):
        Frame.__init__(self, parent)
        self.grid_rowconfigure((0, 1, 2, 3), weight=1)
        self.grid_columnconfigure((0, 1, 2, 3), weight=1)

        self.controller = controller
        self.columns = 3
        self.raw_data = []
        label = Label(self, text="Claim annotator", font=LARGE_FONT)
        label.grid(row=0, column=0, pady=10, columnspan=self.columns)

        self.data_button = Button(self, text="Load data", command=lambda: self.load_data())
        self.data_button.grid(row=1, column=0, columnspan=self.columns)

    def load_data(self):
        w = 600
        h = 600
        self.controller.geometry('{}x{}'.format(w, h))
        self.raw_data = data_loader.load_annotation_data('claim')
        self.data_button.destroy()
        label = Label(self, text="Data loaded successfully")
        label.grid(row=1, column=0, columnspan=self.columns, pady=10, padx=10)

        # Set up annotation
        print(self.raw_data)
Example #2
0
class StartUI:
    def __init__(self, master):
        self.master = master
        master.title("Sudoku")

        self.frame = Frame(master)
        self.frame.pack(side=TOP)
        self.label = Label(
            self.frame,
            text="\"If you are curious, you'll find the puzzles around"
            " you. \nIf you are determined, you will solve them.\"")
        self.label.pack(side=TOP)

        self.start_button = Button(master,
                                   text="Start",
                                   fg='purple',
                                   command=self.start_game)
        self.start_button.pack(side=BOTTOM)

    def start_game(self):
        try:
            self.canvas.destroy()
            self.clock.destroy()
        except:
            pass

        GameUI(self.master)
        self.start_button.destroy()
Example #3
0
def clear_items(label1: Label, label2: Label, rb_lst: list,
                forget_button: Button) -> None:
    """Hopefully deletes it when I click clear."""
    label1.destroy()
    label2.destroy()
    for rb in rb_lst:
        rb.destroy()
    forget_button.destroy()
class BaseUi:
    def __init__(self, caller, window):
        self.caller = caller
        self.window = window

    def setUp(self, nameOfImage, targetFunc, preloopFunc=None):
        cv_img = rh.get_image(nameOfImage)

        self.height, self.width, ne_channels = cv_img.shape

        self.canvas = Canvas(self.window, width=self.width, height=self.height)
        self.canvas.bind("<Button 1>", targetFunc)

        self.canvas.pack()

        photo = PIL.ImageTk.PhotoImage(image=PIL.Image.fromarray(cv_img))
        self.canvas.create_image(0, 0, image=photo, anchor=NW)

        buttonText = "Back"
        if self.typeName == "AgentList":
            buttonText = "Exit"
        self.B = Button(
            self.window,
            text=buttonText,
            command=lambda:
            [self.B.destroy(),
             self.canvas.pack_forget(),
             self.caller.setUp()])
        self.B.pack()

        if (preloopFunc):
            preloopFunc()

        self.window.mainloop()
Example #5
0
class button(Button):
    def __init__(self, parent=None, func=None, values={}, position={}):
        self.buttonObject = Button(parent)
        self.state = dict()
        self.state["visible"] = True
        self.state["rendered"] = False
        self.values = values
        self.position = position
        self.func = func
        self.createWidgets()
        self.render()

    def createWidgets(self):
        for val in self.values:
            self.buttonObject[val] = self.values[val]
        self.buttonObject["command"] = self.func

    def set_state(self, state):
        self.state = state

    def get_state(self):
        return self.state

    def render(self):
        self.state["rendered"] = True
        self.state["visible"] = True
        if "column" in self.position:
            print(self.position["column"])
            self.buttonObject.grid(column=self.position["column"])
        if "row" in self.position:
            self.buttonObject.grid(row=self.position["row"])
        if "sticky" in self.position:
            self.buttonObject.grid(sticky=self.position["sticky"])
        if "padx" in self.position:
            self.buttonObject.grid(padx=self.position["padx"])
        if "pady" in self.position:
            self.buttonObject.grid(pady=self.position["pady"])
        if "columnspan" in self.position:
            self.buttonObject.grid(columnspan=self.position["columnspan"])
        if "rowspan" in self.position:
            self.buttonObject.grid(rowspan=self.position["rowspan"])
        self.buttonObject.grid()

    def destroy(self):
        self.buttonObject.destroy()
def pause(event):
    # If <p> is pressed the game is paused then unpauses game if presssed again
    # Button enables user to save and quit game.
    global pausecount, paused, countdown3, countdown2, countdown1, saveAndQuit
    pausecount += 1
    print(pausecount)
    if pausecount % 2 == 1:
        paused = "true"
        print(paused)
        saveAndQuit = Button(
            window,
            image=saveandquitgameimg,
            command=lambda: [saveGame(), sys.exit()])
        saveAndQuit.place(x=250, y=900)
    else:
        time.sleep(1)
        saveAndQuit.destroy()
        paused = "false"
Example #7
0
class Menu:
    def __init__(self, master):
        self.master = master
        master.title("TicTacToe")
        self.label_index = 0
        self.label_text = StringVar()
        self.label_text.set('TicTacToe')
        self.lable = Label(master, textvariable=self.label_text)
        self.lable.pack()
        self.start_button = Button(master, text='Start', command=self.start)
        self.start_button.pack()

    def start(self):
        self.lable.destroy()
        self.start_button.destroy()
        self.play()

    def play(self):
        Play(self.master)
Example #8
0
class Menu:
    def __init__(self, master):
        self.master = master
        master.title("TicTacToe")
        self.label_index = 0
        self.label_text = StringVar()
        self.label_text.set('TicTacToe')
        self.lable = Label(master, textvariable=self.label_text)
        self.lable.pack()
        self.start_button = Button(master, text='Start', command=self.start)
        self.start_button.pack()

    def start(self):
        self.lable.destroy()
        self.start_button.destroy()
        self.play()

    def play(self):
        Play(self.master)
Example #9
0
 def updateButtons(self, indexes, whatToDo, pid):
     firstIndex = indexes[0]
     scale = self.MAXWIDTH / 100
     if whatToDo:
         # Have to add a button
         b = Button()
         # Test Button
         # Things you will need
         bWidth = scale * len(indexes)
         bStartX = self.STARTX + (firstIndex * scale)
         b = Button(self.gui, image=self.photo,bg='red')
         b['width']=bWidth
         b['height']=self.HEIGHT
         b.place(x=bStartX,y=self.Y)
         self.gui.update()
         self.memoryButtons[pid]=b
     else:
         b = self.memoryButtons.get(pid)
         del self.memoryButtons[pid]
         b.destroy()
         self.gui.update()
Example #10
0
class Option(Toplevel):
    def __init__(self, arr):
        Toplevel.__init__(self)
        self.title('屏蔽关键词')
        self.arr = arr
        self.copy_arr = list(self.arr.items())
        self.geometry('200x450+500+200')
        self.show_options()
        self.wm_attributes('-topmost', 1)

    def show_options(self):
        row = Frame(self)
        row.pack(fill="x")
        label = Label(row, text='点击下列需要屏蔽的关键词', width=40)
        label.pack()
        for i in range(10):
            key, value = self.copy_arr.pop(0)
            btn = Button(row, text=key + ': ' + str(value), width=20)
            btn['command'] = lambda row=row, binst=btn: self.func(row, binst)
            btn.pack()
        self.finbtn = Button(row, text='完成', width=8, command=self.quit_window)
        self.finbtn.pack()

    def func(self, row, btn):
        self.arr.pop(btn['text'].split(':')[0])
        self.finbtn.destroy()
        btn.destroy()
        if self.copy_arr:
            key, value = self.copy_arr.pop(0)
            btn1 = Button(row, text=key + ': ' + str(value), width=20)
            btn1['command'] = lambda binst=btn1: self.func(row, binst)
            btn1.pack()
            self.finbtn = Button(row,
                                 text='完成',
                                 width=8,
                                 command=self.quit_window)
            self.finbtn.pack()

    def quit_window(self):
        self.destroy()
Example #11
0
class StancePage(Frame):
    def __init__(self, parent, controller):
        self.raw_data = []
        Frame.__init__(self, parent)
        title = Label(self, text="Stance annotator", font=LARGE_FONT)
        title.place(x=self.winfo_width()/2, y=25, anchor='center')

        self.data_button = Button(self, text="Load data", command=lambda: self.load_data())
        self.data_button.grid(pady=10, padx=10)

    def load_data(self):
        self.raw_data = data_loader.load_annotation_data('stance')
        self.data_button.destroy()

        label = Label(self, text="Data loaded successfully")
        label.grid(pady=10, padx=10)
        print(len(self.raw_data))
        for i in range(len(self.raw_data)):

            for j in range(len(self.raw_data[0])):
                datapoint = Entry(self, text=self.raw_data[i][j]['full_text'])
                datapoint.grid()
        # Set up annotation
        print(self.raw_data)
Example #12
0
class game(object):
    def __init__(self):
        self.root = Tk()
        self.root["width"]=logix.WIDTH*(CARDW+PAD)+3*PAD
        self.root["height"]=logix.HEIGHT*(CARDH+PAD)+3*PAD + 50
        self.root.title("Unocolour")
        self.mainscreen()
        self.root.mainloop()
        
    def mainscreen(self):
        self.gamename = tkinter.Label(self.root, text = "UNOCOLOUR", font = ("Ariel", 24))
        self.gamename.place(x=(logix.WIDTH*(CARDW+PAD)+3*PAD-400)//2, y=10, width = 400, height = 25)
        self.startbutton = Button(text = "Start", command=self.startgame)
        self.startbutton.place(x=(logix.WIDTH*(CARDW+PAD)+3*PAD-100)//2, y=60, width = 100, height = 25)

    def startgame(self):
        self.cardcounter = tkinter.Label(text = "Cards: 108")
        self.cardcounter.place(x=10, y=25)
        self.lvltitle = tkinter.Label(text = "Level I")
        self.lvltitle.place(x=10, y=10)
        self.b=board(self.root, self)
        self.b.place(x=10,y=50)
        self.startbutton.destroy()
        del self.startbutton
        
    def endgame(self):
        self.b.destroy()
        self.cardcounter.destroy()
        self.lvltitle.destroy()
        del self.b, self.cardcounter, self.lvltitle
        self.mainscreen()

    def update_counter(self, n):
        self.cardcounter["text"] = "Cards: {}".format(n)
    def update_level(self, n):
        self.lvltitle["text"] = "Level {}".format(romanik(n))
Example #13
0
class GameWindow(object):
    """Define the game window and its functionality."""


    def __init__(self):
        """Initialize a new instance of the GameWindow."""
        self.new_game()


    def click_button(self, row_index, button_index):
        """Register the user's button-click by changing this button's color."""
        current_value = self.button_rows[row_index][button_index]
        if current_value is None:
            current_value = 0
        else:
            current_value += 1
        # Set the new color. If we've run through the colors, loop back around.
        self.button_rows[row_index][button_index] = (
            current_value if current_value < 6 else 0
        )
        # Get the textual color value of the button.
        button_color = colors[self.button_rows[row_index][button_index]]
        # Set the button's color and assign it to the self.BUTTON_GUESSES dict.

        # store what row player is on for points purposes if wins
        self.attempt = row_index
        #add 1 as row_index ordered from 0-5 not 1-6
        self.attempt += 1

        self.BUTTON_GUESSES[row_index][button_index] = Button(
            self.BUTTON_FRAMES[row_index],
            bg=button_color,
            text=" ",
            command=partial(self.click_button, row_index, button_index),
        )
        self.BUTTON_GUESSES[row_index][button_index].grid(
            row=(7 + row_index), column=button_index, pady=4, padx=4
        )



    def compare_guess_solution(self, user_guess):
        """Check the player's guess."""
        # Check to see if their guess was correct.
        if not self.game.correct_solution(user_guess):
            # Their guess was incorrect.
            return False

        # Their solution was correct.
        # Reveal the secret code.
        self.SOLUTION_BUTTON.destroy()
        self.display_solution()
        self.ROOT.update()

        PlayerStats.played += 1
        PlayerStats.wins += 1
        self.calc_points_won()
        self.calc_win_rate()
        self.save_stats()

        # Let them know they've won.
        showinfo(
            "Bletchley",
            "You genius, "
            "you cracked the code.\n\n    Alan would be proud of you!"
            "\n\nYou earned "+str(self.points)+" points for that win.",
        )

        self.new_game()

    def decode_row(self, row_index):
        """Check result of the decode button press for row 1."""
        # Ensure that all four colors have been guessed.
        if self.button_rows[row_index].count(None):
            return None

        # Disable decode button, so no cheating.
        self.DECODE_BUTTONS[row_index].configure(state=DISABLED)

        # Build user_guess string.
        this_row = self.button_rows[row_index]
        user_guess = [colors[item] for item in this_row]

        # Construct the outcome string for output to the yesllow label.
        peg_string = self.game.generate_peg_string(user_guess)

        # display outcome in gui on yellow label
        self.BUTTON_FRAME_LABELS[row_index] = Label(
            self.BUTTON_FRAMES[row_index], bg="yellow", text=peg_string
        )
        self.BUTTON_FRAME_LABELS[row_index].grid(
            row=(7 + row_index), column=4, pady=4, padx=4, sticky=W
        )

        # Disable the buttons in this row.
        for button_index in range(4):
            self.BUTTON_GUESSES[row_index][button_index].configure(
                state=DISABLED
            )

        # Enable the next row's DECODE_BUTTON if it isn't in the last row.
        if row_index != 5:
            self.DECODE_BUTTONS[row_index + 1].configure(state=NORMAL)

        # Check to see if their solution was correct.
        correct = self.compare_guess_solution(user_guess)
        # Check to see if the game is over.
        if row_index == 5 and not correct:
            # If this is the last guess and they're wrong, reveal the solution
            # and tell the user they've lost.
            self.reveal_solution()

    def display_solution(self):
        """Reveal the solution to the player."""
        secret_buttons = list()
        # Generate the four buttons that display the secret code.
        for index, bg in enumerate(self.game.secret_code):
            # Create a button.
            secret_button = Button(self.SOLUTION_FRAME, bg=bg)
            # Assign its position.
            secret_button.grid(row=0, column=(4 + index), pady=4, padx=4)
            # Add it to the secret_buttons list.
            secret_buttons.append(secret_button)

    def new_game(self):
        """Reset the GameWindow and start a new game, and build gui"""
        # Attempt to destroy the ROOT window if it exists.
        try:
            self.ROOT.destroy()
        except Exception as e:
            pass

        # Initialize a new Bletchley Game.
        self.game = BletchleyGame()

        # Initialize the Tunes class.
        self.tunes = music.Tunes(available_songs)

        # Initialize the dictionary that stores the user's guesses per-row.
        self.button_rows = {
            i: [None] * 4 for i in range(6)
        }

        # Construct the main window.
        self.ROOT = Tk()
        self.ROOT.title(game_title)
        self.ROOT.geometry("252x576")
        self.ROOT.resizable(False, False)

        # Construct the menu bar.
        self.MENU_BAR = Menu(self.ROOT)

        # Construct the main menu.
        self.MAIN_MENU = Menu(self.MENU_BAR, tearoff=0)
        self.MENU_BAR.add_cascade(label="Menu", menu=self.MAIN_MENU)
        self.MAIN_MENU.add_command(label="New Game", command=self.new_game)

        self.MAIN_MENU.add_command(
            label="How To play",
            command=partial(
                showinfo,
                "How To play",
                "Click on the blue pegs to change their colours.\nClick the green "  \
                "DECODE button to see if you cracked the code.\n\n"  \
                "Clues will be given on the yellow label about "  \
                "each colour you chose.\n\n"
                "'*' means correct colour and correct position.\n"
                "'X' means you have the colour correct, but in the wrong position.\n"
                "'0000' means you have no colours at all in the hidden code.\n\n"
                "Try to work out what the secret code is within six attempts to win."
                "\nYou can give in by clicking on the reveal button at any time.",
            ),
        )


        self.MAIN_MENU.add_command(
            label="Visit Blog",
            command=partial(
                self.open_browser, "https://stevepython.wordpress.com/"
            ),
        )
        self.MAIN_MENU.add_command(
            label="About",
            command=partial(
                showinfo,
                "About",
                "Bletchley V2.15r by Steve Shambles Feb 2019",
            ),
        )
        self.MAIN_MENU.add_command(label="Exit", command=self.QUIT)


        # Construct the music menu.
        self.MUSIC_MENU = Menu(self.MENU_BAR, tearoff=0)
        self.MENU_BAR.add_cascade(label="Music", menu=self.MUSIC_MENU)
        # Add the menu items for each of the available songs.
        for song_name, song_file in self.tunes.track_list():
            self.MUSIC_MENU.add_command(
                # Define the menu item label.
                label="Play {}".format(song_name),
                # Call the function to play the appropriate song.
                command=partial(self.tunes.play_track, song_file),
            )
        self.MUSIC_MENU.add_separator()
        self.MUSIC_MENU.add_command(
            label="Stop music", command=self.tunes.stop_music
        )
        self.MUSIC_MENU.add_command(
            label="Free music from Bensound.com",
            command=partial(self.open_browser, "https://bensound.com/"),
        )

        # Add stats menu
        self.STATS_MENU = Menu(self.MENU_BAR, tearoff=0)
        self.MENU_BAR.add_cascade(label="Stats", menu=self.STATS_MENU)
        self.STATS_MENU.add_command(
            label="View Your Stats", command=self.view_stats
        )
        self.STATS_MENU.add_command(
            label="Reset Your Stats", command=self.reset_stats
        )


        # Add the menu bar to the ROOT window.
        self.ROOT.config(menu=self.MENU_BAR)

        # Create frame for the image
        FRAME0 = LabelFrame(self.ROOT)
        FRAME0.grid(padx=18, pady=18)

        if not os.path.isfile("blt-panel-v2.png"):
            messagebox.showinfo("Player Stats",  \
            "The file 'blt-panel-v2.png' is missing\n"  \
            "from the current directory. Please replace it.")
            self.QUIT()

        IMAGE = Image.open('blt-panel-v2.png')
        PHOTO = ImageTk.PhotoImage(IMAGE)
        LABEL = Label(FRAME0, image=PHOTO)
        LABEL.IMAGE = PHOTO
        LABEL.grid(padx=2, pady=2)


        # Create the lists and dict that will store the various elements of
        # each row.
        self.BUTTON_FRAMES = list()
        self.BUTTON_FRAME_LABELS = list()
        self.DECODE_BUTTONS = list()
        self.BUTTON_GUESSES = dict()
        # Construct each row.
        for row_index in range(6):
            # Create the frame.
            BUTTON_FRAME = LabelFrame(
                self.ROOT,
                fg="blue",
                text="Attempt {}".format(row_index + 1),
                relief=SUNKEN
            )
            BUTTON_FRAME.grid()
            # Add the frame to the list.
            self.BUTTON_FRAMES.append(BUTTON_FRAME)

            # Create the empty buttons list.
            BUTTON_GUESS_LIST = [None] * 4
            for button_index in range(4):
                # Craft all four buttons.
                BUTTON = Button(
                    BUTTON_FRAME,
                    bg="skyblue",
                    text=" ",
                    command=partial(
                        self.click_button, row_index, button_index
                    ),
                )
                BUTTON.grid(
                    row=(7 + row_index), column=button_index, pady=4, padx=4
                )
                BUTTON_GUESS_LIST[button_index] = BUTTON
            # Assign the button list to the button dictionary.
            self.BUTTON_GUESSES[row_index] = BUTTON_GUESS_LIST[:]

            # Create the solution frame's label.
            FRAME_LABEL = Label(BUTTON_FRAME, bg="yellow", text="        ")
            FRAME_LABEL.grid(row=(7 + row_index), column=4, pady=4, padx=4)
            # Append the label to the label list.
            self.BUTTON_FRAME_LABELS.append(FRAME_LABEL)

            # Create the decode button.
            DECODE_BUTTON = Button(
                BUTTON_FRAME,
                bg="green2",
                text="DECODE",
                command=partial(self.decode_row, row_index),
            )
            DECODE_BUTTON.grid(row=(7 + row_index), column=5, pady=4, padx=4)
            # Append the decode button to the list.
            self.DECODE_BUTTONS.append(DECODE_BUTTON)

        # Make sure player can only decode row 1 to start with
        # by disabling all other decode buttons.
        for index in range(1, 6):
            self.DECODE_BUTTONS[index].configure(state=DISABLED)

        # cover up secret code with a button.
        self.SOLUTION_FRAME = LabelFrame(
            self.ROOT, fg="blue", text="Solution", relief=SUNKEN, padx=4, pady=6
        )
        self.SOLUTION_FRAME.grid()
        self.SOLUTION_BUTTON = Button(
            self.SOLUTION_FRAME,
            bg="gold",
            text="      REVEAL SECRET CODE      ",
            command=self.reveal_solution,
        )
        self.SOLUTION_BUTTON.grid(row=9, column=5, pady=4, padx=4)

        # Run the main loop.
        self.centre_gui()
        self.run()

    def open_browser(self, website_url):
        """Open the specified URL in a browser window."""
        webbrowser.open(website_url)

    def QUIT(self):
        """Completely quit the game."""
        self.tunes.stop_music()
        self.ROOT.destroy()

    def reveal_solution(self):
        """Reveal button has been clicked, so show secret_code."""
        # Reveal the secret code.
        self.SOLUTION_BUTTON.destroy()
        self.display_solution()
        # Let them know they've lost.
        showinfo("Bletchley", "        G A M E  O V E R  M A N\n\n"  \
                 "     You can do better than that!\n\n"  \
                 "Try again to improve your game stats.")

        PlayerStats.played += 1
        PlayerStats.lost += 1
        self.calc_win_rate()
        self.save_stats()

        self.new_game()


    def view_stats(self):
        '''create an  info msg box'''
        messagebox.showinfo("Player Stats", "Games Played: "  \
        +str(PlayerStats.played)+"\n"+"  Games Won: "+str(PlayerStats.wins)  \
        +"\n"+"   Games Lost: "+str(PlayerStats.lost)  \
        +"\n"+"   Points Won: "+str(PlayerStats.points)  \
        +"\n"+"        Win rate: "+str(PlayerStats.win_rate)+"%")


    def reset_stats(self):
        '''Msbox asks to confirm or not, if so then resets stats to zero.'''
        QUEST = messagebox.askyesno('Really?', 'Are you sure you want '  \
        'to reset all your stats to zero?')

        if QUEST is False:
            return
        self.zero_all_stats()

    def zero_all_stats(self):
        '''Reset all stt to zero, either from menu by user or if stats
        file not found and new one created with zero stats'''
        all_stats = []
        PlayerStats.played = 0
        PlayerStats.wins = 0
        PlayerStats.lost = 0
        PlayerStats.points = 0
        PlayerStats.win_rate = 0
        self.save_stats()

    def calc_points_won(self):
        '''Do simple calc for points won depending on how many
           tries it took to win.'''

        pts = self.attempt * 10
        self.points = 70 - pts
        PlayerStats.points = PlayerStats.points + self.points

    def calc_win_rate(self):
        '''calculate percent wins to games ratio'''
        PlayerStats.win_rate = PlayerStats.wins  / PlayerStats.played *100

    def save_stats(self):
        '''Save playing history to a text file'''

        with open("bletchley.blt", 'w') as contents:

            save_string = str(PlayerStats.played)+str("\n")
            contents.write(save_string)
            save_string = str(PlayerStats.wins)+str("\n")
            contents.write(save_string)
            save_string = str(PlayerStats.lost)+str("\n")
            contents.write(save_string)
            save_string = str(PlayerStats.points)+str("\n")
            contents.write(save_string)
            save_string = str(PlayerStats.win_rate)+str("\n")
            contents.write(save_string)

    def check_stats_exists(self):
        '''Test that bletchley.blt file is there, if not creates new one.'''
        if not os.path.isfile("bletchley.blt"):
            with open("bletchley.blt", "w"):
                self.zero_all_stats()

    def load_stats(self):
        '''Load players playing history from text file.
           The info is stored one variable valueon each new line'''
        self.check_stats_exists()

        with open("bletchley.blt", 'r') as contents:

            SAVED_STATS = contents.read().split('\n')
            all_stats = (SAVED_STATS)

            PlayerStats.played = int((all_stats[0]))
            PlayerStats.wins = int((all_stats[1]))
            PlayerStats.lost = int((all_stats[2]))
            PlayerStats.points = int((all_stats[3]))
            PlayerStats.win_rate = float((all_stats[4]))
            PlayerStats.win_rate = round(PlayerStats.win_rate, 1)

    def centre_gui(self):
        '''Not my code, found on net somewhere, credit to unknown author
           It should centre the game on any screen, but on my 19 inch monitor
           it was too low so had to add -200 to POSITIONDOWN, no idea why.'''
        # Get values of the height and width of gui.
        WINDOWWIDTH = self.ROOT.winfo_reqwidth()
        WINDOWHEIGHT = self.ROOT.winfo_reqheight()

        # Gets both half the screen width/height and window width/height
        POSITIONRIGHT = int(self.ROOT.winfo_screenwidth()/2 - WINDOWWIDTH/2)
        POSITIONDOWN = int(self.ROOT.winfo_screenheight()/2 - WINDOWHEIGHT/2)

        # Positions the window in the center of the page.
        self.ROOT.geometry("+{}+{}".format(POSITIONRIGHT,POSITIONDOWN-200))

    def run(self):
        """Start the main loop."""
        self.load_stats()
        self.ROOT.mainloop()
Example #14
0
class HangmanGUI(Tk):

    def __init__(self,parent=None):
        Tk.__init__(self,parent)
        self.count=0
        self.title('Hangman')
        self.lst = [' ', ' ', ' ', ' ', ' ', ' ', ' ']
        self.lst1 = ["O", "/", "|", "\\", "|", "/", "\\"]
        self.make_widgets()



    def botPlayer(self):
        wordlist=['Adult', 'Aeroplane', 'Air', 'Aircraft Carrier', 'Airforce', 'Airport', 'Album', 'Alphabet', 'Apple', 'Arm',
        'Army', 'Baby', 'Baby', 'Backpack', 'Balloon', 'Banana', 'Bank', 'Barbecue', 'Bathroom', 'Bathtub', 'Bed', 'Bed', 'Bee',
        'Bible', 'Bible', 'Bird', 'Bomb', 'Book', 'Boss', 'Bottle', 'Bowl', 'Box', 'Boy', 'Brain', 'Bridge', 'Butterfly', 'Button',
        'Cappuccino', 'Car',  'Carpet', 'Carrot', 'Cave', 'Chair', 'Chess Board', 'Chief', 'Child', 'Chisel', 'Chocolates',
        'Church', 'Church', 'Circle', 'Circus', 'Circus', 'Clock', 'Clown', 'Coffee', 'Comet', 'Compact Disc', 'Compass',
        'Computer', 'Crystal', 'Cup', 'Cycle', 'Data Base', 'Desk', 'Diamond', 'Dress', 'Drill', 'Drink', 'Drum', 'Dung', 'Ears', 'Earth',
        'Egg', 'Electricity', 'Elephant', 'Eraser', 'Explosive', 'Eyes', 'Family', 'Fan', 'Feather', 'Festival', 'Film', 'Finger', 'Fire',
        'Floodlight', 'Flower', 'Foot', 'Fork', 'Freeway', 'Fruit', 'Fungus', 'Game', 'Garden', 'Gas', 'Gate', 'Gemstone', 'Girl', 'Gloves',
        'God', 'Grapes', 'Guitar', 'Hammer', 'Hat', 'Hieroglyph', 'Highway', 'Horoscope', 'Horse', 'Hose', 'Ice', 'Insect',
        'Jet fighter', 'Junk', 'Kaleidoscope', 'Kitchen', 'Knife', 'Leather jacket', 'Leg', 'Library', 'Liquid', 'Magnet', 'Man', 'Map', 'Maze',
        'Meat', 'Meteor', 'Microscope', 'Milk', 'Milkshake', 'Mist', 'Money $$$$', 'Monster', 'Mosquito', 'Mouth', 'Nail', 'Navy', 'Necklace',
        'Needle', 'Onion', 'PaintBrush', 'Pants', 'Parachute', 'Passport', 'Pebble', 'Pendulum', 'Pepper', 'Perfume', 'Pillow', 'Plane', 'Planet',
        'Pocket', 'Potato', 'Printer', 'Prison', 'Pyramid', 'Radar', 'Rainbow', 'Record', 'Restaurant', 'Rifle', 'Ring', 'Robot', 'Rock', 'Rocket',
        'Roof', 'Room', 'Rope', 'Saddle', 'Salt', 'Sandpaper', 'Sandwich', 'Satellite', 'School', 'Sex', 'Ship', 'Shoes', 'Shop', 'Shower', 'Signature',
        'Skeleton', 'Slave', 'Snail', 'Software', 'Solid', 'Space Shuttle', 'Spectrum', 'Sphere', 'Spice', 'Spiral', 'Spoon', 'Spot Light',
        'Square', 'Staircase', 'Star', 'Stomach', 'Sun', 'Sunglasses', 'Surveyor', 'Swimming Pool', 'Sword', 'Table', 'Tapestry', 'Teeth',
        'Telescope', 'Television', 'Thermometer', 'Tiger', 'Toilet', 'Tongue', 'Torch', 'Torpedo', 'Train', 'Treadmill', 'Triangle', 'Tunnel', 'Typewriter',
        'Umbrella', 'Vacuum', 'Vampire', 'Videotape', 'Vulture', 'Water', 'Weapon', 'Web', 'Wheelchair', 'Window', 'Woman', 'Worm']
        self.wordSpace = []
        self.wordLetters = []
        self.button1.destroy()
        self.button2.destroy()
        randomWordIndex = random.randint(0,(len(wordlist)-1))  # chooses index of word
        self.randomword = wordlist[randomWordIndex].lower()  # gets random word from list
        for i in self.randomword:
            self.wordLetters.append(i)
        for i in range(len(self.randomword)):
            self.wordSpace.append('_')
        self.wordLabel =Label(self,text=self.wordSpace)
        self.wordLabel.grid(row=16,column=0)  # Shows spaces for randomword

        self.alphabet = list(string.ascii_lowercase) # gets alphabet

        self.letterChoice =Label(self,text=self.alphabet)
        self.letterChoice.grid(row=17,column=0)
        self.playerEntry = Entry(self)
        self.playerEntry.grid(row=18,column =0)
        self.submit = Button(self, text='Submit',command=lambda:self.playWord())
        self.submit.grid(row=18,column=1)

    def playWord(self):
        letter = self.playerEntry.get()
        if letter in self.alphabet:
            if letter in self.wordLetters:
                while letter in self.wordLetters:
                    index = self.wordLetters.index(letter)
                    self.wordSpace[index] = letter
                    self.wordLetters[index] = ''
                self.wordLabel.config(text=self.wordSpace)
                self.result.config(text='Yes!')
            else:
                self.result.config(text='Nope')
                self.lst[self.count] = self.lst1[self.count]
                self.top.config(text='       {}       |'.format(self.lst[0]))
                self.middle.config(text='      {}{}{}      |'.format(self.lst[1],self.lst[2],self.lst[3]))
                self.lower.config(text='       {}       |'.format(self.lst[4]))
                self.bottom.config(text='      {} {}      |'.format(self.lst[5],self.lst[6]))
                self.count+=1
            self.alphabet[self.alphabet.index(letter)] = '_'
            self.letterChoice.config(text=self.alphabet)
            self.playerEntry.delete(0,END)
        else:
            showinfo(title='Invalid Choice', message='You have already picked this letter, please try again.')
        if self.lst[6] == '\\':
            showinfo(title='You Lost', message='You lost, Play Again if you want')
            self.resetGame()
        if '_' not in self.wordSpace:
            showinfo(title='You Won',message="You Won!, Play Again if you want")
            self.resetGame()

    def resetGame(self):
        self.lst = [' ', ' ', ' ', ' ', ' ', ' ', ' ']
        self.lst1 = ["O", "/", "|", "\\", "|", "/", "\\"]
        self.playerEntry.destroy()
        self.submit.destroy()
        self.result.destroy()
        self.letterChoice.destroy()
        self.wordLabel.destroy()
        self.make_widgets()

        self.alphabet = list(string.ascii_lowercase)

    def playerChoice(self):
        self.playmode.config(text='')
        self.wordSpace = []
        self.wordLetters = []
        self.button1.destroy()
        self.button2.destroy()
        self.playerChosenWord=''

        self.playerWordEntry = Entry(self)
        self.playerWordEntry.grid(row=13,column =0)
        self.button = Button(self, text='Submit', command=lambda: self.buttonGet())
        self.button.grid(row=13, column=1)

        self.alphabet = list(string.ascii_lowercase) # gets alphabet

        for i in self.playerChosenWord:
            self.wordLetters.append(i)

        for i in range(len(self.playerChosenWord)):
            self.wordSpace.append('_')



    def buttonGet(self):
        self.playerChosenWord = self.playerWordEntry.get()
        self.alphabet = list(string.ascii_lowercase)  # gets alphabet

        for i in self.playerChosenWord:
            self.wordLetters.append(i)

        for i in range(len(self.playerChosenWord)):
            self.wordSpace.append('_')

        self.wordLabel = Label(self, text=self.wordSpace)
        self.wordLabel.grid(row=16, column=0)
        self.letterChoice =Label(self,text=self.alphabet)
        self.letterChoice.grid(row=17,column=0)
        self.playerEntry = Entry(self)
        self.playerEntry.grid(row=18,column =0)
        self.submit = Button(self, text='Submit',command=lambda:self.playWord())
        self.button.destroy()
        self.playerWordEntry.destroy()
        self.submit.grid(row=18,column=1)

    def multiPlayer(self):
        print('multi')

    def make_widgets(self):
        Label(self,text='This is Hangman').grid(row=0,column=0)
        Label(self,text='A Game where you choose a word and I or another player will attempt to guess that word.').grid(row=1,column=0)
        Label(self,text='Every time a chosen letter is wrong, one part of the Hangman will be added.').grid(row=2,column=0)
        Label(self,text='If the entire Hangman is drawn before the word is guessed, YOU WIN!!!').grid(row=3,column=0)
        Label(self,text='        _______').grid(row=4,column=0)
        Label(self,text='       |       |').grid(row=5,column=0)
        Label(self,text='       |       |').grid(row=6,column=0)

        self.top = Label(self,text='       {}       |'.format(self.lst[0]))
        self.top.grid(row=7,column=0)
        self.middle = Label(self,text='      {}{}{}      |'.format(self.lst[1],self.lst[2],self.lst[3]))
        self.middle.grid(row=8,column=0)
        self.lower = Label(self,text='       {}       |'.format(self.lst[4]))
        self.lower.grid(row=9,column=0)
        self.bottom = Label(self,text='      {} {}      |'.format(self.lst[5],self.lst[6]))
        self.bottom.grid(row=10,column=0)

        Label(self,text='               |').grid(row=11,column=0)
        Label(self,text='          ===========').grid(row=12,column=0)
        self.result = Label(self, text='')
        self.result.grid(row=19, column=0, columnspan=2)
        self.button1=Button(self,text='Bot Chooses Word',command=lambda:self.botPlayer())
        self.button1.grid(row=14,column=0)
Example #15
0
class colorDice(tkinter.Button):
    
    def __init__(self):
        
        self.button = None
        self.g()
        self.count=0
        self.diceNumbers=[]
        self.obj =[]
        
    def random_generatorForColor(self):
        result = random.randint(0, 478)
        f = cfc.c.COLORS[result]
        return str(f)   
    def random_generator(self):
        result = random.randint(1, 6)
        self.numberCounter(result)
        strinG = ""
        strinG += str(result)
        return strinG
    def diceNumbers(self, num):
        
        return num
    def g(self):
        global count
        if(self.button == None):
            
            result= self.random_generator()
            cResult = self.random_generatorForColor()
         
            dN.Num.diceNumbers.append(result)
            
            self.button =  Button(root, text = "" + result, bg =""+cResult, height = 3  , width = 10, command = self.g)
            self.button.pack()
            count+=1
          
           
        if(count%15==0 and count !=0 ):
            
            r=dN.Num.diceNumbers
            
            self.name()
           
            
            for i in r:
                print(i)
            

        else:
            
            result = self.random_generator()
            cResult = self.random_generatorForColor()
            r=dN.Num.diceNumbers.append(result)
            self.button.destroy()
            self.button =  Button(root, text = "" + result, bg =""+cResult , height = 3  , width = 10, command = self.g)
            self.button.pack()
            count+=1
            
            
        if(count%15==0 and count !=0 ):
            Done=True
            r=dN.Num.diceNumbers
            for i in r:
                print(i)
            
            self.name()
            
            
    def numberCounter(self, result):
            if result == 1:
                diceList[0]+=1
            elif result == 2:
                diceList [1]+=1
            elif result == 3:
                diceList[2]+=1
            elif result == 4:
                diceList[3]+=1
            elif result == 5:
                diceList[4]+=1
            else:
                diceList[5]+=1
    def takingInuserUnput(self,input):
        return input
    def name(self):
        r0 = Tk()
        label =  Label(r0, text = "First and Last Name", justify ="center")
        label.pack()
        e = Entry(r0)
        e.pack()
        b = Button(r0, text="Submit", width=10, command=lambda : self.OnButtonClick(1,e.get()))
        b.pack()
        
        
       
       
    def callback(self):
            import ColorandOrdinary.ShowChart as M
            M.start(diceList)
    def OnButtonClick(self, button_id,e):
        if button_id == 1:
            st =""
            r=dN.Num.diceNumbers
            f=dict(zip(('Roll One is: ', 'Roll Two is: ','Roll Three is: ','Roll Four is: ','Roll Five is: ','Roll Six is: ','Roll Seven is: ',
                      'Roll Eight is: ','Roll Nine is: ','Roll Ten is: ','Roll Eleven is: ','RollTwelve is: ','Roll Thirthteenth is: ','Roll Fourthteenth is: ','Roll Fifthteenth is: '), (r)))
            nameDict= {'Name: ':e}
            ColorD ={'Type of Dice':'COLOR'}
            f.update(ColorD)
            f.update(nameDict)
            collection.insert(f)
            import ColorandOrdinary.Send_Sms as SS 
            
            client = SS.Client("ACcb07e49822bc4906cb515e45b66447d4","ca6aa57cfa027e322c8dd80aa5569e5a")
            client.messages.create(from_='+18562882993',
                       to='+12672304684',
                       body=' '.join('{0}{1}, '.format(key, val) for key, val in f.items()))
            self.callback()
class MyFirstGUI:
    def __init__(self, master):
        self.master = master
        master.title("Blackjack - Caiden Tousaw")

        self.label = Label(master, text=starting_card)
        self.label.pack()
        self.label.place(x=460, y=480)

        self.label2 = Label(master, text=starting_card2)
        self.label2.pack()
        self.label2.place(x=500, y=480)

        self.label_dealer = Label(master, text=dealer_card)
        self.label_dealer.pack()
        self.label_dealer.place(x=460, y=80)

        self.label_dealer2 = Label(master, text="??")
        self.label_dealer2.pack()
        self.label_dealer2.place(x=500, y=80)

        self.label3 = Label(master, text=new_card)
        self.label4 = Label(master, text=new_card2)

        self.label_dealer3 = Label(master, text=dealer_card3)

        # The hit button will give you another card value
        self.hit_button = Button(
            master, text="Hit",
            command=self.hit)  # The Button command will create a button.
        self.hit_button.pack()
        self.hit_button.config(
            height=2, width=10, background="black",
            foreground="white")  # Cof=nfig changes how the thing looks
        self.hit_button.place(x=60, y=540)  # Will place it in these coords

        # This is the "stand button" that will cause the user to stand, and for them to win, or lose
        self.stand_button = Button(master, text="Stand", command=self.stand)
        self.stand_button.pack()  # This will place the button on the screen
        self.stand_button.config(height=2,
                                 width=10,
                                 background="black",
                                 foreground="white")
        self.stand_button.place(x=820, y=540)

        if starting_card == 1:
            if starting_card2 == 10:
                print("You got 21! you win!")
            else:
                pass
        else:
            pass

        if starting_card2 == 1:
            if starting_card == 10:
                print("You got 21! you win!")
            else:
                pass
        else:
            pass

        if dealer_card == 1:
            if dealer_card2 == 10:
                print("The dealer got 21! you lose.")
                self.label_dealer2 = Label(master, text=dealer_card2)
                self.label_dealer2.pack()
                self.label_dealer2.place(x=500, y=80)

            else:
                pass
        else:
            pass

        if dealer_card2 == 1:
            if dealer_card == 10:
                print("The dealer got 21! you lose.")
                self.label_dealer = Label(master, text=dealer_card)
                self.label_dealer.pack()
                self.label_dealer.place(x=460, y=80)
            else:
                pass
        else:
            pass

    def hit2(self):
        print("You hit!")
        self.label4.pack()
        self.label4.place(x=450, y=480)
        self.label2.place(x=530, y=480)
        self.label.place(x=420, y=480)
        self.label3.place(x=480, y=480)
        if starting_card + starting_card2 + new_card + new_card2 > 21:
            print("You busted! You lost.")
        elif starting_card + starting_card2 + new_card + new_card2 == 21:
            print("You win! you got 21!")
        else:
            pass

    def hit(self):
        print("You hit!")
        self.label3.pack()
        self.label2.place(x=510, y=480)
        self.label.place(x=480, y=480)
        self.label3.place(x=450, y=480)
        if starting_card + starting_card2 + new_card > 21:
            print("You busted! You lost.")
        elif starting_card + starting_card2 + new_card == 21:
            print("You win! you got 21!")
        else:
            # The hit button will give you another card value
            self.hit_button = Button(
                text="Hit",
                command=self.hit2)  # The Button command will create a button.
            self.hit_button.pack()
            self.hit_button.config(
                height=2, width=10, background="black",
                foreground="white")  # Cof=nfig changes how the thing looks
            self.hit_button.place(x=60, y=540)  # Will place it in these coords

    def stand(self):
        self.hit_button.destroy()
        self.stand_button.destroy()
        print("You stand!")
        if dealer_card + dealer_card2 < 17:
            self.label_dealer = Label(text=dealer_card)
            self.label_dealer.pack()
            self.label_dealer.place(x=540, y=80)
            self.label_dealer2 = Label(text="??")
            self.label_dealer2.pack()
            self.label_dealer2.place(x=500, y=80)
            self.label_dealer3 = Label(text=dealer_card3)
            self.label_dealer3.pack()
            self.label_dealer3.place(x=460, y=80)
            self.label_dealer4 = Label(text=dealer_card4)
            self.label_dealer4.pack()
            self.label_dealer4.place(x=420, y=80)
            if dealer_card + dealer_card2 + dealer_card3 < 17:
                time.sleep(0.5)
                self.label_dealer = Label(text=dealer_card)
                self.label_dealer.pack()
                self.label_dealer.place(x=500, y=80)
                self.label_dealer2 = Label(text="??")
                self.label_dealer2.pack()
                self.label_dealer2.place(x=460, y=80)
                self.label_dealer3 = Label(text=dealer_card3)
                self.label_dealer3.pack()
                self.label_dealer3.place(x=420, y=80)
                if dealer_card + dealer_card2 + dealer_card3 + dealer_card4 < 17:
                    self.label_dealer = Label(text=dealer_card)
                    self.label_dealer.pack()
                    self.label_dealer.place(x=540, y=80)
                    self.label_dealer2 = Label(text="??")
                    self.label_dealer2.pack()
                    self.label_dealer2.place(x=500, y=80)
                    self.label_dealer3 = Label(text=dealer_card3)
                    self.label_dealer3.pack()
                    self.label_dealer3.place(x=460, y=80)
                    self.label_dealer4 = Label(text=dealer_card4)
                    self.label_dealer4.pack()
                    self.label_dealer4.place(x=420, y=80)
            elif dealer_card + dealer_card2 + dealer_card3 == 21:
                tims.sleep(0.5)
                print("The dealer got 21! You lose")
            else:
                self.label_dealer2.destroy()
                time.sleep(0.5)
                self.label_dealer2 = Label(text=dealer_card2)
                print("The dealer busted! You win!")
        else:
            print("wiat")
Example #17
0
class TrendProg(Frame):

    def __init__(self, parent):
        Frame.__init__(self, parent, background='white')
        # saved reference to parent widget. "Tk root window"
        self.parent = parent
        self._workbook = None
        self._file_path = None
        self._folder_path = None

        # set properties of buttons
        self.frame_1 = Frame(self, relief=RAISED)
        self.run_button = Button(self, text='Run', width=10,
                                 command=self.run_program)
        self.file_button = Button(self.frame_1, text='Select File',
                                  width=15, command=self.get_file)
        self.folder_button = Button(self.frame_1, text='Select Folder',
                                    width=15, command=self.get_folder)
        self.close_button = Button(self, text='Close', width=10,
                                   command=self.quit)
        self.init_gui()

    def init_gui(self):
        self.parent.title('Trending Analysis')
        # fill frame to take up whole of root window
        self.pack(fill=BOTH, expand=True)
        self.frame_1.pack(fill=BOTH, expand=True)

        # put buttons on GUI
        self.folder_button.pack(side=RIGHT, padx=5)
        self.file_button.pack(side=LEFT, padx=5, pady=5)
        self.close_button.pack(side=RIGHT, padx=5, pady=5)
        self.run_button.pack(side=RIGHT, pady=5)

    def get_file(self):
        self._file_path = filedialog.askopenfilename()
        if self._file_path != '':
            self.file_button.config(text='File Selected!')
            self.file_button.pack(fill=BOTH, expand=True, padx=5, pady=5)
            self.folder_button.destroy()

    def get_folder(self):
        self._folder_path = filedialog.askdirectory()
        if self._folder_path != '':
            self.folder_button.config(text='Folder Selected!')
            self.folder_button.pack(fill=BOTH, expand=True, padx=5, pady=5)
            self.file_button.destroy()

    def run_program(self):
        workbook = 'Draft_Detail_Findings.xlsx'
        worksheet = 'Template'
        # user selected one CAPA
        print('=' * 75)
        if self._folder_path == '' or self._folder_path is None:
            self._file_path = self.convert_to_docx(self._file_path)
            docx_to_xlsx.main(self._file_path, workbook, worksheet)
            print('=' * 75)
        # user selected a folder of CAPA's
        elif self._file_path == '' or self._file_path is None:
            for f in os.listdir(self._folder_path):
                # get full path name
                file_name = str(self._folder_path + '/' + f)
                file_name = self.convert_to_docx(file_name)
                docx_to_xlsx.main(file_name, workbook, worksheet)
                print('=' * 75)

        # get ready to end the program
        # pd = project_data.TrendData(workbook, worksheet)
        print('Done.')
        self.frame_1.destroy()
        self.run_button.destroy()
        self.close_button.config(text='Done.')
        self.close_button.pack(fill=BOTH, expand=True, padx=10, pady=10)

    @classmethod
    def convert_to_docx(cls, file_selected):
        """ Check that file(s) selected is .docx NOT .doc and convert if needed. """
        if str(file_selected).endswith('.docx'):
            return file_selected
        else:
            new_file_name = re.sub('.doc', '.docx', file_selected)
            # full path to wordconv.exe
            word_conv = r'C:\Program Files (x86)\Microsoft Office\Office12\wordconv.exe'
            commands = ['wordconv.exe', '-oice', '-nme', file_selected, new_file_name]
            try:
                print('CONVERTING {}'.format(file_selected))
                subprocess.Popen(commands, executable=word_conv)
                # wait for converted file to be created
                while not os.path.exists(new_file_name):
                    time.sleep(1.5)
                print('REMOVING old .doc file ...')
                os.remove(file_selected)
                return new_file_name
            except OSError:
                print('FAILED to convert file. Check to see if it exists.')
Example #18
0
class initface():
    def __init__(self, master):
        global currenttime
        currenttime = strftime('%Y-%m-%d %H:%M:%S', localtime()).split(' ')
        self.Year = int(currenttime[0].split('-')[0])
        self.Month = int(currenttime[0].split('-')[1])
        self.Day = int(currenttime[0].split('-')[2])
        self.master = master
        self.user_info = User()
        #设置窗口大小和位置
        self.master.geometry('370x400+400+100')
        self.master.minsize(370, 400)
        self.master.maxsize(370, 400)
        self.master.title(u'我的成功日记')
        global content_first
        command = self.user_info.load_conf()
        #print(command)

        #创建一个文本框
        #self.entry = Entry(self.master)
        #self.entry.place(x=10,y=10,width=200,height=25)
        #self.entry.bind("<Key-Return>",self.submit1)
        self.record_in = Text(self.master, background='azure')
        # 喜欢什么背景色就在这里面找哦,但是有色差,得多试试:http://www.science.smith.edu/dftwiki/index.php/Color_Charts_for_TKinter
        self.record_in.place(x=10, y=5, width=345, height=155)
        self.record_in.bind("<Key-Return>", self.submit1)

        #创建三个按钮
        #为按钮添加事件
        #self.submit_btn = Button(self.master,text=u'提交',command=self.submit)
        #self.submit_btn.place(x=280,y=165,width=35,height=25)
        self.submit_btn2 = Button(self.master, text=u'复位', command=self.reset)
        self.submit_btn2.place(x=200, y=365, width=40, height=30)
        self.submit_btn3 = Button(self.master,
                                  text=u'保存上传',
                                  command=self.upload)
        self.submit_btn3.place(x=280, y=365, width=65, height=30)
        self.submit_btn4 = Button(self.master,
                                  text=u'查看日历',
                                  command=self.check)
        self.submit_btn4.place(x=20, y=365, width=65, height=30)
        #日记记录输出结果
        self.title_label = Label(self.master, text=u'diary record:')
        self.title_label.place(x=10, y=165)
        #记录结果

        self.record_out = Text(self.master, background='light cyan')
        self.record_out.place(x=10, y=193, width=345, height=165)
        #回车提交

        #初始参数输入
        self.record_in.insert(END, '请输入用户名:')
        self.record_in.focus_force()
        #self.record_in.mark('insert',END)
        #print(currenttime)
        #print(currenttime)
        content_first = '日期: ' + currenttime[0] + '     时间: ' + currenttime[
            1] + '\n'
        self.record_out.insert(END, content_first)

    def check(self):
        global datelist, cmd_index, file_name, user_command, backupdir
        backupdir = user_command[-1].split(' ')[1]
        #print(backupdir)
        cmd_index = 0
        datelist = []
        if file_name == '':
            datelist = []
        else:
            with open('.\\data\\' + file_name + '.txt', "r") as f:
                data = f.read()
                #print(data)
            date_all = re.findall(r"(\d{4}-\d{1,2}-\d{1,2})", data)
            for date in date_all:
                datelist.append(date)
        #print(datelist)

        self.record_in.destroy()
        self.record_out.destroy()
        self.submit_btn2.destroy()
        self.submit_btn3.destroy()
        self.submit_btn4.destroy()
        self.title_label.destroy()
        Calendar_ui(self.master, self.Year, self.Month, self.Day)

    def submit1(self, event):
        global cmd_index
        global user_command
        global file_name
        #从输入框获取用户输入的值
        #content_ori = self.result_text1.get(0.0,END).split('\n')[-2]
        #print(content_ori)
        #content = content_ori.strip().replace("\n"," ")
        content = self.record_in.get(0.0, END)
        self.user_name = content.strip().replace('\n', '').split(':')[-1]
        #print(content)
        if cmd_index == 0:
            self.record_out.insert(END, '你好,' + self.user_name + '\n\n')
            file_name = self.user_name
        else:
            self.record_out.insert(END, content.strip() + '\n')

        self.record_in.delete(0.0, END)
        self.record_in.mark_set('insert', '0.0')

        cmd_index += 1
        #print(user_command)
        if cmd_index <= len(user_command) - 1:
            self.record_in.insert(
                0.0, user_command[cmd_index - 1].strip().replace('\n', ''))
        else:
            self.record_in.mark_set('insert', '0.0')
            self.record_in.insert(0.0, '当天的成功日记已经完成,请确认内容后点击‘保存上传...’')

        #self.result_text.delete(0.0,END)
        #self.result_text.insert(END,result)

        #print(content)

    def reset(self):
        global cmd_index
        self.record_in.delete(0.0, END)
        self.record_out.delete(2.0, END)
        self.record_out.insert(END, '\n')
        self.record_in.insert(END, '请输入用户名:')
        cmd_index = 0

    def upload(self):
        global content_first
        if file_name != '':
            self.record_in.delete(0.0, END)
            self.record_in.mark_set('insert', '0.0')
            f = open('.\\data\\' + file_name + '.txt', 'a+')
            record = self.record_out.get(0.0, END).strip() + '\n\n\n\n\n'
            f.write(record)
        else:
            self.record_in.insert(0.0, '未指定用户名,请按复位键!')
        f.seek(0)
        lines = f.readlines()
        #print(Counter(lines)[content_first])
        if Counter(lines)[content_first] == 0:
            self.record_in.insert(0.0, '保存失败!')
        elif Counter(lines)[content_first] == 1:
            self.record_in.insert(0.0, '保存成功!')
        elif Counter(lines)[content_first] > 1:
            self.record_in.insert(0.0, '存在重复上传数据,可进入文件删除多余内容!')
        f.close()
Example #19
0
class Frontend():
    def __init__(self, x, y, b):
        self.x = str(x)  #1600
        self.y = str(y)  #900
        self.pressed = 0
        self.b = 10
        self.c = 30
        self.grapher = 0
        self.graph = [0, 0, 0, 0]
        self.root = b

    def startwindow(self):
        # self.root=Tk()
        a = str(self.x + 'x' + self.y)
        self.root.title('Wahrscheinlichkeinten & Simulation')
        self.root.geometry(a)
        self.g = Label(self.root, bg='white')
        self.g.place(x=0, y=0, width=self.x, height=self.y)
        # self.g.bind('<1>',self.optioncanged)
        self.lst1 = [
            'Marriage', 'Atom', 'BubbleGum', 'House_of_Cards', 'Lotto',
            'SecretSanta', 'Coins'
        ]
        self.var1 = StringVar(self.root)
        self.var1.set('Marriage')
        self.drop = OptionMenu(self.root, self.var1, *self.lst1)
        self.drop.config(font=('Arial', (30)), bg='white')
        self.drop['menu'].config(font=('calibri', (20)), bg='white')
        self.drop.pack(side=TOP)
        self.photo = PhotoImage(file='z1.gif')
        self.label = Label(image=self.photo, borderwidth=0)
        self.label.image = self.photo
        self.label.bind('<1>', self.MouseOneDown)
        self.label.place(y=0, x=int(self.x) - 200)
        self.startbutton = Button(self.root,
                                  text='Start',
                                  font=('Arial', 40),
                                  bg='#B4045F',
                                  borderwidth=5,
                                  command=self.startpressed)
        self.startbutton.place(x=0,
                               y=int(self.y) - 100,
                               width=int(self.y) - 200,
                               height=100)
        self.csvbutton = Button(self.root,
                                text='Export CSV',
                                font=('Arial', 40),
                                bg='green',
                                borderwidth=5,
                                command=self.csvpressed)
        self.csvbutton.place(x=int(self.x) / 2 + 50,
                             y=int(self.y) - 100,
                             width=int(self.y) - 230,
                             height=100)

    def startpressed(self):
        if self.grapher == 1:
            for x in range(len(self.graph)):
                if self.graph[x] != 0:
                    self.graph[x].destroy()
            self.grapher = 0
            self.root.update()
        a = self.var1.get()
        if self.pressed == 1:
            try:
                self.b = int(self.changer0.get('1.0', 'end-1c'))
            except (AttributeError, TclError, ValueError):
                self.b = 10
            try:
                self.c = self.changer2.get('1.0', 'end-1c')
            except (AttributeError, TclError, ValueError):
                self.c = 1
        if a == 'Marriage':
            self.run0 = Marriage(self.b)
            self.run0.DEBUG = False
            self.run0.sim()
        elif a == 'Atom':
            self.c = float(self.c)
            self.run1 = Atom(self.c, self.b)
            self.run1.DEBUG = False
            self.run1.sim()
        elif a == 'BubbleGum':
            self.run2 = BubbleGum(self.b)
            self.run2.DEBUG = False
            self.run2.sim()
            self.grapher = 1
            self.graph = [0, 0]
            g = str(round(self.run2.getrel()[0], 4))
            h = str(round(self.run2.getrel()[1], 4))
            self.graph[0] = Label(self.root,
                                  bg='white',
                                  text='Durchschnitt Karten zu viel: ' + g,
                                  font=('calibri', 19))
            self.graph[0].place(x=10, y=450)
            self.graph[1] = Label(self.root,
                                  bg='white',
                                  text='Durchschnitt dass es passiert: ' + h,
                                  font=('calibri', 19))
            self.graph[1].place(x=10, y=500)
        elif a == 'House_of_Cards':
            if self.c == '':
                self.c = 0
            else:
                self.c = int(self.c)
            self.run3 = House_of_Cards(self.b, self.c)
            self.run3.DEBUG = False
            self.run3.sim()
            self.grapher = 1
            self.graph = [0]
            self.graph[0] = Label(self.root,
                                  bg='white',
                                  text=('Durchschnitt: ' +
                                        str(round(self.run3.getrel(), 4))),
                                  font=('calibri', 19))
            self.graph[0].place(x=10, y=450)
        elif a == 'Lotto':
            self.run4 = Lotto(self.b)
            self.run4.DEBUG = False
            self.run4.sim()
            x = 4
            y = 1
            count = 0
            self.graph = [0, 0, 0, 0]
            self.grapher = 1
            self.graph[0] = Label(self.root, bg='black')
            self.graph[0].place(x=10,
                                width=10 + (int(self.x) * 0.8),
                                height=1,
                                y=int(self.y) - int(self.y) / 4 * 0.5 - 350)
            self.graph[1] = Label(self.root,
                                  text='50%',
                                  bg='white',
                                  font=('calibri', 10))
            self.graph[1].place(x=60 + (int(self.x) * 0.8),
                                width=50,
                                height=50,
                                y=int(self.y) - int(self.y) / 4 * 0.5 - 375)
            self.graph[2] = Label(self.root, bg='black')
            self.graph[2].place(x=10, width=20, height=1, y=int(self.y) - 350)
            self.graph[3] = Label(self.root, bg='black')
            self.graph[3].place(x=10,
                                width=20,
                                height=1,
                                y=int(self.y) - int(self.y) / 4 - 350)
            for draw in self.run4.turns:
                if draw.count(0) == 0:
                    count += 1
                elif draw.count(1) == 0:
                    count += 1
                elif draw.count(2) == 0:
                    count += 1
                elif draw.count(3) == 0:
                    count += 1
                elif draw.count(4) == 0:
                    count += 1
                elif draw.count(5) == 0:
                    count += 1
                self.graph += [0]
                self.graph[x] = Label(self.root, bg='red')
                if str(self.c) == '1':
                    self.graph[x].place(
                        x=int(10 + (int(self.x) * 0.8) * ((y - 1) / self.b)),
                        width=int(1250 / self.b),
                        height=int(self.y) - 350 - (int(
                            int(self.y) - int(self.y) / 4 *
                            (count / y) - 350)),
                        y=int(
                            int(self.y) - int(self.y) / 4 * (count / y) - 350))
                else:
                    self.graph[x].place(
                        x=int(10 + (int(self.x) * 0.8) * (y / self.b)),
                        width=3,
                        height=3,
                        y=int(
                            int(self.y) - int(self.y) / 4 * (count / y) - 350))
                x += 1
                y += 1
                self.root.update()
        elif a == 'SecretSanta':
            if self.c == '':
                self.c = 1
            else:
                self.c = int(self.c)
            self.run5 = SecretSanta(self.b, self.c)
            self.run5.DEBUG = False
            self.run5.sim()
            self.grapher = 1
            self.graph = [0]
            self.graph[0] = Label(self.root,
                                  bg='white',
                                  text=('Durchschnitt: ' +
                                        str(round(self.run5.getrel(), 4))),
                                  font=('calibri', 19))
            self.graph[0].place(x=10, y=450)
        elif a == 'Coins':
            self.run6 = Coins(self.b)
            self.run6.sim()
            self.grapher = 1
            self.graph = [0, 0]
            v = self.run6.geterg()
            vv = self.run6.getrel()
            self.graph[0] = Label(self.root,
                                  bg='white',
                                  text=('Statistik für www: ' + str(v[0]) +
                                        '    ' + str(vv[0])),
                                  font=('calibri', 19))
            self.graph[0].place(x=10, y=450)
            self.graph[1] = Label(self.root,
                                  bg='white',
                                  text=('Statistik für zwz:   ' + str(v[1]) +
                                        '    ' + str(vv[1])),
                                  font=('calibri', 19))
            self.graph[1].place(x=10, y=500)

    def csvpressed(self):
        a = self.var1.get()
        if a == 'Marriage':
            self.run0.exportcsv('Marriage_Simulation.csv')
        elif a == 'Atom':
            self.run1.exportCSV('Atom_Simulation.csv')
        elif a == 'Lotto':
            self.run4.exportCSV('Lotto_Simulation.csv')
#  def optioncanged(self,event):
#          a=self.var1.get()
#         if a=='Marriage':
#            self.csvbutton.destroy()
#           self.csvbutton=Button(self.root,text='Export CSV',font=('Arial',40),bg='green',borderwidth=5,command=self.csvpressed)
#      self.csvbutton.place(x=int(self.x)/2+50,y=int(self.y)-100,width=int(self.y)-230,height=100)
#      elif a=='Atom':
#         self.csvbutton.destroy()
#        self.csvbutton=Button(self.root,text='Export CSV',font=('Arial',40),bg='green',borderwidth=5,command=self.csvpressed)
#       self.csvbutton.place(x=int(self.x)/2+50,y=int(self.y)-100,width=int(self.y)-230,height=100)
#            elif a=='BubbleGum':
#               self.csvbutton.destroy()
#              self.csvbutton=Button(self.root,text='Export CSV',font=('Arial',40),bg='gray',borderwidth=5)
#             self.csvbutton.place(x=int(self.x)/2+50,y=int(self.y)-100,width=int(self.y)-230,height=100)
#        elif a=='House_of_Cards':
#           self.csvbutton.destroy()
#          self.csvbutton=Button(self.root,text='Export CSV',font=('Arial',40),bg='gray',borderwidth=5)
#         self.csvbutton.place(x=int(self.x)/2+50,y=int(self.y)-100,width=int(self.y)-230,height=100)
#    elif a=='Lotto':
#       self.csvbutton.destroy()
#      self.csvbutton=Button(self.root,text='Export CSV',font=('Arial',40),bg='green',borderwidth=5,command=self.csvpressed)
#     self.csvbutton.place(x=int(self.x)/2+50,y=int(self.y)-100,width=int(self.y)-230,height=100)
#elif a=='SecretSanta':
#             self.csvbutton.destroy()
#            self.csvbutton=Button(self.root,text='Export CSV',font=('Arial',40),bg='gray',borderwidth=5)
#           self.csvbutton.place(x=int(self.x)/2+50,y=int(self.y)-100,width=int(self.y)-230,height=100)

    def MouseOneDown(self, event):
        if self.pressed == 0:
            a = self.var1.get()
            if a == 'Marriage':
                self.changer0 = Text(self.root,
                                     bg='white',
                                     font=('Arial', 30),
                                     borderwidth=1)
                self.changer0.place(y=100,
                                    x=int(self.x) - 150,
                                    width=100,
                                    height=50)
                self.changer1 = Label(self.root,
                                      text='Versuche:',
                                      bg='white',
                                      font=('Arial', 30),
                                      borderwidth=1)
                self.changer1.place(y=100,
                                    x=int(self.x) - 400,
                                    width=250,
                                    height=50)
                self.csvbutton.destroy()
                self.csvbutton = Button(self.root,
                                        text='Export CSV',
                                        font=('Arial', 40),
                                        bg='green',
                                        borderwidth=5,
                                        command=self.csvpressed)
                self.csvbutton.place(x=int(self.x) / 2 + 50,
                                     y=int(self.y) - 100,
                                     width=int(self.y) - 230,
                                     height=100)
            elif a == 'Atom':
                self.changer0 = Text(self.root,
                                     bg='white',
                                     font=('Arial', 30),
                                     borderwidth=1)
                self.changer0.place(y=100,
                                    x=int(self.x) - 150,
                                    width=100,
                                    height=50)
                self.changer1 = Label(self.root,
                                      text='Anzahl der Atome:',
                                      bg='white',
                                      font=('Arial', 30),
                                      borderwidth=1)
                self.changer1.place(y=100,
                                    x=int(self.x) - 600,
                                    width=450,
                                    height=50)
                self.changer2 = Text(self.root,
                                     bg='white',
                                     font=('Arial', 30),
                                     borderwidth=1)
                self.changer2.place(y=200,
                                    x=int(self.x) - 150,
                                    width=100,
                                    height=50)
                self.changer3 = Label(self.root,
                                      text='Zerfallswahrscheinlichkeit:',
                                      bg='white',
                                      font=('Arial', 30),
                                      borderwidth=1)
                self.changer3.place(y=200,
                                    x=int(self.x) - 650,
                                    width=500,
                                    height=50)
                self.csvbutton.destroy()
                self.csvbutton = Button(self.root,
                                        text='Export CSV',
                                        font=('Arial', 40),
                                        bg='green',
                                        borderwidth=5,
                                        command=self.csvpressed)
                self.csvbutton.place(x=int(self.x) / 2 + 50,
                                     y=int(self.y) - 100,
                                     width=int(self.y) - 230,
                                     height=100)
            elif a == 'BubbleGum':
                self.changer0 = Text(self.root,
                                     bg='white',
                                     font=('Arial', 30),
                                     borderwidth=1)
                self.changer0.place(y=100,
                                    x=int(self.x) - 150,
                                    width=100,
                                    height=50)
                self.changer1 = Label(self.root,
                                      text='Versuche:',
                                      bg='white',
                                      font=('Arial', 30),
                                      borderwidth=1)
                self.changer1.place(y=100,
                                    x=int(self.x) - 400,
                                    width=250,
                                    height=50)
                self.csvbutton.destroy()
                self.csvbutton = Button(self.root,
                                        text='Export CSV',
                                        font=('Arial', 40),
                                        bg='gray',
                                        borderwidth=5)
                self.csvbutton.place(x=int(self.x) / 2 + 50,
                                     y=int(self.y) - 100,
                                     width=int(self.y) - 230,
                                     height=100)
            elif a == 'House_of_Cards':
                self.changer0 = Text(self.root,
                                     bg='white',
                                     font=('Arial', 30),
                                     borderwidth=1)
                self.changer0.place(y=100,
                                    x=int(self.x) - 150,
                                    width=100,
                                    height=50)
                self.changer1 = Label(self.root,
                                      text='Versuche:',
                                      bg='white',
                                      font=('Arial', 30),
                                      borderwidth=1)
                self.changer1.place(y=100,
                                    x=int(self.x) - 400,
                                    width=250,
                                    height=50)
                self.changer2 = Text(self.root,
                                     bg='white',
                                     font=('Arial', 30),
                                     borderwidth=1)
                self.changer2.place(y=200,
                                    x=int(self.x) - 150,
                                    width=100,
                                    height=50)
                self.changer3 = Label(self.root,
                                      text='Kartenanzahl(32,55):',
                                      bg='white',
                                      font=('Arial', 30),
                                      borderwidth=1)
                self.changer3.place(y=200,
                                    x=int(self.x) - 620,
                                    width=450,
                                    height=50)
                self.csvbutton.destroy()
                self.csvbutton = Button(self.root,
                                        text='Export CSV',
                                        font=('Arial', 40),
                                        bg='gray',
                                        borderwidth=5)
                self.csvbutton.place(x=int(self.x) / 2 + 50,
                                     y=int(self.y) - 100,
                                     width=int(self.y) - 230,
                                     height=100)
            elif a == 'Lotto':
                self.changer0 = Text(self.root,
                                     bg='white',
                                     font=('Arial', 30),
                                     borderwidth=1)
                self.changer0.place(y=100,
                                    x=int(self.x) - 150,
                                    width=100,
                                    height=50)
                self.changer1 = Label(self.root,
                                      text='Versuche:',
                                      bg='white',
                                      font=('Arial', 30),
                                      borderwidth=1)
                self.changer1.place(y=100,
                                    x=int(self.x) - 400,
                                    width=250,
                                    height=50)
                self.changer2 = Text(self.root,
                                     bg='white',
                                     font=('Arial', 30),
                                     borderwidth=1)
                self.changer2.place(y=200,
                                    x=int(self.x) - 150,
                                    width=100,
                                    height=50)
                self.changer3 = Label(self.root,
                                      text='Version:',
                                      bg='white',
                                      font=('Arial', 30),
                                      borderwidth=1)
                self.changer3.place(y=200,
                                    x=int(self.x) - 400,
                                    width=250,
                                    height=50)
                self.csvbutton.destroy()
                self.csvbutton = Button(self.root,
                                        text='Export CSV',
                                        font=('Arial', 40),
                                        bg='green',
                                        borderwidth=5,
                                        command=self.csvpressed)
                self.csvbutton.place(x=int(self.x) / 2 + 50,
                                     y=int(self.y) - 100,
                                     width=int(self.y) - 230,
                                     height=100)
            elif a == 'SecretSanta':
                self.changer0 = Text(self.root,
                                     bg='white',
                                     font=('Arial', 30),
                                     borderwidth=1)
                self.changer0.place(y=100,
                                    x=int(self.x) - 150,
                                    width=100,
                                    height=50)
                self.changer1 = Label(self.root,
                                      text='Versuche:',
                                      bg='white',
                                      font=('Arial', 30),
                                      borderwidth=1)
                self.changer1.place(y=100,
                                    x=int(self.x) - 400,
                                    width=250,
                                    height=50)
                self.changer2 = Text(self.root,
                                     bg='white',
                                     font=('Arial', 30),
                                     borderwidth=1)
                self.changer2.place(y=200,
                                    x=int(self.x) - 150,
                                    width=100,
                                    height=50)
                self.changer3 = Label(self.root,
                                      text='Anzahl der Schüler:',
                                      bg='white',
                                      font=('Arial', 30),
                                      borderwidth=1)
                self.changer3.place(y=200,
                                    x=int(self.x) - 550,
                                    width=400,
                                    height=50)
                self.csvbutton.destroy()
                self.csvbutton = Button(self.root,
                                        text='Export CSV',
                                        font=('Arial', 40),
                                        bg='gray',
                                        borderwidth=5)
                self.csvbutton.place(x=int(self.x) / 2 + 50,
                                     y=int(self.y) - 100,
                                     width=int(self.y) - 230,
                                     height=100)
            elif a == 'Coins':
                self.changer0 = Text(self.root,
                                     bg='white',
                                     font=('Arial', 30),
                                     borderwidth=1)
                self.changer0.place(y=100,
                                    x=int(self.x) - 150,
                                    width=100,
                                    height=50)
                self.changer1 = Label(self.root,
                                      text='Versuche:',
                                      bg='white',
                                      font=('Arial', 30),
                                      borderwidth=1)
                self.changer1.place(y=100,
                                    x=int(self.x) - 400,
                                    width=250,
                                    height=50)
                self.csvbutton.destroy()
                self.csvbutton = Button(self.root,
                                        text='Export CSV',
                                        font=('Arial', 40),
                                        bg='gray',
                                        borderwidth=5)
                self.csvbutton.place(x=int(self.x) / 2 + 50,
                                     y=int(self.y) - 100,
                                     width=int(self.y) - 230,
                                     height=100)
            self.pressed = 1
        else:
            try:
                self.c = self.changer2.get('1.0', 'end-1c')
                self.changer3.destroy()
                self.changer2.destroy()
            except (AttributeError, TclError):
                z = 0
            try:
                self.b = self.changer0.get('1.0', 'end-1c')
                self.changer1.destroy()
                self.changer0.destroy()
            except (AttributeError, TclError):
                z = 0
            if self.b == '':
                self.b = 1
            else:
                self.b = int(self.b)
            if self.c == '':
                self.c = 1
            else:
                self.c = int(float(self.c))
            self.pressed = 0
Example #20
0
class App:
    def __init__(self):
        self.root = Tk()
        # self.root.overrideredirect(1)
        w = 300
        h = 40
        self.root.title("Ynov Apps")
        ws = self.root.winfo_screenwidth()  # width of the screen
        hs = self.root.winfo_screenheight()
        x = ws - w
        y = hs - h
        self.root.geometry('%dx%d+%d+%d' % (w, h, x, y - 70))
        self.root.resizable(False, False)
        self.root.iconbitmap(r'favicon.ico')

        self.frame = Frame(self.root,
                           width=w,
                           height=h,
                           borderwidth=2,
                           relief="flat")

        self.frame.pack_propagate(False)
        self.frame.pack()

        self.bConnect = Button(self.frame,
                               text="Connexion",
                               command=self.connect)

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

        self.lDisplay = Label(self.frame,
                              text="Connexion en cours ...",
                              relief="flat",
                              borderwidth=2)

        self.canvas = Canvas(self.frame,
                             width=80,
                             height=32,
                             relief="flat",
                             borderwidth="2")
        self.canvas.grid(column=1, row=0)
        self.green = ImageTk.PhotoImage(green)
        self.yellow = ImageTk.PhotoImage(yellow)
        self.red = ImageTk.PhotoImage(red)

        self.canvas.create_image(70, 20, image=self.red, tags="red")
        self.canvas.create_image(70,
                                 20,
                                 image=self.yellow,
                                 tags="yellow",
                                 state="hidden")
        self.canvas.create_image(70,
                                 20,
                                 image=self.green,
                                 tags="green",
                                 state="hidden")

    def connect(self):
        self.bConnect.destroy()
        self.lDisplay.grid(column=0, row=0, pady=5)
        self.canvas.itemconfigure("red", state="hidden")
        self.canvas.itemconfigure("yellow", state="normal")

        Thread(target=connect_vpn, daemon=True).start()
Example #21
0
class Frontend():
    def __init__(self,x,y,b):
        self.x=str(x)   #1600
        self.y=str(y)   #900
        self.pressed=0
        self.b=10
        self.c=30
        self.grapher=0
        self.graph=[0,0,0,0]
        self.root=b
    def startwindow(self):
       # self.root=Tk()
        a=str(self.x+'x'+self.y)
        self.root.title('Wahrscheinlichkeinten & Simulation')
        self.root.geometry(a)
        self.g=Label(self.root,bg='white')
        self.g.place(x=0,y=0,width=self.x,height=self.y)
       # self.g.bind('<1>',self.optioncanged)
        self.lst1 = ['Marriage','Atom','BubbleGum','House_of_Cards','Lotto','SecretSanta','Coins']
        self.var1 = StringVar(self.root)
        self.var1.set('Marriage')
        self.drop = OptionMenu(self.root,self.var1,*self.lst1)
        self.drop.config(font=('Arial',(30)),bg='white')
        self.drop['menu'].config(font=('calibri',(20)),bg='white')
        self.drop.pack(side=TOP)
        self.photo = PhotoImage(file='z1.gif')
        self.label = Label(image=self.photo,borderwidth=0)
        self.label.image = self.photo
        self.label.bind('<1>',self.MouseOneDown)
        self.label.place(y=0,x=int(self.x)-200)
        self.startbutton=Button(self.root,text='Start',font=('Arial',40),bg='#B4045F',borderwidth=5,command=self.startpressed)       
        self.startbutton.place(x=0,y=int(self.y)-100,width=int(self.y)-200,height=100)
        self.csvbutton=Button(self.root,text='Export CSV',font=('Arial',40),bg='green',borderwidth=5,command=self.csvpressed)     
        self.csvbutton.place(x=int(self.x)/2+50,y=int(self.y)-100,width=int(self.y)-230,height=100)
    def startpressed(self):
            if self.grapher==1:
                for x in range(len(self.graph)):
                    if self.graph[x]!=0:
                        self.graph[x].destroy()
                self.grapher=0
                self.root.update()
            a=self.var1.get()
            if self.pressed==1:
                try:
                    self.b=int(self.changer0.get('1.0','end-1c'))
                except (AttributeError,TclError,ValueError):
                    self.b=10
                try:
                    self.c=self.changer2.get('1.0','end-1c')
                except (AttributeError,TclError,ValueError):
                    self.c=1
            if a=='Marriage':
                self.run0=Marriage(self.b)
                self.run0.DEBUG=False
                self.run0.sim()
            elif a=='Atom':
                self.c=float(self.c)
                self.run1=Atom(self.c,self.b)
                self.run1.DEBUG=False
                self.run1.sim()
            elif a=='BubbleGum':
                self.run2=BubbleGum(self.b)
                self.run2.DEBUG=False
                self.run2.sim()
                self.grapher=1
                self.graph=[0,0]
                g=str(round(self.run2.getrel()[0],4))
                h=str(round(self.run2.getrel()[1],4))
                self.graph[0]=Label(self.root,bg='white',text='Durchschnitt Karten zu viel: '+g,font=('calibri',19))
                self.graph[0].place(x=10,y=450)
                self.graph[1]=Label(self.root,bg='white',text='Durchschnitt dass es passiert: '+h,font=('calibri',19))
                self.graph[1].place(x=10,y=500)
            elif a=='House_of_Cards':
                if self.c=='':
                    self.c=0
                else:
                    self.c=int(self.c)
                self.run3=House_of_Cards(self.b,self.c)
                self.run3.DEBUG=False
                self.run3.sim()
                self.grapher=1
                self.graph=[0]
                self.graph[0]=Label(self.root,bg='white',text=('Durchschnitt: '+str(round(self.run3.getrel(),4))),font=('calibri',19))
                self.graph[0].place(x=10,y=450)
            elif a=='Lotto':
                self.run4=Lotto(self.b)
                self.run4.DEBUG=False
                self.run4.sim()
                x=4
                y=1
                count=0
                self.graph=[0,0,0,0]
                self.grapher=1
                self.graph[0]=Label(self.root,bg='black')
                self.graph[0].place(x=10,width=10+(int(self.x)*0.8),height=1,y=int(self.y)-int(self.y)/4*0.5-350)
                self.graph[1]=Label(self.root,text='50%',bg='white',font=('calibri',10))
                self.graph[1].place(x=60+(int(self.x)*0.8),width=50,height=50,y=int(self.y)-int(self.y)/4*0.5-375)
                self.graph[2]=Label(self.root,bg='black')
                self.graph[2].place(x=10,width=20,height=1,y=int(self.y)-350)
                self.graph[3]=Label(self.root,bg='black')
                self.graph[3].place(x=10,width=20,height=1,y=int(self.y)-int(self.y)/4-350)
                for draw in self.run4.turns:
                    if draw.count(0) == 0:
                        count += 1
                    elif draw.count(1) == 0:
                        count += 1
                    elif draw.count(2) == 0:
                        count += 1
                    elif draw.count(3) == 0:
                        count += 1
                    elif draw.count(4) == 0:
                        count += 1
                    elif draw.count(5) == 0:
                        count += 1
                    self.graph+=[0]
                    self.graph[x]=Label(self.root,bg='red')
                    if str(self.c)=='1':
                        self.graph[x].place(x=int(10+(int(self.x)*0.8)*((y-1)/self.b)),width=int(1250/self.b),height=int(self.y)-350-(int(int(self.y)-int(self.y)/4*(count/y)-350)),y=int(int(self.y)-int(self.y)/4*(count/y)-350))
                    else:
                        self.graph[x].place(x=int(10+(int(self.x)*0.8)*(y/self.b)),width=3,height=3,y=int(int(self.y)-int(self.y)/4*(count/y)-350))
                    x+=1
                    y+=1
                    self.root.update()
            elif a=='SecretSanta':
                if self.c=='':
                    self.c=1
                else:
                    self.c=int(self.c)
                self.run5=SecretSanta(self.b,self.c)
                self.run5.DEBUG=False
                self.run5.sim()
                self.grapher=1
                self.graph=[0]
                self.graph[0]=Label(self.root,bg='white',text=('Durchschnitt: '+str(round(self.run5.getrel(),4))),font=('calibri',19))
                self.graph[0].place(x=10,y=450)
            elif a=='Coins':
                self.run6=Coins(self.b)
                self.run6.sim()
                self.grapher=1
                self.graph=[0,0]
                v=self.run6.geterg()
                vv=self.run6.getrel()
                self.graph[0]=Label(self.root,bg='white',text=('Statistik für www: '+str(v[0])+'    '+str(vv[0])),font=('calibri',19))
                self.graph[0].place(x=10,y=450)
                self.graph[1]=Label(self.root,bg='white',text=('Statistik für zwz:   '+str(v[1])+'    '+str(vv[1])),font=('calibri',19))
                self.graph[1].place(x=10,y=500)
    def csvpressed(self):
        a=self.var1.get()
        if a=='Marriage':
            self.run0.exportcsv('Marriage_Simulation.csv')
        elif a=='Atom':
            self.run1.exportCSV('Atom_Simulation.csv')
        elif a=='Lotto':
            self.run4.exportCSV('Lotto_Simulation.csv')
  #  def optioncanged(self,event):
  #          a=self.var1.get()
   #         if a=='Marriage':
    #            self.csvbutton.destroy()
     #           self.csvbutton=Button(self.root,text='Export CSV',font=('Arial',40),bg='green',borderwidth=5,command=self.csvpressed)     
          #      self.csvbutton.place(x=int(self.x)/2+50,y=int(self.y)-100,width=int(self.y)-230,height=100)
      #      elif a=='Atom':
       #         self.csvbutton.destroy()
        #        self.csvbutton=Button(self.root,text='Export CSV',font=('Arial',40),bg='green',borderwidth=5,command=self.csvpressed)     
         #       self.csvbutton.place(x=int(self.x)/2+50,y=int(self.y)-100,width=int(self.y)-230,height=100)
#            elif a=='BubbleGum':
 #               self.csvbutton.destroy()
  #              self.csvbutton=Button(self.root,text='Export CSV',font=('Arial',40),bg='gray',borderwidth=5)     
   #             self.csvbutton.place(x=int(self.x)/2+50,y=int(self.y)-100,width=int(self.y)-230,height=100)
    #        elif a=='House_of_Cards':
     #           self.csvbutton.destroy()
      #          self.csvbutton=Button(self.root,text='Export CSV',font=('Arial',40),bg='gray',borderwidth=5)     
       #         self.csvbutton.place(x=int(self.x)/2+50,y=int(self.y)-100,width=int(self.y)-230,height=100)
        #    elif a=='Lotto':
         #       self.csvbutton.destroy()
          #      self.csvbutton=Button(self.root,text='Export CSV',font=('Arial',40),bg='green',borderwidth=5,command=self.csvpressed)     
           #     self.csvbutton.place(x=int(self.x)/2+50,y=int(self.y)-100,width=int(self.y)-230,height=100)
            #elif a=='SecretSanta':
   #             self.csvbutton.destroy()
    #            self.csvbutton=Button(self.root,text='Export CSV',font=('Arial',40),bg='gray',borderwidth=5)     
     #           self.csvbutton.place(x=int(self.x)/2+50,y=int(self.y)-100,width=int(self.y)-230,height=100)
    def MouseOneDown(self,event):
        if self.pressed==0:
            a=self.var1.get()
            if a=='Marriage':
                self.changer0=Text(self.root,bg='white',font=('Arial',30),borderwidth=1)
                self.changer0.place(y=100,x=int(self.x)-150,width=100,height=50)
                self.changer1=Label(self.root,text='Versuche:',bg='white',font=('Arial',30),borderwidth=1)
                self.changer1.place(y=100,x=int(self.x)-400,width=250,height=50)
                self.csvbutton.destroy()
                self.csvbutton=Button(self.root,text='Export CSV',font=('Arial',40),bg='green',borderwidth=5,command=self.csvpressed)     
                self.csvbutton.place(x=int(self.x)/2+50,y=int(self.y)-100,width=int(self.y)-230,height=100)
            elif a=='Atom':
                self.changer0=Text(self.root,bg='white',font=('Arial',30),borderwidth=1)
                self.changer0.place(y=100,x=int(self.x)-150,width=100,height=50)
                self.changer1=Label(self.root,text='Anzahl der Atome:',bg='white',font=('Arial',30),borderwidth=1)
                self.changer1.place(y=100,x=int(self.x)-600,width=450,height=50)
                self.changer2=Text(self.root,bg='white',font=('Arial',30),borderwidth=1)
                self.changer2.place(y=200,x=int(self.x)-150,width=100,height=50)
                self.changer3=Label(self.root,text='Zerfallswahrscheinlichkeit:',bg='white',font=('Arial',30),borderwidth=1)
                self.changer3.place(y=200,x=int(self.x)-650,width=500,height=50)
                self.csvbutton.destroy()
                self.csvbutton=Button(self.root,text='Export CSV',font=('Arial',40),bg='green',borderwidth=5,command=self.csvpressed)     
                self.csvbutton.place(x=int(self.x)/2+50,y=int(self.y)-100,width=int(self.y)-230,height=100)
            elif a=='BubbleGum':
                self.changer0=Text(self.root,bg='white',font=('Arial',30),borderwidth=1)
                self.changer0.place(y=100,x=int(self.x)-150,width=100,height=50)
                self.changer1=Label(self.root,text='Versuche:',bg='white',font=('Arial',30),borderwidth=1)
                self.changer1.place(y=100,x=int(self.x)-400,width=250,height=50)
                self.csvbutton.destroy()
                self.csvbutton=Button(self.root,text='Export CSV',font=('Arial',40),bg='gray',borderwidth=5)     
                self.csvbutton.place(x=int(self.x)/2+50,y=int(self.y)-100,width=int(self.y)-230,height=100)
            elif a=='House_of_Cards':
                self.changer0=Text(self.root,bg='white',font=('Arial',30),borderwidth=1)
                self.changer0.place(y=100,x=int(self.x)-150,width=100,height=50)
                self.changer1=Label(self.root,text='Versuche:',bg='white',font=('Arial',30),borderwidth=1)
                self.changer1.place(y=100,x=int(self.x)-400,width=250,height=50)
                self.changer2=Text(self.root,bg='white',font=('Arial',30),borderwidth=1)
                self.changer2.place(y=200,x=int(self.x)-150,width=100,height=50)
                self.changer3=Label(self.root,text='Kartenanzahl(32,55):',bg='white',font=('Arial',30),borderwidth=1)
                self.changer3.place(y=200,x=int(self.x)-620,width=450,height=50)
                self.csvbutton.destroy()
                self.csvbutton=Button(self.root,text='Export CSV',font=('Arial',40),bg='gray',borderwidth=5)     
                self.csvbutton.place(x=int(self.x)/2+50,y=int(self.y)-100,width=int(self.y)-230,height=100)
            elif a=='Lotto':
                self.changer0=Text(self.root,bg='white',font=('Arial',30),borderwidth=1)
                self.changer0.place(y=100,x=int(self.x)-150,width=100,height=50)
                self.changer1=Label(self.root,text='Versuche:',bg='white',font=('Arial',30),borderwidth=1)
                self.changer1.place(y=100,x=int(self.x)-400,width=250,height=50)
                self.changer2=Text(self.root,bg='white',font=('Arial',30),borderwidth=1)
                self.changer2.place(y=200,x=int(self.x)-150,width=100,height=50)
                self.changer3=Label(self.root,text='Version:',bg='white',font=('Arial',30),borderwidth=1)
                self.changer3.place(y=200,x=int(self.x)-400,width=250,height=50)
                self.csvbutton.destroy()
                self.csvbutton=Button(self.root,text='Export CSV',font=('Arial',40),bg='green',borderwidth=5,command=self.csvpressed)     
                self.csvbutton.place(x=int(self.x)/2+50,y=int(self.y)-100,width=int(self.y)-230,height=100)
            elif a=='SecretSanta':
                self.changer0=Text(self.root,bg='white',font=('Arial',30),borderwidth=1)
                self.changer0.place(y=100,x=int(self.x)-150,width=100,height=50)
                self.changer1=Label(self.root,text='Versuche:',bg='white',font=('Arial',30),borderwidth=1)
                self.changer1.place(y=100,x=int(self.x)-400,width=250,height=50)
                self.changer2=Text(self.root,bg='white',font=('Arial',30),borderwidth=1)
                self.changer2.place(y=200,x=int(self.x)-150,width=100,height=50)
                self.changer3=Label(self.root,text='Anzahl der Schüler:',bg='white',font=('Arial',30),borderwidth=1)
                self.changer3.place(y=200,x=int(self.x)-550,width=400,height=50)
                self.csvbutton.destroy()
                self.csvbutton=Button(self.root,text='Export CSV',font=('Arial',40),bg='gray',borderwidth=5)     
                self.csvbutton.place(x=int(self.x)/2+50,y=int(self.y)-100,width=int(self.y)-230,height=100)
            elif a=='Coins':
                self.changer0=Text(self.root,bg='white',font=('Arial',30),borderwidth=1)
                self.changer0.place(y=100,x=int(self.x)-150,width=100,height=50)
                self.changer1=Label(self.root,text='Versuche:',bg='white',font=('Arial',30),borderwidth=1)
                self.changer1.place(y=100,x=int(self.x)-400,width=250,height=50)
                self.csvbutton.destroy()
                self.csvbutton=Button(self.root,text='Export CSV',font=('Arial',40),bg='gray',borderwidth=5)     
                self.csvbutton.place(x=int(self.x)/2+50,y=int(self.y)-100,width=int(self.y)-230,height=100)
            self.pressed=1
        else:
            try:
                self.c=self.changer2.get('1.0','end-1c')
                self.changer3.destroy()
                self.changer2.destroy()
            except (AttributeError,TclError):
                    z=0
            try:
                self.b=self.changer0.get('1.0','end-1c')
                self.changer1.destroy()
                self.changer0.destroy()
            except (AttributeError,TclError):
                    z=0
            if self.b=='':
                self.b=1
            else:
                self.b=int(self.b)
            if self.c=='':
                self.c=1
            else:
                self.c=int(float(self.c))
            self.pressed=0
Example #22
0
class MyServer:
    def __init__(self):
        self.__ini_data()
        print('Data prepared...')
        # self.__ini_socket()
        self.__ini_widget()

        self.__exit()

    def __ini_widget(self):
        self.root_window = Tk()
        self.root_window.title('Server')

        # pre connection settings widgets group
        frame_address = Frame(self.root_window)
        frame_address.pack(side=TOP, fill=X, padx=5, pady=5)
        label_ip = Label(frame_address, text='IP')
        label_ip.grid(row=0, sticky=EW)
        self.ip_text = StringVar()
        self.ip_text.set(self.HOST)
        self.ip_texter = Entry(frame_address, textvariable=self.ip_text, width=30)
        self.ip_texter.grid(row=0, column=1, sticky=EW)
        label_port = Label(frame_address, text='Port')
        label_port.grid(row=1, sticky=EW)
        self.port_text = StringVar()
        self.port_text.set(self.PORT)
        self.port_texter = Entry(frame_address, textvariable=self.port_text)
        self.port_texter.grid(row=1, column=1, sticky=EW)
        self.btn_open = Button(frame_address, text='Open Port', command=self.__open_port)
        self.btn_open.grid(row=2, columnspan=2, sticky=NSEW)

        # talk widgets group
        self.frame_talk = Frame(self.root_window)

        self.c_info = Label(self.frame_talk, text='Client info - -\nWating for connection')
        self.c_info.pack(side=TOP, fill=X)

        self.list_box_data = Listbox(self.frame_talk)
        self.list_box_data.pack(expand=True, fill=BOTH)

        self.c_text = Label(self.frame_talk, text="Client's message")
        self.c_text.pack(side=TOP, fill=X)

        self.frame_server_input = Frame(self.frame_talk)
        self.frame_server_input.pack(fill=X)
        self.s_text = StringVar()
        self.s_texter = Entry(self.frame_server_input, textvariable=self.s_text)
        self.s_texter.bind("<Key>", self.on_texter_key)
        self.s_texter.pack(side=LEFT, fill=X, expand=True)
        btn_send = Button(self.frame_server_input, text='Send', command=self.on_click_btn_send, width=15)
        btn_send.pack(side=RIGHT)

        # btn exit
        btn_exit = Button(self.root_window, text='Exit', command=self.on_btn_exit)
        btn_exit.pack(side=BOTTOM, fill=X, padx=5, pady=5)

        # open window
        self.root_window.mainloop()

    def __exit(self):
        if self.INI_SERVER:
            self.server.close()

        print('Byebye')
        # if self.CONN:
        #     self.client.close()

    def __start_listen(self):
        print('Start listen')
        try:
            self.client, self.c_add = self.server.accept()
            t_conn_establish = datetime.datetime.now()
            print('Connection established')
            self.c_info['text'] = 'Client info: host = %s , port = %d\nConnected at %s' % (
                self.c_add[0], self.c_add[1], t_conn_establish.strftime('%Y-%m-%d %H:%M:%S'))
            self.INI_CLIENT = True
            # self.CONN = True
            self.root_window.update()
            while True:
                try:
                    c_data = json.loads(self.client.recv(1024).decode('utf8'))
                    if c_data['release']:  # 放在后面会卡死
                        # self.CONN = False
                        break
                    print('%s\nClient:%s' % (c_data['s_time'], c_data['msg']))
                    self.c_text['text'] = c_data['msg']

                    self.list_box_data.insert(END, 'Client %s :' % (c_data['s_time']))
                    self.list_box_data.insert(END, ' %s' % (c_data['msg']))
                    self.list_box_data.see(END)

                    self.root_window.update()
                except Exception as e:
                    traceback.print_exc()
            if not self.EXIT:
                self.c_info['text'] = 'Connection released'
                self.frame_server_input.destroy()
                self.c_text['text'] = "Client is offline"

        except OSError as e:
            traceback.print_exc()
            pass

    def on_click_btn_send(self):
        try:
            self.s_data['msg'] = self.s_text.get()
            self.s_data['s_time'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            self.client.send(json.dumps(self.s_data).encode('utf-8'))
            self.s_text.set('')
            self.list_box_data.insert(END, 'Server %s :' % (self.s_data['s_time']))
            self.list_box_data.insert(END, ' %s' % (self.s_data['msg']))
            self.list_box_data.see(END)
        except Exception as e:
            traceback.print_exc()

    def on_texter_key(self, event):
        if event.keysym == 'Return':
            # 按下了回车
            self.on_click_btn_send()

    def __open_port(self):
        self.btn_open.destroy()
        self.frame_talk.pack(expand=True, fill=BOTH)

        self.HOST = self.ip_text.get()
        self.PORT = int(self.port_text.get())
        self.server.bind((self.HOST, self.PORT))
        self.INI_SERVER = True

        print('Server socket bind successfully\nListening...')

        self.c_info['text'] = "Waiting for client's connection"
        self.server.listen(3)
        self.root_window.update()

        self.thread_listen = threading.Thread(target=self.__start_listen)
        self.thread_listen.start()

    def on_btn_exit(self):
        self.EXIT=True
        self.frame_server_input.destroy()
        self.c_text['text'] = "Waiting for client's exit"
        if self.INI_SERVER and not self.INI_CLIENT:
            self.server.close()
        if self.INI_CLIENT:
            self.s_data['release'] = True
            self.client.send(json.dumps(self.s_data).encode('utf-8'))
            print('Exit signal sent...')
            # self.client.close()
            self.root_window.update()
            self.thread_listen.join()
        self.root_window.destroy()

    def __ini_data(self):
        self.INI_SERVER = False
        self.INI_CLIENT = False
        # self.CONN=False
        self.EXIT=False

        self.HOST = '127.0.0.1'
        # self.HOST = '192.168.1.101'
        self.PORT = 54321

        self.s_data = {'msg': '', 'release': False, 's_time': ''}

        self.server = socket.socket()
Example #23
0
class Example(Frame):
  
    def __init__(self, parent):
        Frame.__init__(self, parent)   
         
        self.parent = parent
        self.initUI()

        
    def initUI(self):
      
        self.parent.title("EGUANA")
        self.style = ttk.Style()        
        self.style.theme_use("alt")        
        
        self.photoName = "eguana.gif"
        self.frame = Frame(self, relief=FLAT, borderwidth=10,bg='#FADC46')

        self.frame.pack(fill=BOTH, expand=True)        
        self.pack(fill=BOTH, expand=True)
        
        self.setupMenuBar()
        self.setupTopBar()  
        
    def setupMenuBar(self):
        
        self.menubar = EguanaMenu(self.parent,self)
        self.parent.config(menu=self.menubar)

    def setupTopBar(self):
        
        self.openButton3D = Button(self.frame,text="Select Directory for 3D EMA",relief=RAISED,command=self.askDirectory)
        self.openButton3D.grid(row=0,column=0, sticky=N+S+E+W,padx=2,pady =2)
        
        self.openButton2D = Button(self.frame,text="Select Directory for 2D EMA",relief=RAISED,command=self.askDirectory);
        self.openButton2D.grid(row=2,column=2, sticky=N+S+E+W,padx=2,pady =2)

        self.p1Button = Button(self.frame,text="Placeholder",relief=RAISED)
        self.p1Button.grid(row=0,column=1, sticky=N+S+E+W,padx=2,pady =2)
        self.p2Button = Button(self.frame,text="Placeholder",relief=RAISED)
        self.p2Button.grid(row=0,column=2, sticky=N+S+E+W,padx=2,pady =2)
        self.p3Button = Button(self.frame,text="Placeholder",relief=RAISED)
        self.p3Button.grid(row=1,column=0, sticky=N+S+E+W,padx=2,pady =2)
        self.p4Button = Button(self.frame,text="Placeholder",relief=RAISED)
        self.p4Button.grid(row=1,column=2, sticky=N+S+E+W,padx=2,pady =2)
        self.p5Button = Button(self.frame,text="Placeholder",relief=RAISED)
        self.p5Button.grid(row=2,column=0, sticky=N+S+E+W,padx=2,pady =2)
        self.p6Button = Button(self.frame,text="Placeholder",relief=RAISED)
        self.p6Button.grid(row=2,column=1, sticky=N+S+E+W,padx=2,pady =2)

        self.openButton3D.bind('<Motion>',self.cursorPosition)
        self.openButton2D.bind('<Motion>',self.cursorPosition)

        self.photo = PhotoImage(file="eguana.gif")
        self.photo = self.photo.subsample(2);
        self.photo_label = Label(self.frame,image=self.photo,borderwidth=0,highlightthickness=0)
        self.photo_label.configure(bg='#FADC46')
        
        self.photo_label.grid(row=1,column=1, sticky=N+S+E+W,padx=2,pady =2)
        
        self.photo_label.image = self.photo
    
    
        self.frame.columnconfigure(0, weight=1)
        self.frame.columnconfigure(1, weight=1)
        self.frame.columnconfigure(2, weight=1)
        self.frame.rowconfigure(0, weight=1)
        self.frame.rowconfigure(1, weight=1)
        self.frame.rowconfigure(2, weight=1)
        
    def askDirectory(self):

        dirStr = filedialog.askdirectory()
        
        if len(dirStr):
            self.openButton3D.destroy()
            self.openButton2D.destroy()
            self.p1Button.destroy()
            self.p2Button.destroy()
            self.p3Button.destroy()
            self.p4Button.destroy()
            self.p5Button.destroy()
            self.p6Button.destroy()

            self.menubar.entryconfigure('Filter', state = 'active')
            self.photo_label.destroy()

            dirStr = 'Input Path : '+dirStr
            
            
            self.frame.grid_forget()
            
           

            self.infoFrame = Frame(self.frame, relief=FLAT, bg='#FADC46')
            self.infoFrame.grid(row=0,column=0,columnspan=3, sticky=N+S+E+W,padx=2,pady =2)
               
        
            self.directoryLabel = Label(self.infoFrame, text="No project currently selected",relief=FLAT)
            self.directoryLabel.grid(row=0,column=0,columnspan=2, sticky=N+S+E+W,padx=2,pady =2)
            self.directoryLabel.config(text=dirStr)
            
        
            self.outputDirButton = Button(self.infoFrame,text="No output directory selected. Click to select an output directory ",relief=RAISED,fg='red',command=self.askOutputDirectory)
            self.outputDirButton.grid(row=1,column=0,columnspan=2, sticky=N+S+E+W,padx=2,pady =2)
            
            
            self.filterButton = Button(self.infoFrame,text="No filter selected. Click to select a filter",relief=RAISED,fg='red',command=self.selectFilter)
            self.filterButton.grid(row=2,column=0,columnspan=2, sticky=N+S+E+W,padx=2,pady =2)
           
           
            self.trialLabel = Label(self.infoFrame,text="Trial Number",relief=FLAT,justify=RIGHT,anchor=E)
            self.trialLabel.grid(row=3,column=0, sticky=N+S+E+W,padx=2,pady =2)


            vcmd = (self.master.register(self.validate),'%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W')
            self.trialEntry = Entry(self.infoFrame,validate = 'key', validatecommand = vcmd)
            self.trialEntry.grid(row=3,column=1, sticky=N+S+E+W,padx=2,pady =2)

            self.infoFrame.columnconfigure(0, weight=1)
            self.infoFrame.columnconfigure(1, weight=1)
            self.infoFrame.rowconfigure(0, weight=1)
            self.infoFrame.rowconfigure(1, weight=1)
            self.infoFrame.rowconfigure(2, weight=1)
            self.infoFrame.rowconfigure(3, weight=1)

            self.showPlotTools()

    def validate(self, action, index, value_if_allowed,
                       prior_value, text, validation_type, trigger_type, widget_name):
                           
        if len(value_if_allowed)==0 : 
            return True
        
        if text in '0123456789.-+ ':
            try:
                float(value_if_allowed)
                return True
            except ValueError:
                return False
        else:
            return False
            
    def askOutputDirectory(self):
        dirStr = filedialog.askdirectory()
        if len(dirStr):
            dirStr = 'Output Path : '+dirStr
            self.outputDirButton.destroy()
            self.outputDirLabel = Label(self.infoFrame, relief=FLAT)
            self.outputDirLabel.grid(row=1,column=0,columnspan=2, sticky=N+S+E+W,padx=2,pady =2)
            self.outputDirLabel.config(text=dirStr)

            

    def showPlotTools(self):        
        
        f2= Frame(self.frame, relief=FLAT,bg='#FADC46')
        f2.grid(row=1,column=0,rowspan=2,columnspan=3,sticky=N+S+E+W,padx=10,pady =10)
        
        b1 = Button(f2,text='3D K',relief=RAISED,command= lambda:self.plotButtonPressed(1))
        b1.grid(row=0, column=0,sticky=N+S+E+W,padx=5,pady =5)
        
        b2 = Button(f2,text='3D Dist',relief=RAISED,command=lambda:self.plotButtonPressed(2))
        b2.grid(row=0, column=1,sticky=N+S+E+W,padx=5,pady =5)
        
        b3 = Button(f2,text='3D DP',relief=RAISED,command=lambda:self.plotButtonPressed(3))
        b3.grid(row=0, column=2,sticky=N+S+E+W,padx=5,pady =5)
        
        b4 = Button(f2,text='2D K',relief=RAISED,command=lambda:self.plotButtonPressed(4))
        b4.grid(row=1, column=0,sticky=N+S+E+W,padx=5,pady =5)

        b5 = Button(f2,text='2D Dist',relief=RAISED,command=lambda:self.plotButtonPressed(5))
        b5.grid(row=1, column=1,sticky=N+S+E+W,padx=5,pady =5)

        b6 = Button(f2,text='2D DP',relief=RAISED,command=lambda:self.plotButtonPressed(6))
        b6.grid(row=1, column=2,sticky=N+S+E+W,padx=5,pady =5)
        
        f2.columnconfigure(0, weight=1)
        f2.columnconfigure(1, weight=1)
        f2.columnconfigure(2, weight=1)

        f2.rowconfigure(0, weight=1)
        f2.rowconfigure(1, weight=1)
       
       
    def plotButtonPressed(self,number):
        trialNum = self.trialEntry.get()
        
        try:
            trialNum = float(trialNum)
            
            
            if trialNum < 16 and trialNum > 0:
                self.plotFigure(number)
                return True             
            else:
                messagebox.showerror(
                    "Trial Number Error",
                    "The trial number is out of range"
                    )     
                return False
        except ValueError:
            messagebox.showerror(
                "Trial Number Error",
                "Error with the trial number"
            )  
            return False
            
    def plotFigure(self,number):
        m =  CoilNumDialog(self.frame)
        if m.isSet():
            print(m.getValues())
        
    def selectFilter(self):        
        self.top = FilterPopup(self);

    def speech3DButtonPressed(self):
        self.menubar.filterSelected(0)
        self.top.destroy()
        if hasattr(self, 'filterLabel'):
            self.filterLabel.config(text="Filter : speech3D")
        else:
            self.filterLabel = Label(self.infoFrame, text="Filter : speech3D",relief=FLAT)
            self.filterLabel.grid(row=2,column=0,columnspan=2, sticky=N+S+E+W,padx=2,pady =2)
            self.filterButton.destroy()
    
    def speech2DButtonPressed(self):
        self.menubar.filterSelected(1)
        self.top.destroy()
        if hasattr(self, 'filterLabel'):
            self.filterLabel.config(text="Filter : speech2D")
        else:
            self.filterLabel = Label(self.infoFrame, text="Filter : speech2D ",relief=FLAT)
            self.filterLabel.grid(row=2,column=0,columnspan=2, sticky=N+S+E+W,padx=2,pady =2)
            self.filterButton.destroy()
    
    def swallow3DButtonPressed(self):
        self.menubar.filterSelected(2)
        self.top.destroy()
        if hasattr(self, 'filterLabel'):
            self.filterLabel.config(text="Filter : swallow3D")
        else:
            self.filterLabel = Label(self.infoFrame, text="Filter : swallow3D ",relief=FLAT)
            self.filterLabel.grid(row=2,column=0,columnspan=2, sticky=N+S+E+W,padx=2,pady =2)
            self.filterButton.destroy()
    
    def swallow2DButtonPressed(self):
        self.menubar.filterSelected(3)
        self.top.destroy()
        if hasattr(self, 'filterLabel'):
            self.filterLabel.config(text="Filter : swallow2D")
        else:
            self.filterLabel = Label(self.infoFrame, text="Filter : swallow2D ",relief=FLAT)
            self.filterLabel.grid(row=2,column=0,columnspan=2, sticky=N+S+E+W,padx=2,pady =2)
            self.filterButton.destroy()

    def changeImage(self):
        self.photo = PhotoImage(file=self.photoName)
        self.photo = self.photo.subsample(2);
        self.photo_label.image = self.photo  
        self.photo_label.config(image=self.photo)
        
        
        
    def cursorPosition(self,event):       
        if event.widget ==  self.openButton3D:
            if self.photoName == "eguana2.gif":
                self.photoName = "eguana.gif"
                self.changeImage()
                
        elif event.widget ==  self.openButton2D:
            if self.photoName == "eguana.gif":
                self.photoName = "eguana2.gif"
                self.changeImage()
Example #24
0
class GameUI(StartUI):
    def __init__(self, master):
        self.master = master
        self.canvas = Canvas(master, width=WIDTH, height=HEIGHT, bg="white")
        self.canvas.pack(fill=BOTH, side=TOP)

        # Buttons
        self.check_mode = False
        self.check_button = Button(master,
                                   text="Check",
                                   fg='green',
                                   command=self.check_sudoku)
        self.check_button.pack(side=RIGHT)
        self.solve_button = Button(master,
                                   text="Solve",
                                   fg='blue',
                                   command=self.draw_solution)
        self.solve_button.pack(side=RIGHT)
        self.hint_button = Button(master,
                                  text="Hint",
                                  fg='purple',
                                  command=self.give_hint)
        self.hint_button.pack(side=LEFT)

        # Get a sudoku and its solution.
        self.original_sudoku = sudoku_solver.randomized_sudoku(
            number_of_removed_cells)  # Original
        self.user_sudoku = deepcopy(self.original_sudoku)  # User will change
        self.sudoku_solution = sudoku_solver.solve_sudoku(
            deepcopy(self.user_sudoku))  # Solution of the sudoku

        self.canvas.bind("<Button-1>", self.canvas_click)
        self.canvas.bind("<Key>", self.canvas_key)

        # Start some variables
        self.row, self.column = 0, 0
        self.start_time = time.time()

        # Set up the clock
        self.clock = Label(master)
        self.clock.pack(side=BOTTOM)
        self.__draw_clock()

        self.__draw_sudoku()

    def __draw_grid(self):
        """
        Draws grid divided with blue lines into 3x3 squares
        """
        for i in range(10):
            color = "black" if i % 3 == 0 else "gray"

            x0 = MARGIN + i * SIDE
            y0 = MARGIN
            x1 = MARGIN + i * SIDE
            y1 = HEIGHT - MARGIN
            self.canvas.create_line(x0, y0, x1, y1, fill=color)

            x0 = MARGIN
            y0 = MARGIN + i * SIDE
            x1 = WIDTH - MARGIN
            y1 = MARGIN + i * SIDE
            self.canvas.create_line(x0, y0, x1, y1, fill=color)

    def __draw_numbers(self):
        """
        Fills the grid with sudoku numbers
        """
        self.canvas.delete("numbers")
        for i in range(9):
            for j in range(9):
                number = self.user_sudoku[i][j]
                if number != 0:
                    if number == self.original_sudoku[i][j]:
                        color = "black"
                    # Highlight numbers that are wrong
                    elif self.check_mode and \
                            number != self.sudoku_solution[i][j]:
                        color = "red"
                    else:
                        color = "blue"

                    x = MARGIN + SIDE / 2 + i * SIDE
                    y = MARGIN + SIDE / 2 + j * SIDE
                    self.canvas.create_text(x,
                                            y,
                                            text=number,
                                            tags="numbers",
                                            fill=color)

    def canvas_click(self, event):
        '''
        Selects which cell has been clicked
        '''
        x, y = event.x, event.y
        if WIDTH - MARGIN > x > MARGIN and HEIGHT - MARGIN > y > MARGIN:
            self.canvas.focus_set()

            row = (x - MARGIN) // SIDE
            column = (y - MARGIN) // SIDE

            if (row, column) == (self.row, self.column):
                (self.row, self.column) = (-1, -1)
            elif self.original_sudoku[row][column] == 0:
                self.row, self.column = row, column

        self.__draw_red_box()

    def __draw_red_box(self):
        '''
        Draw red box around the cell selected
        '''
        self.canvas.delete("red_square")
        if self.row >= 0 and self.column >= 0:
            x0 = MARGIN + self.row * SIDE + 1
            y0 = MARGIN + self.column * SIDE + 1
            x1 = MARGIN + (self.row + 1) * SIDE - 1
            y1 = MARGIN + (self.column + 1) * SIDE - 1
            self.canvas.create_rectangle(x0,
                                         y0,
                                         x1,
                                         y1,
                                         outline="red",
                                         tags="red_square")

    def canvas_key(self, event):
        '''
        Selects which key has been pressed
        '''
        number = event.char
        if number in "1234567890" and self.row >= 0 and self.column >= 0:
            self.user_sudoku[self.row][self.column] = int(number)
            self.__draw_sudoku()

    def __draw_sudoku(self):
        self.__draw_grid()
        self.__draw_numbers()
        self.__draw_red_box()
        if self.is_sudoku_solved():
            self.__draw_victory()

    def draw_solution(self):
        '''
        Solve the sudoku and draw it
        '''
        self.user_sudoku = self.sudoku_solution
        self.__draw_sudoku()

    def give_hint(self):
        '''
        Gives the solution for a random cell
        '''
        while True:
            i = np.random.randint(0, 9)
            j = np.random.randint(0, 9)
            if self.user_sudoku[i][j] == 0:
                self.user_sudoku[i][j] = self.sudoku_solution[i][j]
                print('Hint for cell: ', i, ',', j)
                self.__draw_sudoku()
                return

    def check_sudoku(self):
        self.check_mode = True
        self.__draw_numbers()
        self.check_mode = False

    def is_sudoku_solved(self):
        for i in range(9):
            for j in range(9):
                number = self.user_sudoku[i][j]
                if number != self.sudoku_solution[i][j]:
                    return False
        return True

    def __draw_clock(self):

        game_time = time.time() - self.start_time
        min = game_time // 60
        sec = game_time % 60
        t = "%02d:%02d" % (min, sec)
        self.clock.config(text=t)
        # Call this function to update the clock every 200 ms
        if not (self.is_sudoku_solved()):
            self.clock.after(200, self.__draw_clock)

    def __draw_victory(self):
        # create a oval (which will be a circle)
        x0 = y0 = MARGIN + SIDE * 2
        x1 = y1 = MARGIN + SIDE * 7
        self.canvas.create_oval(x0,
                                y0,
                                x1,
                                y1,
                                tags="victory",
                                fill="dark blue",
                                outline="blue")
        # create text
        x = y = MARGIN + 4 * SIDE + SIDE / 2
        self.canvas.create_text(x,
                                y,
                                text="Congrats!",
                                tags="winner",
                                fill="white",
                                font=("Arial", 32))
        self.check_button.destroy()
        self.hint_button.destroy()
        self.solve_button.destroy()

        self.start_button = Button(self.master,
                                   text="Restart",
                                   fg='purple',
                                   command=self.start_game)
        self.start_button.pack(side=BOTTOM)
Example #25
0
class MainEngine(object):
    def __init__(self):
        ## get option parameters from an external option file
        # set a directory for the resource file
        pathCurrentDir = os.path.dirname(__file__)  # current script directory
        pathRelDir = "resource/options.txt"
        pathAbsDir = os.path.join(pathCurrentDir, pathRelDir)
        optionFile = open(pathAbsDir, encoding="utf-8")

        # lists for difficulty parameters from the property
        self.optionDiffCount = []
        self.optionDiffTime = []
        self.optionWidgetCoordinate = []

        # find the option parameters and bind to lists
        # these will bind the important parameter only as integer by using slicing
        for optionLine in optionFile.readlines():
            if "DiffCountEasy:" in optionLine:
                self.optionDiffCount.append(int(optionLine[15:-1]))
            elif "DiffCountNorm:" in optionLine:
                self.optionDiffCount.append(int(optionLine[15:-1]))
            elif "DiffCountHard:" in optionLine:
                self.optionDiffCount.append(int(optionLine[15:-1]))
            elif "DiffTimeEasy:" in optionLine:
                self.optionDiffTime.append(int(optionLine[14:-1]))
            elif "DiffTimeNorm:" in optionLine:
                self.optionDiffTime.append(int(optionLine[14:-1]))
            elif "DiffTimeHard:" in optionLine:
                self.optionDiffTime.append(int(optionLine[14:-1]))
            elif "UILabelScoreX:" in optionLine:  # index 0
                self.optionWidgetCoordinate.append(int(optionLine[15:-1]))
            elif "UILabelScoreY:" in optionLine:  # index 1
                self.optionWidgetCoordinate.append(int(optionLine[15:-1]))
            elif "UILabelLifeX:" in optionLine:  # index 2
                self.optionWidgetCoordinate.append(int(optionLine[14:-1]))
            elif "UILabelLifeY:" in optionLine:  # index 3
                self.optionWidgetCoordinate.append(int(optionLine[14:-1]))
            elif "UILabelLineTopX:" in optionLine:  # index 4
                self.optionWidgetCoordinate.append(int(optionLine[17:-1]))
            elif "UILabelLineTopY:" in optionLine:  # index 5
                self.optionWidgetCoordinate.append(int(optionLine[17:-1]))
            elif "UILabelLineBotX:" in optionLine:  # index 6
                self.optionWidgetCoordinate.append(int(optionLine[17:-1]))
            elif "UILabelLineBotY:" in optionLine:  # index 7
                self.optionWidgetCoordinate.append(int(optionLine[17:-1]))
            elif "UIinputTxtBoxX:" in optionLine:  # index 8
                self.optionWidgetCoordinate.append(int(optionLine[16:-1]))
            elif "UIinputTxtBoxY:" in optionLine:  # index 9
                self.optionWidgetCoordinate.append(int(optionLine[16:-1]))

        # initialize tkinter window parameters
        self.root = Tk()
        self.root.title("Acid Rain")
        self.root.geometry("640x480")
        self.root.resizable(0, 0)

        # initialize some engine variables
        self.radioVar = IntVar()  # for difficulty option feature
        self.diffCount = self.optionDiffCount[0]  # default: easy
        self.diffTime = self.optionDiffTime[0]  # default: easy
        self.statusGame = False
        self.statusScore = 0
        self.statusLife = 10
        self.wordCreateLimit = 2

        # call the third phase of initialization
        self.initSecond()

    # 2nd phase of initialization: create widgets
    def initSecond(self):
        ## initialize widgets for difficulty selection
        self.diffLabel = Label(self.root, text="Select the difficulty.")

        # difficulty select options with radiobuttons
        # function difficultySelection will be called if the player hit the diffBtn
        self.radioBtn1 = Radiobutton(text="Easy",
                                     variable=self.radioVar,
                                     value=1)
        self.radioBtn2 = Radiobutton(text="Normal",
                                     variable=self.radioVar,
                                     value=2)
        self.radioBtn3 = Radiobutton(text="Hard",
                                     variable=self.radioVar,
                                     value=3)
        self.diffBtn = Button(self.root,
                              text="Select",
                              command=self.difficultySelection,
                              width=5,
                              height=1)

        ## initialize widgets for the game
        self.labelScore = Label(self.root,
                                text=("Score: " + str(self.statusScore)))
        self.labelLife = Label(self.root,
                               text=("Life: " + str(self.statusLife)))
        self.labelLineTop = Label(self.root, text="- " * 68)
        self.labelLineBot = Label(self.root, text="- " * 68)
        self.inputEntry = Entry(self.root)
        self.labelBlockList = [
            Label(self.root, text='') for i in range(self.optionDiffCount[2])
        ]

        # inputResponse will be called if the player hit <Return> key
        self.root.bind('<Return>', self.inputResponse)
        self.root.bind('<Escape>', self.inputResponseEscape)

        # call the third phase of initialization
        self.initThird()

    # 3rd phase of initialization: difficulty selection
    def initThird(self):
        ## difficulty selection, showing all relevant widgets
        self.diffLabel.pack()
        self.radioBtn1.pack()
        self.radioBtn2.pack()
        self.radioBtn3.pack()
        self.diffBtn.pack()

        # execute the game
        self.root.mainloop()

    def difficultySelection(self):
        if self.radioVar.get() == 1:  # Easy
            self.diffCount = self.optionDiffCount[0]
            self.diffTime = self.optionDiffTime[0]

        elif self.radioVar.get() == 2:  # Normal
            self.diffCount = self.optionDiffCount[1]
            self.diffTime = self.optionDiffTime[1]

        elif self.radioVar.get() == 3:  # Hard
            self.diffCount = self.optionDiffCount[2]
            self.diffTime = self.optionDiffTime[2]

        self.gameStart()  # difficulty selection is finished

    def gameStart(self):
        # remove all widgets for difficulty selection
        self.radioBtn1.destroy()
        self.radioBtn2.destroy()
        self.radioBtn3.destroy()
        self.diffBtn.destroy()
        self.diffLabel.destroy()

        # initialize the game
        self.statusGame = True
        self.labelScore.place(x=self.optionWidgetCoordinate[0],
                              y=self.optionWidgetCoordinate[1])
        self.labelLife.place(x=self.optionWidgetCoordinate[2],
                             y=self.optionWidgetCoordinate[3])
        self.labelLineTop.place(x=self.optionWidgetCoordinate[4],
                                y=self.optionWidgetCoordinate[5])
        self.labelLineBot.place(x=self.optionWidgetCoordinate[6],
                                y=self.optionWidgetCoordinate[7])
        self.inputEntry.place(x=self.optionWidgetCoordinate[8],
                              y=self.optionWidgetCoordinate[9])

        self.loopTimer = PerpetualTimer(self.diffTime / 130, self.loopFunction,
                                        self.diffCount)
        self.loopTimer.start()

    def inputResponse(self, event):

        if self.statusGame == True:

            matchFound = acid_rain.gameEngine.inputResponse(
                self.diffCount, self.inputEntry.get())  # check the word
            self.inputEntry.delete(0, END)  # clear the text box

            if matchFound == True:
                self.statusScore += 1

                # find current dead block object and configure the widgets to renew the field
                for i in range(self.diffCount):
                    if acid_rain.gameEngine.wordBlockList[i].alive == True:
                        pass
                    else:
                        self.labelBlockList[i].configure(
                            text=acid_rain.gameEngine.wordBlockList[i].name)
                        self.labelBlockList[i].place_forget()
                        self.labelScore.configure(text=("Score: " +
                                                        str(self.statusScore)))

            else:
                pass

        else:
            pass  # game is not started yet

    def inputResponseEscape(self, event):

        self.loopTimer.stop()
        messagebox.showinfo("Game Over!", "You hit the escape key!")

    def loopFunction(self, diffCount):
        ## deploy a new word block if we have not enough word blocks on the field
        # prevent the burst as using wordCreateLimit variable
        if len(acid_rain.gameEngine.blockNameList
               ) < diffCount and self.wordCreateLimit == 2:

            self.wordCreateLimit = 0  # set the limit variable

            # find a dead block object and call the blockCreate function
            for i in range(diffCount):

                if acid_rain.gameEngine.wordBlockList[i].alive == True:
                    pass

                else:
                    acid_rain.gameEngine.wordBlockList[i].blockCreate(
                        acid_rain.gameEngine
                    )  # calling the blockCreate function
                    self.labelBlockList[i].configure(
                        text=acid_rain.gameEngine.wordBlockList[i].name
                    )  # pass the name of the new block to widget
                    self.labelBlockList[i].place(
                        x=10 +
                        acid_rain.gameEngine.wordBlockList[i].coordinate[0] *
                        60,
                        y=30 +
                        acid_rain.gameEngine.wordBlockList[i].coordinate[1] *
                        19)
                    break  # if we find one, escape the loop

        # after two loop, we allow to deploy a new block
        if self.wordCreateLimit != 2:
            self.wordCreateLimit += 1

        ## active block moves
        for i in range(diffCount):

            if acid_rain.gameEngine.wordBlockList[i].alive == True:

                # if the player missed this block, call blockRemove function and subtract life
                if acid_rain.gameEngine.wordBlockList[i].coordinate[1] == 20:
                    acid_rain.gameEngine.wordBlockList[i].blockRemove(
                        acid_rain.gameEngine)
                    self.labelBlockList[i].configure(
                        text=acid_rain.gameEngine.wordBlockList[i].name)
                    self.labelBlockList[i].place_forget()
                    self.statusLife -= 1

                    # check the remaining life
                    if self.statusLife != 0:
                        pass
                    else:  # game over
                        self.loopTimer.stop()
                        messagebox.showinfo(
                            "Game Over!",
                            f"Your Final Score is {self.statusScore}!")

                else:
                    acid_rain.gameEngine.wordBlockList[i].coordinate[
                        1] += 1  # adjust y-coordinate

                    if acid_rain.gameEngine.wordBlockList[i].coordinate[
                            1] != 0:  # check if the word is just created (to prevent 'blinking' bug)
                        self.labelBlockList[i].place(
                            x=10 +
                            acid_rain.gameEngine.wordBlockList[i].coordinate[0]
                            * 60,
                            y=30 +
                            acid_rain.gameEngine.wordBlockList[i].coordinate[1]
                            * 19)
                    else:
                        pass

            else:
                pass

        ## configure score and life
        self.labelScore.configure(text=("Score: " + str(self.statusScore)))
        self.labelLife.configure(text=("Life: " + str(self.statusLife)))
Example #26
0
class IPTracker:
    def __init__(self, master):
        """ Creating global variables and frames. """

        self._FINISH = False
        self._FINISH_SEARCHING = False
        self.hosts_searching_thread = None

        self.assigned_devices = []
        self.devices_to_track = set()
        self.network_cards = set()
        self.devices_frames = []
        self.devices_frames_buttons = {}
        self.settings_dict = {}

        self.load_settings()

        self.root = master
        self.root.title("IP Tracker")
        self.root.minsize(500, 700)
        self.root.maxsize(500, 700)

        self.network_cards = self.search_interfaces()

        self.selected_netcard = self.network_cards[0]["Name"]

        self.assigned_devices = self.get_ip_list()

        # Frames

        self.master = tk.Frame(self.root, width='500', height='700')
        self.frame1 = tk.Frame(self.master)
        self.frame2 = tk.Frame(self.master)
        self.frame3 = tk.Frame(self.master)
        self.frame4 = tk.Frame(self.master,
                               width='500',
                               height='10',
                               highlightthickness=10)

        # Frames layout

        self.master.pack(anchor="nw", fill="both", expand=True)

        self.frame1.pack(anchor="nw", fill="x", expand=False)
        self.frame2.pack(anchor="nw", fill="x", expand=False)
        self.frame3.pack(anchor="nw", fill="x", expand=False)
        self.frame4.pack(anchor="nw", fill="both", expand=True)

        self.canvas = tk.Canvas(self.frame4)
        self.scrollbar = ttk.Scrollbar(self.frame4,
                                       orient="vertical",
                                       command=self.canvas.yview)
        self.scrollable_frame = ttk.Frame(self.canvas)
        self.scrollable_frame.pack(anchor="nw", fill="both", expand=True)

        self.scrollable_frame.bind(
            "<Configure>", lambda e: self.canvas.configure(scrollregion=self.
                                                           canvas.bbox("all")))

        self.canvas.bind_all("<MouseWheel>", self._on_mousewheel)
        self.canvas.create_window((0, 0),
                                  window=self.scrollable_frame,
                                  anchor="nw")
        self.canvas.configure(yscrollcommand=self.scrollbar.set)

        self.frame4.config(highlightbackground="SystemButtonFace",
                           highlightcolor="SystemButtonFace")
        self.myscrollbar = ttk.Scrollbar(self.frame4,
                                         orient="vertical",
                                         command=self.canvas.yview)
        self.canvas.configure(yscrollcommand=self.myscrollbar.set, bg="white")

        self.frame4.pack()
        self.canvas.pack(side="left", fill="both", expand=True)
        self.scrollbar.pack(side="right", fill="y")

        # Frame 1

        self.top_label = Label(self.frame1,
                               text="Devices tracker",
                               font=("", 12))

        # layout 1

        self.top_label.pack(pady=3)

        # Frame 2

        self.frame2.grid_rowconfigure(3, weight=1)
        self.frame2.grid_columnconfigure(6, weight=1)

        self.drop_list = Label(self.frame2, text="Network card:")

        self.netcards_value = StringVar()
        self.combobox = ttk.Combobox(self.frame2,
                                     textvariable=self.netcards_value)
        self.combobox['values'] = [i["Name"] for i in self.network_cards]
        self.combobox.current(0)
        self.combobox.bind("<<ComboboxSelected>>", self.select_netcard)

        self.settings = Button(self.frame2,
                               text="Settings",
                               width=6,
                               command=self.create_settings_window)
        vcmd = master.register(self.validate)

        # layout 2

        self.drop_list.grid(row=0, column=0, sticky=W)
        self.combobox.grid(row=0, column=1, sticky=W)
        self.settings.grid(row=0, column=7, sticky=W)

        # Frame 3

        self.ip_address_label = Label(self.frame3, text="Add IP address:")

        self.custom_ip_1 = Entry(self.frame3,
                                 validate="key",
                                 validatecommand=(vcmd, '%P'),
                                 width=4)
        self.custom_ip_2 = Entry(self.frame3,
                                 validate="key",
                                 validatecommand=(vcmd, '%P'),
                                 width=4)
        self.custom_ip_3 = Entry(self.frame3,
                                 validate="key",
                                 validatecommand=(vcmd, '%P'),
                                 width=4)
        self.custom_ip_4 = Entry(self.frame3,
                                 validate="key",
                                 validatecommand=(vcmd, '%P'),
                                 width=4)

        self.add_ip_button = Button(self.frame3,
                                    text="Add",
                                    command=self.get_address_ip_from_user)

        self.search_devices_button = Button(
            self.frame3,
            text="Search for devices",
            command=lambda: self.change_search_button_on())

        self.run_tracking_button = Button(self.frame3,
                                          text="Run tracking",
                                          command=lambda: self.track())

        # layout 3

        self.ip_address_label.grid(row=0, column=0, sticky=W)
        self.custom_ip_1.grid(row=0, column=1, sticky=W)
        self.custom_ip_2.grid(row=0, column=2, sticky=W)
        self.custom_ip_3.grid(row=0, column=3, sticky=W)
        self.custom_ip_4.grid(row=0, column=4, sticky=W)
        self.add_ip_button.grid(row=0, column=5, sticky=W, padx=2)
        self.search_devices_button.grid(row=0, column=7, sticky=W, padx=2)
        self.run_tracking_button.grid(row=0, column=9, padx=2)

        self.select_netcard(None, self.network_cards[0]["Name"])

        self.refresh_searching()

    def load_settings(self):
        """ Reading settings from settings.txt """

        with open("settings.txt", "r") as f:
            f = f.readlines()
            for line in f:
                if len(line) > 0:
                    line = line.replace("\n", "")
                    line = line.split("=")
                    self.settings_dict[line[0]] = line[1]

    def save_settings(self, new_settings):
        """ Changing settings in settings.txt """

        if len(new_settings) > 0:
            for i in new_settings.keys():
                self.settings_dict[i] = new_settings[i]

        with open("settings.txt", "w") as f:
            wrt = ""
            for i in self.settings_dict.keys():
                wrt += i + "=" + self.settings_dict[i] + "\n"
            f.write(wrt)
        self.load_settings()

    def get_ip_list(self):
        """ Reading ip list for network card from devices.json. """

        ret = []

        try:
            with open("devices.json") as f:
                devices_in_network = json.load(f)

                devices_in_network_keys = list(devices_in_network.keys())

                if type(self.selected_netcard) == str:
                    return []

                if not self.selected_netcard["Name"] in devices_in_network_keys:

                    devices_in_network[self.selected_netcard["Name"]] = []
                    with open("devices.json", "w") as f:
                        json.dump(devices_in_network, f)

                for line in devices_in_network[self.selected_netcard["Name"]]:

                    line = line.replace("\n", "")

                    splitted = line.split(".")
                    correct = True

                    try:
                        length = 0
                        for i in splitted:
                            if not len(i) < 1 and not len(i) > 3 and int(
                                    i) <= 255 and int(i) >= 0:
                                correct = True
                                length += 1
                            else:
                                correct = False
                                break

                        if length == 4 and correct == True and line not in ret:
                            ret.append(line)

                    except:
                        pass
        except:
            ret = []
        return ret

    def add_ip(self, ip_address):
        """ Adding ip received from user."""

        if ip_address not in self.assigned_devices:
            self.insert_device(self.selected_netcard, ip_address)
            self.assigned_devices.append(ip_address)
            self.refresh_searching()

    def __write_line(self, status):
        """ Write line of data(Date,time,status) in each file. """

        with open(self.path, "a", newline='') as self.f:
            self.writer = csv.writer(self.f, delimiter="\t")
            self.writer.writerow([
                str(datetime.now().strftime("%Y-%m-%d %H:%M:%S")) + " " +
                status
            ])
            return

    def _get_card_name_from_reg(self, iface_guids):
        """ Getting network card name from regedit. """

        iface_names = ['(unknown)' for i in range(len(iface_guids))]
        reg = wr.ConnectRegistry(None, wr.HKEY_LOCAL_MACHINE)
        reg_key = wr.OpenKey(
            reg,
            r'SYSTEM\CurrentControlSet\Control\Network\{4d36e972-e325-11ce-bfc1-08002be10318}'
        )
        for i in range(len(iface_guids)):
            try:
                reg_subkey = wr.OpenKey(reg_key,
                                        iface_guids[i] + r'\Connection')
                iface_names[i] = wr.QueryValueEx(reg_subkey, 'Name')[0]
            except FileNotFoundError:
                pass
        return iface_names

    def search_interfaces(self):
        """ Searching for network cards on local machine. """

        self.network_cards = []
        for i in netifaces.interfaces():
            tmp = {}
            try:

                tmp["Name"] = self._get_card_name_from_reg([i])[0]
                if not tmp["Name"] == "(unknown)":

                    tmp["IP Address"] = netifaces.ifaddresses(i)[
                        netifaces.AF_INET][0]['addr']
                    tmp["Mask"] = netifaces.ifaddresses(i)[
                        netifaces.AF_INET][0]['netmask']
                    tmp["Gateway"] = netifaces.gateways()['default'][
                        netifaces.AF_INET][0]

                    self.network_cards.append(tmp)
            except:
                pass
        return self.network_cards

    def _start_searching(self, network_card):
        """ Starts searching for new network cards. """

        network = IPNetwork('/'.join(
            [network_card["Gateway"], network_card["Mask"]]))
        generator = network.iter_hosts()

        for i in generator:

            i = str(i)
            if self._FINISH_SEARCHING:
                self.change_search_button_off(True, False)
                break
            else:
                if not i in self.assigned_devices and not i == network_card[
                        "IP Address"]:

                    response = subprocess.Popen(
                        'ping -n 1 {}'.format(i),
                        stdout=subprocess.PIPE).communicate()[0]

                    if "unreachable" in str(
                            response) or "Request timed out" in str(response):
                        pass
                    else:
                        self.insert_device(self.selected_netcard, i)
                        self.assigned_devices.append(i)
                        self.refresh_searching()
                else:
                    pass

        self._FINISH_SEARCHING = False
        self.change_search_button_off(True, False)
        return

    def search_new_hosts(self, name):
        """ Starts thread for host searching. """

        for interface in self.network_cards:
            if interface["Name"] == name["Name"]:
                self.hosts_searching_thread = threading.Thread(
                    target=self._start_searching, args=(interface, ))
                self.hosts_searching_thread.start()

                break

    def stop_searching(self):
        """ Changing flag _FINISH_SEARCHING to true and stopping current searching thread. """

        self._FINISH_SEARCHING = True

    def _run_tracking(self, interval):
        """ Run tracking devices in self.devices_to_track. """

        while True:

            if len(self.devices_to_track) > 0:
                for hostname in self.devices_to_track.copy():

                    if hostname in self.devices_to_track:

                        self.response = subprocess.Popen(
                            'ping -n 1 {}'.format(hostname),
                            stdout=subprocess.PIPE).communicate()[0]

                        if not os.path.exists("data/" +
                                              self.selected_netcard["Name"]):
                            os.makedirs("data/" +
                                        self.selected_netcard["Name"])

                        self.path = "data/{}/{}.csv".format(
                            self.selected_netcard["Name"], hostname)

                        if "unreachable" in str(
                                self.response) or "Request timed out" in str(
                                    self.response):
                            if os.path.exists(self.path):
                                self.__write_line("0")
                            else:
                                self.__write_line("0")
                        else:
                            if os.path.exists(self.path):
                                self.__write_line("1")
                            else:
                                self.__write_line("1")

                        self.check_status(self.path, hostname)
            if interval <= 0:
                interval = 1
            for i in range(interval):

                if self._FINISH:
                    self.run_tracking_button = Button(
                        self.frame3,
                        text="Run tracking",
                        command=lambda: self.track())
                    self.run_tracking_button.grid(row=0, column=9)
                    self._FINISH = False
                    for key in self.devices_frames_buttons.keys():
                        if "start" in key:
                            self.devices_frames_buttons[key][2].configure(
                                background="SystemButtonFace", text="N/A")
                    return
                time.sleep(1)

    def add_device_to_track(self, data):
        """ Adding device to self.devices_to_track. """

        self.devices_to_track.add(data[1])
        self.devices_frames_buttons[data[0]][1] = ttk.Button(
            data[2],
            text='Stop',
            command=lambda c=[data[0], data[1], data[2]
                              ]: self.remove_device_to_track(c))
        self.devices_frames_buttons[data[0]][1].grid(row=int(data[0][-1]),
                                                     column=2,
                                                     padx=5)

    def remove_device_to_track(self, data):
        """ Removing device from self.devices_to_track. """

        self.devices_to_track.remove(data[1])
        self.devices_frames_buttons[data[0]][1] = ttk.Button(
            data[2],
            text='Start',
            command=lambda c=[data[0], data[1], data[2]
                              ]: self.add_device_to_track(c))
        self.devices_frames_buttons[data[0]][1].grid(row=int(data[0][-1]),
                                                     column=2,
                                                     padx=5)

        if len(self.devices_to_track) == 0:
            for key in self.devices_frames_buttons.keys():
                if "start" in key and self.devices_frames_buttons[key][
                        0] not in self.devices_to_track:
                    self.devices_frames_buttons[key][2].configure(
                        background="SystemButtonFace", text="N/A")

    def insert_device(self, net_card, ip_address):
        """ Inserting device to devices.json. """

        with open('devices.json') as f:
            data = json.load(f)

        try:
            data[net_card["Name"]].append(ip_address)
        except:
            data[net_card["Name"]] = [ip_address]

        with open('devices.json', 'w') as f:
            json.dump(data, f)

    def track(self):
        """ Starts devices tracking thread and change name of button to 'Stop tracking' """

        try:
            interval = int(self.settings_dict["interval"])
            if interval == 0:
                interval = 1
        except:
            interval = 1

        self._FINISH = False
        self.t = threading.Thread(target=self._run_tracking, args=(interval, ))
        self.t.start()
        self.run_tracking_button = Button(
            self.frame3,
            text="Stop tracking",
            command=lambda: self.turn_off_tracking())
        self.run_tracking_button.grid(row=0, column=9)

    def turn_off_tracking(self):
        """ Changing flag self._FINISH to True and stopping tracking. """

        self._FINISH = True

    def check_status(self, path, hostname):
        """ Checking status of last line in file('current_ip'.csv). If status is 1 display 'ON', if 0 display 'OFF', if not device is not currently tracked display 'N/A' """

        with open(path, 'r') as f:

            line = list(csv.reader(f, delimiter=' '))
            for key in self.devices_frames_buttons.keys():

                if self.devices_frames_buttons[key][
                        0] == hostname and "start" in key:
                    if line[-1][2] == "1":
                        self.devices_frames_buttons[key][2].configure(
                            background="green", text="ON")
                    else:
                        self.devices_frames_buttons[key][2].configure(
                            background="red", text="OFF")
                elif "start" in key and self.devices_frames_buttons[key][
                        0] not in self.devices_to_track:
                    self.devices_frames_buttons[key][2].configure(
                        background="SystemButtonFace", text="N/A")

    def create_settings_window(self):
        """ Opens window with general settings to change.  """

        self.settings_window = tk.Toplevel(self.master)
        self.settings_window.title("Settings")
        self.settings_window.minsize(200, 50)
        self.settings_window.maxsize(200, 200)
        vcmd = self.settings_window.register(self.validate_interval)

        empty_space1 = Label(self.settings_window, text="")
        empty_space1.grid(row=0, column=0)

        Label(self.settings_window, text="Interval [s]",
              font=("", )).grid(row=1, column=0)
        val = StringVar()
        interval_value = Entry(self.settings_window,
                               textvariable=val,
                               validate="key",
                               validatecommand=(vcmd, '%P'),
                               width=3)
        interval_value.grid(row=1, column=1)

        empty_space2 = Label(self.settings_window, text="")
        empty_space2.grid(row=2, column=0)

        confirm_button = Button(self.settings_window,
                                text="Confirm",
                                command=lambda: self.save_settings(
                                    {"interval": interval_value.get()}))
        confirm_button.grid(row=3, column=1)

    def change_search_button_on(self):
        """ If clicked 'Search for devices' button changes it's text to 'Stop searching' """

        self.search_devices_button.destroy()
        self.stop_search_devices_button = Button(
            self.frame3,
            text="Stop searching",
            command=lambda: self.change_search_button_off(False, True))
        self.stop_search_devices_button.grid(row=0, column=7, sticky=W)
        self.search_new_hosts(self.selected_netcard)

    def change_search_button_off(self, button, stop):
        """ If clicked 'Stop searching' button changes it's text to 'Search for devices' """
        def change_button():
            self.search_devices_button.destroy()
            self.search_devices_button = Button(
                self.frame3,
                text="Search for devices",
                command=lambda: self.change_search_button_on())
            self.search_devices_button.grid(row=0, column=7, sticky=W)

        def stop_search_button():
            self.stop_searching()

        if stop:
            stop_search_button()
        if button:
            self.search_devices_button.destroy()
            change_button()

    def clear_history(self, ip):
        """ Clearing file which contain data from device tracking.  """

        path = "data/{}/{}.csv".format(self.selected_netcard["Name"], ip)
        with open(path, "w") as f:
            f.write("")

    def select_netcard(self, event, netcard=""):
        """ If clicked network card name from list chosen one is assigned to current self.selected_network_card. """

        self._FINISH = True

        if len(netcard) > 0:
            netcard = netcard
        else:
            netcard = self.combobox.get()

        for card in self.network_cards:
            if card["Name"] == netcard:
                self.selected_netcard = card
                break

        n = 0
        for i in self.devices_frames:
            self.devices_frames[n].destroy()
            n += 1

        self.devices_frames.clear()
        self.assigned_devices.clear()
        self.devices_frames_buttons.clear()

        self.assigned_devices = self.get_ip_list()

        self.refresh_searching()

    def delete_ip_frame(self, ip_address):
        """ Removes ip from self.assigned_devices and deletes it's frame. """

        self.assigned_devices.remove(ip_address)

        with open("devices.json") as f:
            devices_in_network = json.load(f)

            devices_in_network[
                self.selected_netcard["Name"]] = self.assigned_devices

            with open("devices.json", "w") as f:
                json.dump(devices_in_network, f)
        self.refresh_searching()

    def refresh_searching(self):

        try:
            n = 0
            for i in self.devices_frames:
                self.devices_frames[n].destroy()
                n += 1
        except:
            pass
        i = 0
        try:
            self.devices_frames_buttons.clear()
            for ip in self.assigned_devices:
                tmp = tk.Frame(self.scrollable_frame,
                               borderwidth=2,
                               relief="groove")
                tmp.grid(row=i, column=0, pady=5, padx=2)
                tmp.grid_columnconfigure(1, weight=1)
                tmp.configure(background='white')

                text = "{}".format(str(ip))

                tmp_label = ttk.Label(tmp,
                                      text=text,
                                      font=("Arial", 16),
                                      width=13)
                tmp_label.configure(background='white')
                tmp_label.grid(row=i, column=0)

                start = "start_" + str(i)
                options = "options_" + str(i)

                self.devices_frames_buttons[start] = []

                self.devices_frames_buttons[start].append(text)

                if text in self.devices_to_track:

                    self.devices_frames_buttons[start].append(
                        ttk.Button(tmp,
                                   text='Stop',
                                   command=lambda c=[
                                       start, self.devices_frames_buttons[
                                           start][0], tmp
                                   ]: self.remove_device_to_track(c)))
                    self.devices_frames_buttons[start][1].grid(row=i,
                                                               column=2,
                                                               padx=5)

                else:

                    self.devices_frames_buttons[start].append(
                        ttk.Button(tmp,
                                   text='Start',
                                   command=lambda c=[
                                       start, self.devices_frames_buttons[
                                           start][0], tmp
                                   ]: self.add_device_to_track(c)))

                    self.devices_frames_buttons[start][1].grid(row=i,
                                                               column=2,
                                                               padx=5)

                self.devices_frames_buttons[start].append(
                    ttk.Label(tmp, text='N/A'))

                self.devices_frames_buttons[start][2].grid(row=i,
                                                           column=1,
                                                           padx=5)

                self.devices_frames_buttons[start].append(
                    ttk.Button(tmp,
                               text='Clear history',
                               command=lambda c=self.devices_frames_buttons[
                                   start][0]: self.clear_history(c)))

                self.devices_frames_buttons[start][3].grid(row=i,
                                                           column=3,
                                                           padx=5)

                self.devices_frames_buttons[options] = []

                self.devices_frames_buttons[options].append(text)

                self.devices_frames_buttons[options].append(
                    ttk.Button(tmp,
                               text='Delete',
                               command=lambda c=self.devices_frames_buttons[
                                   start][0]: self.delete_ip_frame(c)))

                self.devices_frames_buttons[options][1].grid(row=i,
                                                             column=4,
                                                             padx=5)

                if tmp not in self.devices_frames:
                    self.devices_frames.append(tmp)

                i += 1

        except:
            pass

    def get_address_ip_from_user(self):
        """ Gettings ip from user entry and calling function which insert ip in file. """

        ip1 = self.custom_ip_1.get()
        ip2 = self.custom_ip_2.get()
        ip3 = self.custom_ip_3.get()
        ip4 = self.custom_ip_4.get()

        splitted = [ip1, ip2, ip3, ip4]
        address = ".".join(splitted)

        try:
            length = 0
            for i in splitted:
                correct = True
                if not len(i) < 1 and not len(i) > 3 and int(i) <= 255 and int(
                        i) >= 0:
                    correct = True
                    length += 1
                else:
                    correct = False
                    break

            if length == 4 and correct and address not in self.assigned_devices:

                self.assigned_devices.append(address)
                self.insert_device(self.selected_netcard, address)
                self.refresh_searching()

        except:
            pass

    def validate(self, new_text):
        """ Validation when pressed key. Allows only numbers not bigger than 3 digits. """

        if len(new_text) > 3:
            return False

        if not new_text:  # the field is being cleared

            self.entered_number = 0

            return True

        try:

            self.entered_number = int(new_text)

            return True

        except ValueError:

            return False

    def validate_interval(self, new_value):
        """ Validation when pressed key.
        Allows only numbers not bigger than 2 digits. 
        """

        if len(new_value) > 2:
            return False

        if not new_value:  # the field is being cleared
            return True

        try:
            self.entered_number = int(new_value)

            return True

        except ValueError:
            return False

    def _on_mousewheel(self, event):
        """IF scroll wheeled set position of slider."""

        self.canvas.yview_scroll(int(-1 * (event.delta / 120)), "units")
Example #27
0
class Calendar_ui():
    def __init__(self, master, Year, Month, Day):
        global datelist, file_name, currenttime
        self.master = master
        self.master.title(u'日历')
        self.master.geometry('440x500+400+100')
        self.master.minsize(440, 500)
        self.master.maxsize(440, 500)
        self.Year = Year
        self.Month = Month
        self.Day = Day

        #print(self.Year)
        #print(self.Month)
        #print(self.Day)

        self.button1 = Button(self.master,
                              text='Previous',
                              width=8,
                              height=1,
                              command=self.ButtonPrevious)
        self.button1.place(x=50, y=240, width=80, height=30)
        self.button2 = Button(self.master,
                              text='Next',
                              width=8,
                              height=1,
                              command=self.ButtonNext)
        self.button2.place(x=150, y=240, width=80, height=30)
        self.button3 = Button(self.master,
                              text='back diary',
                              width=8,
                              height=1,
                              command=self.Back)
        self.button3.place(x=340, y=240, width=80, height=30)
        self.button4 = Button(self.master, text=u'查看日记', command=self.review)
        self.button4.place(x=340, y=400, width=80, height=30)
        self.button5 = Button(self.master, text=u'日记备份', command=self.backup)
        self.button5.place(x=340, y=450, width=80, height=30)
        self.summary_log = Text(self.master, background='azure')
        self.summary_log.place(x=20, y=280, width=310, height=200)
        self.summary_log.bind("<Key-Return>", self.enter)
        self.summary_log.delete(0.0, END)
        self.summary_log.insert('0.0', '---绿底日期代表当天有日记记录。')
        if file_name == '':
            self.summary_log.insert(END, '\n---还未输入用户名,请返回日记界面输入有效的日记用户名')
        else:
            self.summary_log.insert(END, '\n---首次记录成功日记时间为: %s。' % datelist[0])
            now = datetime.datetime.strptime(currenttime[0], "%Y-%m-%d")
            firstday = datetime.datetime.strptime(datelist[0], "%Y-%m-%d")
            days = (now - firstday).days
            #print(days)
            self.summary_log.insert(END, '\n---距今天数: %d天,  ' % days)
            now_rate = (len(datelist)) / days
            #print(now_rate)
            self.summary_log.insert(END,
                                    '准时完成度: {:.1f}%。'.format(now_rate * 100))
        self.ui_update()

    def ui_update(self):
        global file_name, datelist, currenttime
        #print(datelist)
        #print(self.Month)
        # 首行放置“年、月”的位置
        label = Label(self.master, text=str(self.Year) + "年")
        label.grid(row=0, column=2)
        label = Label(self.master, text=str(self.Month) + "月")
        label.grid(row=0, column=4)
        # labels列表:放置“星期”的标题
        # 用calendar库计算日历
        #global MonthCal

        labels = [['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']]
        self.MonthCal = calendar.monthcalendar(self.Year, self.Month)
        days_in_month = calendar.monthrange(self.Year, self.Month)[1]
        #print(days_in_month)

        #for days_in_week in self.MonthCal:
        #days_in_month = days_in_month + days_in_week
        #print(max(days_in_month))

        if self.Month < 10:
            select_month = str(self.Year) + '-0' + str(self.Month)
        else:
            select_month = str(self.Year) + '-' + str(self.Month)

        self.dayslist_inMonth = []
        for days in datelist:
            #print(select_month)
            #print(days)
            if re.match(select_month, days) != None:
                self.dayslist_inMonth.append(days)

        #print(dayslist_inMonth)

        #print(self.MonthCal)
        self.clear_grid()
        # 把日历加到labels列表中
        for i in range(len(self.MonthCal)):
            labels.append(self.MonthCal[i])
        #print(self.labels)
        # 放置日历
        for r in range(len(self.MonthCal) + 1):
            for c in range(7):
                if labels[r][c] == 0:
                    labels[r][c] = ' '
                if (r == 0) or (labels[r][c] == ' '):
                    label = Label(self.master,
                                  width=7,
                                  padx=4,
                                  pady=5,
                                  justify='center',
                                  text=str(labels[r][c]))

                else:
                    date_string = datetime.date(self.Year, self.Month,
                                                int(labels[r][c]))
                    #print(date_string)
                    #print(datelist)
                    if str(date_string) in datelist:
                        label = Label(self.master,
                                      bg='green',
                                      width=7,
                                      padx=4,
                                      pady=5,
                                      justify='center',
                                      text=str(labels[r][c]))
                        #print('yes')
                    else:
                        label = Label(
                            self.master,
                            #bg = 'yellow',
                            width=7,
                            padx=4,
                            pady=5,
                            justify='center',
                            text=str(labels[r][c]))
                        #print('no')

                label.grid(row=r + 1, column=c)  # 网格布局

        if file_name != '':
            month_rate = len(self.dayslist_inMonth) / days_in_month
            self.summary_log.insert(
                END, '\n---{}月完成度: {:.1f}%。'.format(self.Month,
                                                    month_rate * 100))

    def clear_grid(self):
        # 先把界面清空
        for r in range(7):
            for c in range(7):
                label = Label(self.master,
                              width=7,
                              padx=4,
                              pady=5,
                              justify='center',
                              text=' ')
                label.grid(row=r + 1, column=c)

    # button:Enter
    def ButtonPrevious(self):
        self.Month = self.Month - 1
        if self.Month < 1:
            self.Month = self.Month + 12
            self.Year = self.Year - 1
        self.ui_update()

    # button:Clear
    def ButtonNext(self):
        self.Month = self.Month + 1
        if self.Month > 12:
            self.Month = self.Month - 12
            self.Year = self.Year + 1
        self.ui_update()

    def Back(self):
        global file_name
        self.clear_grid()
        self.button1.destroy()
        self.button2.destroy()
        self.button3.destroy()
        self.summary_log.destroy()
        self.button4.destroy()
        self.button5.destroy()
        file_name = ''
        initface(self.master)

    def review(self):
        self.summary_log.delete(0.0, END)
        if self.Month < 10:
            self.summary_log.insert(
                END, '---请输入需要查阅的日期: {}-0{}-'.format(str(self.Year),
                                                     str(self.Month)))
        else:
            self.summary_log.insert(
                END, '---请输入需要查阅的日期: {}-{}-'.format(str(self.Year),
                                                    str(self.Month)))
        self.summary_log.focus_force()

    def enter(self, event):
        self.dialog = False
        infor_insert = self.summary_log.get(0.0, END)
        last_line = infor_insert.split('---')[-1]
        #print(last_line)
        date_an = last_line.split(' ')[-1].split('-')

        try:
            if int(date_an[2]) < 10:
                self.date_select = '{}-{}-0{}'.format(date_an[0], date_an[1],
                                                      date_an[2])
            elif int(date_an[2]) < 31:
                self.date_select = '{}-{}-{}'.format(date_an[0], date_an[1],
                                                     date_an[2])
            else:
                self.summary_log.insert(END, '\n---输入错误,日期应小于31!')
                self.summary_log.insert(
                    END, '\n- - - - - - - - - - - - - - - - - - - - - -\n')
                self.dialog = True
            #print(date_select)
        except ValueError:
            self.summary_log.insert(END, '\n---输入的值不正确,请重新输入日期!')
            self.summary_log.insert(
                END, '\n- - - - - - - - - - - - - - - - - - - - - -\n')
            self.dialog = True

        try:
            if self.dayslist_inMonth.count(self.date_select.replace('\n',
                                                                    '')) == 1:
                pass
            else:
                #print(len(self.date_select.replace('\n','')))
                #print(len(self.dayslist_inMonth[0]))
                #print(self.date_select)
                #print(self.dayslist_inMonth[0])
                #print(self.dayslist_inMonth[0] == self.date_select)
                self.summary_log.insert(END, '\n---当日无记录!')
                self.summary_log.insert(
                    END, '\n- - - - - - - - - - - - - - - - - - - - - -\n')
                self.dialog = True

        except AttributeError:
            pass

        self.enter_dialog()

    def enter_dialog(self):
        if self.dialog == True:
            if self.Month < 10:
                self.summary_log.insert(
                    END,
                    '\n---请输入需要查阅的日期: {}-0{}-'.format(str(self.Year),
                                                      str(self.Month)))
            else:
                self.summary_log.insert(
                    END,
                    '\n---请输入需要查阅的日期: {}-{}-'.format(str(self.Year),
                                                     str(self.Month)))
                #self.summary_log.focus_force()

        else:
            with open('.\\data\\' + file_name + '.txt', "r") as f:
                data = f.read()
                record_list = data.split('\n\n\n\n\n')
                #print(record_list)
            for i in record_list:
                #print(i)
                if self.date_select.replace('\n', '') in i:

                    self.summary_log.insert(END, '\n' + i)
                    self.summary_log.insert(
                        END, '\n- - - - - - - - - - - - - - - - - - - - - -')
            record_list = []
            if self.Month < 10:
                self.summary_log.insert(
                    END, '\n\n\n---请输入需要查阅的日期: {}-0{}-'.format(
                        str(self.Year), str(self.Month)))
            else:
                self.summary_log.insert(
                    END,
                    '\n---请输入需要查阅的日期: {}-{}-'.format(str(self.Year),
                                                     str(self.Month)))

    def backup(self):
        global backupdir
        self.summary_log.delete(0.0, END)
        rootdir = '.\\data'
        absdir = path.abspath(path.dirname(rootdir))
        #print(absdir)
        for (dirpath, dirnames, filenames) in walk(rootdir):
            #print(dirpath,dirnames,filenames)
            for filename in filenames:
                if path.splitext(filename)[1] == '.txt':
                    copycmd = 'copy "{}\\data\\{}" "{}\\{}"'.format(
                        absdir, filename, backupdir, filename)
                    print(copycmd)
                    if system(copycmd) == 0:
                        self.summary_log.insert(
                            END, '\n---{} 备份成功!'.format(filename))
                        self.summary_log.insert(
                            END,
                            '\n---备份路径: {}  \n---如需更改备份路径,可以去配置文件上面改'.format(
                                backupdir))
                        self.summary_log.insert(
                            END,
                            '\n\n- - - - - - - - - - - - - - - - - - - - - -')
                    else:
                        self.summary_log.insert(
                            END, '\n---{} 备份失败!'.format(filename))
Example #28
0
class SearchHelper:
    def __init__(self, searchframe):
        self.frame = searchframe

        # keyword entry
        largefont = ('Veranda', 24)
        self.ent_keyword = Entry(self.frame,
                                 width=40,
                                 relief='raised',
                                 font=largefont,
                                 bd=1)
        # todo <Return> and entry is not empty call search()

        self.but_search = Button(
            self.frame,
            text='Search',
            width=15,
            state='disable',
            font="Veranda 16",
            command=lambda: self.frame.search(
                'http://cbrown686-test.apigee.net/cyberapi/articles?q=keywordtitlebody&title='
                + self.ent_keyword.get() + '&body=' + self.ent_keyword.get()))

        self.var = IntVar()
        self.var.set(0)
        self.check_filter = Checkbutton(self.frame,
                                        text="Advanced Filter",
                                        onvalue=1,
                                        offvalue=0,
                                        variable=self.var,
                                        command=self.filter_op,
                                        font="Veranda 16")
        calltipwindow.createToolTip(
            self.check_filter, "Click here for options to narrow your search")

        calltipwindow.createToolTip(
            self.ent_keyword, "Enter a word or phrase here to search by.")
        self.ent_keyword.bind('<Escape>', self.clear_text)
        self.ent_keyword.bind(
            '<Key>', lambda event: self.callenable(event, 'DefaultSearch'))

        if self.var.get():
            self.frame.searchButton(None)

        # filter stuff
        self.appearing_label = Label(searchframe,
                                     text='Appearing In:',
                                     background='#282828',
                                     font=15,
                                     foreground='#5DE0DC')
        self.box_value = StringVar()
        self.box = Combobox(searchframe, textvariable=self.box_value)
        calltipwindow.createToolTip(
            self.appearing_label, "Select where you want us to search "
            "for your provided search phrase.")
        calltipwindow.createToolTip(
            self.box, "Select where you want us to search "
            "for your provided search phrase.")
        self.box['values'] = ('Default', 'Title', 'Body', 'URL')
        self.box.current(0)
        self.box.bind('<<ComboboxSelected>>', self.setbaseurl)

        # author
        self.author_label = Label(searchframe,
                                  text='Author:',
                                  background='#282828',
                                  font=15,
                                  foreground='#5DE0DC')
        self.author_entry = Entry(searchframe,
                                  width=22,
                                  bd=2,
                                  background='#9A9A9A')
        calltipwindow.createToolTip(
            self.author_label,
            "Enter an author's first and/or last name (not case-sensitive).")
        calltipwindow.createToolTip(
            self.author_entry,
            "Enter an author's first and/or last name (not case-sensitive).")

        # subjectivity
        self.fsub_label = Label(searchframe,
                                text='Subjectivity:',
                                background='#282828',
                                font=15,
                                foreground='#5DE0DC')
        calltipwindow.createToolTip(
            self.fsub_label,
            "Choose an option here if you only want to see articles"
            " that are more objectively or subjectively written")
        self.var2 = IntVar()
        self.var2.set(1)
        self.fsub_nv = Radiobutton(searchframe,
                                   text="Don't Care",
                                   variable=self.var2,
                                   value=1,
                                   background='#282828',
                                   foreground='#5DE0DC')
        calltipwindow.createToolTip(
            self.fsub_nv,
            "Select this if you want all articles returned regarless of how they are written."
        )
        self.fsub_gt = Radiobutton(searchframe,
                                   text='More Subjective',
                                   variable=self.var2,
                                   value=2,
                                   background='#282828',
                                   foreground='#5DE0DC')
        calltipwindow.createToolTip(
            self.fsub_gt,
            "Select this if you only want articles that are more subjectively written."
        )
        self.fsub_lt = Radiobutton(searchframe,
                                   text='More Objective',
                                   variable=self.var2,
                                   value=3,
                                   background='#282828',
                                   foreground='#5DE0DC')

        calltipwindow.createToolTip(
            self.fsub_lt,
            "Select this if you only want articles that are more objectively written."
        )
        # date
        self.fD_label = Label(searchframe,
                              text='Date:',
                              background='#282828',
                              font=15,
                              foreground='#5DE0DC')
        self.fD_format = Label(searchframe,
                               text='00/00/0000',
                               background='#282828',
                               foreground='#BBBBBB')
        self.fD_format.configure(foreground='grey')
        self.fD_beinlab = Label(searchframe,
                                text='From:',
                                background='#282828',
                                foreground='#BBBBBB')
        self.fD_endlab = Label(searchframe,
                               text='To:',
                               background='#282828',
                               foreground='#BBBBBB')
        self.fD_ent = Entry(searchframe, width=10, bd=2, background='#9A9A9A')
        self.fD_ent.insert('end', '01/01/0001')
        self.fD_ent2 = Entry(searchframe, width=10, bd=2, background='#9A9A9A')
        self.fD_ent2.insert('end', strftime('%m/%d/%Y'))

        calltipwindow.createToolTip(
            self.fD_label,
            "Narrow your results to articles published in the dates here.")
        calltipwindow.createToolTip(
            self.fD_format,
            "Narrow your results to articles published in the dates here.")
        calltipwindow.createToolTip(
            self.fD_beinlab,
            "Narrow your results to articles published in the dates here.")
        calltipwindow.createToolTip(
            self.fD_endlab,
            "Narrow your results to articles published in the dates here.")
        calltipwindow.createToolTip(self.fD_ent, "Enter Start Date here.")
        calltipwindow.createToolTip(self.fD_ent2, "Enter End Date here.")

        # filter placements
        offset = 100
        self.appearing_label.place(x=400, y=380 + offset)

        # appearing pick
        self.box.place(x=510, y=380 + offset)

        # author label
        self.author_label.place(x=400, y=405 + offset)

        # author entry
        self.author_entry.place(x=510, y=405 + offset)

        # subjectivity
        self.fsub_label.place(x=400, y=430 + offset)
        self.fsub_nv.place(x=510, y=430 + offset)
        self.fsub_gt.place(x=510, y=455 + offset)
        self.fsub_lt.place(x=510, y=480 + offset)

        # date
        self.fD_label.place(x=400, y=505 + offset)
        self.fD_format.place(x=445, y=507 + offset)
        self.fD_beinlab.place(x=510, width=45, y=505 + offset)
        self.fD_ent.place(x=555, width=65, y=505 + offset)
        self.fD_endlab.place(x=630, y=505 + offset)
        self.fD_ent2.place(x=660, width=65, y=505 + offset)

        # buttons
        self.but_search.place(relx=.505, rely=.6, anchor=W)

        # ENTRY BOX for keyword
        self.ent_keyword.place(relx=.5, rely=.5, anchor=CENTER)

        # check button
        self.check_filter.place(relx=.495, rely=.6, relheight=.059, anchor=E)

        self.hidefilters()

    #filter options populate uppon check box of Advanced search option
    def filter_op(self):
        if self.var.get() is 1:
            self.showfilters()
        else:
            self.hidefilters()

    def resetsearch(self):
        self.ent_keyword.destroy()
        self.but_search.destroy()
        self.check_filter.destroy()

        self.appearing_label.destroy()
        self.box.destroy()
        self.author_label.destroy()
        self.author_entry.destroy()
        self.fsub_label.destroy()
        self.fsub_nv.destroy()
        self.fsub_gt.destroy()
        self.fsub_lt.destroy()
        self.fD_label.destroy()
        self.fD_format.destroy()
        self.fD_ent.destroy()
        self.fD_beinlab.destroy()
        self.fD_endlab.destroy()
        self.fD_ent2.destroy()
        self.__init__(self.frame)

    def hidefilters(self):
        self.appearing_label.lower()
        self.box.lower()
        self.author_label.lower()
        self.author_entry.lower()
        self.fsub_label.lower()
        self.fsub_nv.lower()
        self.fsub_gt.lower()
        self.fsub_lt.lower()
        self.fD_label.lower()
        self.fD_format.lower()
        self.fD_ent.lower()
        self.fD_beinlab.lower()
        self.fD_endlab.lower()
        self.fD_ent2.lower()

    def showfilters(self):
        self.appearing_label.lift()
        self.box.lift()
        self.author_label.lift()
        self.author_entry.lift()
        self.fsub_label.lift()
        self.fsub_nv.lift()
        self.fsub_gt.lift()
        self.fsub_lt.lift()
        self.fD_label.lift()
        self.fD_format.lift()
        self.fD_ent.lift()
        self.fD_beinlab.lift()
        self.fD_endlab.lift()
        self.fD_ent2.lift()

    def showsearch(self):
        self.ent_keyword.lift()
        self.but_search.lift()
        self.check_filter.lift()

        if self.var.get():
            self.showfilters()

    def hidesearch(self):
        self.ent_keyword.lower()
        self.but_search.lower()
        self.check_filter.lower()

    def setbaseurl(self, event):
        if self.box.current() is 0:
            self.but_search.config(command=lambda: self.frame.search(
                'http://cbrown686-test.apigee.net/cyberapi/articles?q=keywordtitlebody&title='
                + self.ent_keyword.get() + '&body=' + self.ent_keyword.get()))
        elif self.box.current() is 1:
            self.but_search.config(command=lambda: self.frame.search(
                'http://cbrown686-test.apigee.net/cyberapi/articles?q=keywordtitle&title='
                + self.ent_keyword.get()))
        elif self.box.current() is 2:
            self.but_search.config(command=lambda: self.frame.search(
                'http://cbrown686-test.apigee.net/cyberapi/articles?q=bodyonly&body='
                + self.ent_keyword.get()))
        elif self.box.current() is 3:
            self.but_search.config(command=lambda: self.frame.search(
                'http://cbrown686-test.apigee.net/cyberapi/articles?q=uri&uripath='
                + self.ent_keyword.get()))

    def addurlfilters(self, url):
        if self.var.get():
            au = self.author_entry.get()
            au = au.replace(' ', '+')
            # var2 is the state of the radio check button
            if self.var2.get() == 2:
                url = url + '&author=' + au + '&sub=gt&sdate=' + self.fD_ent.get(
                ) + '&edate=' + self.fD_ent2.get()
                # print(url)
            elif self.var2.get() == 3:
                url = url + '&author=' + au + '&sub=gt&sdate=' + self.fD_ent.get(
                ) + '&edate=' + self.fD_ent2.get()
            else:
                url = url + '&author=' + au + '&sub=&sdate=' + self.fD_ent.get(
                ) + '&edate=' + self.fD_ent2.get()
        else:
            url = url + '&author=&sub=&sdate=01/01/0001&edate=' + strftime(
                '%m/%d/%Y')

        return url

    # Hitting escape when editing the ENTRY box will clear it and disable the search button from being able to be used.
    def clear_text(self):
        self.ent_keyword.delete(0, 'end')
        self.but_search.configure(state='disable')

    def callenable(self, event, searchtype):
        self.frame.after(100, lambda: self.enablesearch(event, searchtype))

    # event bind when Return is entered after a title keyword is entered will enable the search button.
    def enablesearch(self, event, searchtype):
        string = ''
        if searchtype == 'DefaultSearch':
            string = self.ent_keyword.get()
        if string.strip() != '':
            self.but_search.configure(state='normal')
        else:
            self.but_search.configure(state='disabled')
Example #29
0
class Window:
    def __init__(self, root, database_manager) -> None:
        self.root = root
        self.root.title("Авторизация")
        self.root.geometry("255x175+0+0")
        self.database_manager = database_manager

    def main_page_init(self):
        self.root.geometry("330x120+0+0")
        self.root.title("Генератор билетов")
        self.root.eval("tk::PlaceWindow . center")
        self.FrameButtons = Frame(self.root, bg="white")
        self.FrameButtons.place(x=0, y=0)
        self._professors = list()

        professors = self.database_manager.get_all_professors()

        self.professors_combobox_values = list()

        for professor in professors:

            full_name = f"{professor.first_name} {professor.last_name} {professor.patronymic} {professor.id}"

            self.professors_combobox_values.append(full_name)

        self.message_label = Label(
            self.FrameButtons,
            text="Выбери преподавателя из списка",
            font=("times new roman", 20, "bold"),
        )
        self.message_label.grid(row=0, column=0, pady=10, padx=10)

        self.combobox_professor = Combobox(
            self.FrameButtons,
            values=self.professors_combobox_values,
            state="readonly",
            width=30,
        )
        self.combobox_professor.current(0)
        self.combobox_professor.grid(row=1, column=0, padx=10)

        self.button_create = Button(
            self.FrameButtons,
            command=self.create,
            text="Выбрать",
            font=("times new roman", 15, "bold"),
            bg="yellow",
            fg="red",
            width=35,
        )
        self.button_create.grid(row=2, column=0, padx=10)

    def create(self):

        if self.__dict__.get("professors_names") is None:
            self.professors_names = [
                self.combobox_professor.get(),
            ]

            self.combobox_professor.destroy()

            self.professors_combobox_values.remove(self.professors_names[0])

            self.combobox_professor = Combobox(
                self.FrameButtons,
                values=self.professors_combobox_values,
                state="readonly",
                width=30,
            )
            self.combobox_professor.current(0)
            self.combobox_professor.grid(row=1, column=0, padx=10)

            return

        elif len(self.professors_names) == 1 and (
            self.__dict__.get("subjects") is None
        ):
            self.professors_names.append(self.combobox_professor.get())
            self.combobox_professor.destroy()

            professor = self.professors_names.pop(0)
            professor_split = professor.split()
            self._professors.append(
                f"{professor_split[1]} {professor_split[0][:1]}.{professor_split[2][:1]}."
            )
            professor_id = int(professor_split[-1])

            self.message_label.destroy()
            self.message_label = Label(
                self.FrameButtons,
                text=f"{professor_split[1]} {professor_split[0]} {professor_split[2]}",
                font=("times new roman", 20, "bold"),
            )
            self.message_label.grid(row=0, column=0, pady=10, padx=10)

            subjects = self.database_manager.get_subjects_for_professor(
                professor_id=professor_id
            )
            combobox_subjects_values = list()

            for subject in subjects:
                combobox_subjects_values.append(
                    f"{subject.name} {subject.professor_id}"
                )

            self.combobox_subjects = Combobox(
                self.FrameButtons,
                values=combobox_subjects_values,
                state="readonly",
                width=30,
            )
            self.combobox_subjects.current(0)
            self.combobox_subjects.grid(row=1, column=0, padx=10)
            self.subjects = list()
            return

        elif len(self.__dict__.get("subjects")) == 0:
            self.subjects.append(self.combobox_subjects.get())
            self.combobox_subjects.destroy()

            professor = self.professors_names.pop(0)
            professor_split = professor.split()
            self._professors.append(
                f"{professor_split[1]} {professor_split[0][:1]}.{professor_split[2][:1]}."
            )
            professor_id = int(professor_split[-1])

            self.message_label.destroy()
            self.message_label = Label(
                self.FrameButtons,
                text=f"{professor_split[1]} {professor_split[0]} {professor_split[2]}",
                font=("times new roman", 20, "bold"),
            )
            self.message_label.grid(row=0, column=0, pady=10, padx=10)

            subjects = self.database_manager.get_subjects_for_professor(
                professor_id=professor_id
            )
            combobox_subjects_values = list()

            for subject in subjects:
                combobox_subjects_values.append(
                    f"{subject.name} {subject.professor_id}"
                )

            self.combobox_subjects = Combobox(
                self.FrameButtons,
                values=combobox_subjects_values,
                state="readonly",
                width=30,
            )
            self.combobox_subjects.current(0)

            self.combobox_subjects.grid(row=1, column=0, padx=10)

            return

        elif len(self.subjects) == 1:
            self.subjects.append(self.combobox_subjects.get())
            self.combobox_subjects.destroy()
            self.message_label.destroy()

            self.message_label = Label(
                self.FrameButtons,
                text="Выберите кол-во вопросов",
                font=("times new roman", 20, "bold"),
            )
            self.message_label.grid(row=0, column=0, pady=10, padx=10)

            self.combobox_questions_count = Combobox(
                self.FrameButtons, values=[3, 4, 5], state="readonly", width=30,
            )
            self.combobox_questions_count.current(0)

            self.combobox_questions_count.grid(row=1, column=0, padx=10)

            self.questions_count = 0

            return

        elif self.questions_count == 0:
            self.questions_count = int(self.combobox_questions_count.get())

            self.combobox_questions_count.destroy()
            self.message_label.destroy()

            self.is_manually_difficulty = messagebox.askyesno(
                None, "Желаете установить сложность вручную?"
            )
            # * Перемешивание для непостоянства нечётного вопроса
            SystemRandom().shuffle(self.subjects)

            if not self.is_manually_difficulty:
                self.button_create.destroy()
                self.comboboxs_difficulty = []
                questions_count_range = range(self.questions_count)
                difficulties = [
                    _.complexity for _ in self.database_manager.get_all_difficulties()
                ]
                for _ in questions_count_range:
                    combobox_difficulty = Combobox(
                        self.FrameButtons,
                        values=difficulties,
                        state="readonly",
                        width=10,
                    )
                    combobox_difficulty.current(
                        SystemRandom().randint(0, len(difficulties) - 1)
                    )
                    self.comboboxs_difficulty.append((None, combobox_difficulty,))
                self.generate_bilets()
                return  # FIXME: вызов генератора

            self.button_create.destroy()

            self.comboboxs_difficulty = []

            difficulties = [
                _.complexity for _ in self.database_manager.get_all_difficulties()
            ]
            questions_count_range = range(self.questions_count)
            for _ in questions_count_range:
                combobox_difficulty = Combobox(
                    self.FrameButtons, values=difficulties, state="readonly", width=10,
                )

                subject = (
                    self.subjects[0]
                    if _ < (self.questions_count // 2)
                    else self.subjects[1]
                )

                subject = (" ".join(subject.split()[:-1])).strip()

                message_label = Label(
                    self.FrameButtons,
                    text=f"{subject} №{_+1}",
                    font=("times new roman", 20, "bold"),
                    justify="left",
                )

                message_label.grid(row=0 + _, column=0)
                combobox_difficulty.current(0)
                combobox_difficulty.grid(row=0 + _, column=1)

                self.comboboxs_difficulty.append((message_label, combobox_difficulty,))

            self.button_create = Button(
                self.FrameButtons,
                command=self.generate_bilets,
                text="Сгенерировать",
                font=("times new roman", 15, "bold"),
                bg="yellow",
                fg="red",
            )
            self.button_create.grid(
                row=questions_count_range[-1] + 1, column=1,
            )
            self.root.geometry("400x200+0+0")
            self.root.eval("tk::PlaceWindow . center")
            return

    def login_page_init(self) -> None:
        self.Frame = Frame(self.root, bg="white")
        self.Frame.place(x=0, y=0)
        self.username = StringVar()
        self.password = StringVar()

        # *Login entry
        Entry(
            self.Frame, textvariable=self.username, bd=5, relief=GROOVE, font=("", 15),
        ).grid(row=1, column=1, padx=20, pady=10)

        # *Password entry
        Entry(
            self.Frame,
            textvariable=self.password,
            bd=5,
            relief=GROOVE,
            font=("", 15),
            show="*",
        ).grid(row=2, column=1, padx=20)

        # *Sing in button
        Button(
            self.Frame,
            command=self.sign_in,
            text="Sign In",
            width=15,
            font=("times new roman", 15, "bold"),
            bg="yellow",
            fg="red",
        ).grid(row=3, column=1, pady=10)

        # *Sing up button
        Button(
            self.Frame,
            command=self.sign_up,
            text="Sign Up",
            width=15,
            font=("times new roman", 15, "bold"),
            bg="yellow",
            fg="red",
        ).grid(row=4, column=1, pady=10)

    def sign_up(self):
        login, password = self.username.get(), self.password.get()

        result = self.database_manager.sign_up(login, md5(password))
        
        if not result:
            messagebox.showerror("Регистрация", "Ошибка регистрации!", icon="warning")
            return

        messagebox.showinfo("Регистрация", "Пользователь успешно зарегистрирован!")

    def sign_in(self):
        login, password = self.username.get(), self.password.get()
        
        is_sign_in = self.database_manager.sign_in(login, md5(password))

        if is_sign_in:
            # * Очистка фрейма, мусорных атрибутов
            self.Frame.destroy()
            del self.Frame
            del self.username
            del self.password

            # * Инициализация основной страницы
            self.main_page_init()

            return True

        messagebox.showerror(
            "Авторизация", "Логин и/или пароль неверны!", icon="warning"
        )

        return False

    def generate_bilets(self):
        from tkinter.simpledialog import askinteger
        from generator import draw, generate_a4

        config_data = config_read()

        protocol = config_data["default_protocol"]
        specialty = (config_data["default_specialty"],)
        course = config_data["default_course"]
        semester = config_data["default_semester"]
        zam_umr = config_data["default_zam_umr"]
        cicl_comission = config_data["default_cicl_comission"]

        students_count = askinteger(
            None, "Сколько необходимо билетов?", initialvalue="20"
        )

        if not students_count or students_count < 1:
            messagebox.showinfo(
                "Информация",
                "Вы не указали необхомое число студентов!\n\nПовторите попытку!",
            )
            return

        protocol = self.get_string(
            "Введите номер протокола", 410, initialvalue=protocol
        )

        specialty = self.get_string(
            "Введите номер специальности", 440, initialvalue=specialty
        )

        course = self.get_string(
            "Введите номер курса", 220, initialvalue=course, _get_int=True
        )

        semester = self.get_string(
            "Введите номер семестра", 250, initialvalue=semester, _get_int=True
        )

        zam_umr = self.get_string(
            "Введите краткое ФИО заместителя директора по УМР",
            740,
            initialvalue=zam_umr,
        )

        cicl_comission = self.get_string(
            "Введите краткое ФИО председателя цикловой комисси",
            740,
            initialvalue=cicl_comission,
        )

        tasks_difficulty = [combobox[1].get() for combobox in self.comboboxs_difficulty]

        cof = self.questions_count // 2

        first_subject_tasks, last_subject_tasks = (
            tasks_difficulty[:cof],
            tasks_difficulty[cof:],
        )

        first_subject_tasks_count = dict(Counter(first_subject_tasks))
        last_subject_tasks_count = dict(Counter(last_subject_tasks))

        rr = lambda x: list(x.split())

        subjects = list(map(rr, self.subjects))

        first_subject_has = self.database_manager.get_count_tasks(
            list(set(first_subject_tasks)), subjects[0][1], subjects[0][0]
        )
        last_subject_has = self.database_manager.get_count_tasks(
            list(set(last_subject_tasks)), subjects[1][1], subjects[1][0]
        )

        tasks_list = list()

        for comlexity in first_subject_has:
            _tasks_limit = (
                first_subject_tasks_count[comlexity.comlexity] * students_count
            )

            if comlexity.count < _tasks_limit:
                messagebox.showerror(
                    None,
                    f"Необходимо ещё {_tasks_limit-comlexity.count} заданий с сложностью '{comlexity.comlexity}' в предмете {subjects[0][0]} для генерации {students_count} билетов!",
                )
                return

            _tasks_list = self.database_manager.get_tasks(
                complexity=comlexity.comlexity,
                subject_professor_id=subjects[0][1],
                subject_name=subjects[0][0],
                limit=_tasks_limit,
            )
            tasks_list.append(_tasks_list)
        for comlexity in last_subject_has:

            _tasks_limit = (
                last_subject_tasks_count[comlexity.comlexity] * students_count
            )

            if comlexity.count < _tasks_limit:
                messagebox.showerror(
                    None,
                    f"Необходимо ещё {_tasks_limit-comlexity.count} заданий с сложностью '{comlexity.comlexity}' в предмете {subjects[0][0]} для генерации {students_count} билетов!",
                )
                return

            _tasks_list = self.database_manager.get_tasks(
                complexity=comlexity.comlexity,
                subject_professor_id=subjects[1][1],
                subject_name=subjects[1][0],
                limit=_tasks_limit,
            )
            tasks_list.append(_tasks_list)

        builet = None

        from datetime import datetime

        date = datetime.now()

        dirname = f"./results/{students_count} билетов {date.day}.{date.month}.{date.year} {date.hour}:{date.minute}:{date.second}"
        mkdir(dirname)
        students_count_range = range(students_count)
        for task_idx in students_count_range:
            builet_tasks = list()

            _subject_tasks = list(first_subject_tasks_count.items()) + list(
                last_subject_tasks_count.items()
            )

            for idx in range(len(_subject_tasks)):
                _, count = _subject_tasks[idx]
                for _ in range(count):
                    builet_tasks.append(tasks_list[idx].pop(0))

            new_builet = draw(
                str(protocol),
                str(specialty),
                str(course),
                str(semester),
                str(task_idx + 1),
                str(zam_umr),
                str(cicl_comission),
                self._professors,
                [subject[0] for subject in subjects],
                builet_tasks,
            )

            if builet:
                a4 = generate_a4(builet, new_builet)
                a4.save(f"{dirname}/билеты{task_idx}_{task_idx+1}.png")
                builet = None
                continue
            if task_idx == students_count_range[-1]:
                a4 = generate_a4(new_builet, None)
                a4.save(f"{dirname}/билет{task_idx+1}.png")
                break

            builet = new_builet

        from subprocess import Popen

        subprocess.Popen(["open", dirname])
        exit()

    def get_string(
        self, message: str, width: int, initialvalue: str, _get_int: bool = False
    ):
        def check_width(string, width):
            from PIL import ImageFont, ImageDraw, Image

            font = ImageFont.truetype("./docs/font.ttf", 60)
            draw = ImageDraw.Draw(Image.new("RGBA", (1000, 1000,)), "RGBA",)

            _width, _ = draw.textsize(string, font=font)

            return True if _width < width else False

        def get(message):
            result = askstring(None, message, initialvalue=initialvalue)
            
            if not result or not (type(result) is str):
                messagebox.showwarning(None, "Не оставляй поле пустым!")
                return get(message)

            if _get_int and not result.isdigit():
                messagebox.showwarning(None, "Введите число!")
                return get(message)

            return result

        string = get(message)

        if check_width(string, width):
            return string
        messagebox.showwarning(
            None, "Допустимый лимит длинны нарушен, попробуйте что-то покороче!"
        )
        return self.get_string(message, width, initialvalue)
Example #30
0
class Tetris():
    SHAPES = ([(0, 0), (1, 0), (0, 1), (1, 1)], [(0, 0), (1, 0), (2, 0),
                                                 (3, 0)], [(2, 0), (0, 1),
                                                           (1, 1), (2, 1)],
              [(0, 0), (0, 1), (1, 1), (2, 1)], [(0, 1), (1, 1), (1, 0),
                                                 (2, 0)], [(0, 0), (1, 0),
                                                           (1, 1),
                                                           (2, 1)], [(1, 0),
                                                                     (0, 1),
                                                                     (1, 1),
                                                                     (2, 1)])

    BOX_SIZE = 20

    GAME_WIDTH = 300
    GAME_HEIGHT = 500
    GAME_START_POINT = GAME_WIDTH / 2 / BOX_SIZE * BOX_SIZE - BOX_SIZE

    def __init__(self, predictable=False):
        self._level = 1
        self._score = 0
        self._blockcount = 0
        self.speed = 100
        self.predictable = predictable

        self.root = Tk()
        self.root.geometry("500x550")
        self.root.title('Tetris')
        self.root.bind("<Key>", self.game_control)
        self.__game_canvas()
        self.__level_score_label()
        self.__next_piece_canvas()

    def game_control(self, event):
        if event.char in ["a", "A", "\uf702"]:
            self.current_piece.move((-1, 0))
            self.update_predict()
        elif event.char in ["d", "D", "\uf703"]:
            self.current_piece.move((1, 0))
            self.update_predict()
        elif event.char in ["s", "S", "\uf701"]:
            self.hard_drop()
        elif event.char in ["w", "W", "\uf700"]:
            self.current_piece.rotate()
            self.update_predict()

    def new_game(self):
        self.level = 1
        self.score = 0
        self.blockcount = 0
        self.speed = 300

        self.canvas.delete("all")
        self.next_canvas.delete("all")

        self.__draw_canvas_frame()
        self.__draw_next_canvas_frame()

        self.current_piece = None
        self.next_piece = None

        self.game_board = [[0] * ((Tetris.GAME_WIDTH - 20) // Tetris.BOX_SIZE)\
                           for _ in range(Tetris.GAME_HEIGHT // Tetris.BOX_SIZE)]

        self.update_piece()

    def update_piece(self):
        if not self.next_piece:
            self.next_piece = Piece(self.next_canvas, (20, 20))

        self.current_piece = Piece(self.canvas, (Tetris.GAME_START_POINT, 0),
                                   self.next_piece.shape)
        self.next_canvas.delete("all")
        self.__draw_next_canvas_frame()
        self.next_piece = Piece(self.next_canvas, (20, 20))
        self.update_predict()

    def start(self):
        self.new_game()
        self.root.after(self.speed, None)
        self.drop()
        self.root.mainloop()

    def drop(self):
        if not self.current_piece.move((0, 1)):
            self.current_piece.remove_predicts()
            self.completed_lines()
            self.game_board = self.canvas.game_board()
            self.update_piece()

            if self.is_game_over():
                return
            else:
                self._blockcount += 1
                self.score += 1

        self.root.after(self.speed, self.drop)

    def hard_drop(self):
        self.current_piece.move(
            self.current_piece.predict_movement(self.game_board))

    def update_predict(self):
        if self.predictable:
            self.current_piece.predict_drop(self.game_board)

    def update_status(self):
        self.status_var.set(f"Level: {self.level}, Score: {self.score}")
        self.status.update()

    def is_game_over(self):
        if not self.current_piece.move((0, 1)):

            self.play_again_btn = Button(self.root,
                                         text="Play Again",
                                         command=self.play_again)
            self.quit_btn = Button(self.root, text="Quit", command=self.quit)
            self.play_again_btn.place(x=Tetris.GAME_WIDTH + 10,
                                      y=200,
                                      width=100,
                                      height=25)
            self.quit_btn.place(x=Tetris.GAME_WIDTH + 10,
                                y=300,
                                width=100,
                                height=25)
            return True
        return False

    def play_again(self):
        self.play_again_btn.destroy()
        self.quit_btn.destroy()
        self.start()

    def quit(self):
        self.root.quit()

    def completed_lines(self):
        y_coords = [
            self.canvas.coords(box)[3] for box in self.current_piece.boxes
        ]
        completed_line = self.canvas.completed_lines(y_coords)
        if completed_line == 1:
            self.score += 400
        elif completed_line == 2:
            self.score += 1000
        elif completed_line == 3:
            self.score += 3000
        elif completed_line >= 4:
            self.score += 12000

    def __game_canvas(self):
        self.canvas = GameCanvas(self.root,
                                 width=Tetris.GAME_WIDTH,
                                 height=Tetris.GAME_HEIGHT)
        self.canvas.pack(padx=5, pady=10, side=LEFT)

    def __level_score_label(self):
        self.status_var = StringVar()
        self.status = Label(self.root,
                            textvariable=self.status_var,
                            font=("Helvetica", 10, "bold"))

    def __next_piece_canvas(self):
        self.next_canvas = Canvas(self.root, width=100, height=100)
        self.next_canvas.pack(padx=5, pady=10)

    def __draw_canvas_frame(self):
        self.canvas.create_line(10,
                                0,
                                10,
                                self.GAME_HEIGHT,
                                fill="black",
                                tags="line")
        self.canvas.create_line(self.GAME_WIDTH - 10,
                                0,
                                self.GAME_WIDTH - 10,
                                self.GAME_HEIGHT,
                                fill="black",
                                tags="line")
        self.canvas.create_line(10,
                                self.GAME_HEIGHT,
                                self.GAME_WIDTH - 10,
                                self.GAME_HEIGHT,
                                fill="black",
                                tags="line")

    def __draw_next_canvas_frame(self):
        self.next_canvas.create_rectangle(10, 10, 90, 90, tags="frame")

    #set & get
    def __get_level(self):
        return self._level

    def __set_level(self, level):
        self.speed = 500 - (level - 1) * 1
        self._level = level
        self.update_status()

    def __get_score(self):
        return self._score

    def __set_score(self, score):
        self._score = score
        self.update_status()

    def __get_blockcount(self):
        return self._blockcount

    def __set_blockcount(self, blockcount):
        self.level = blockcount // 5 + 1
        self._blockcount = blockcount

    level = property(__get_level, __set_level)
    score = property(__get_score, __set_score)
    blockcount = property(__get_blockcount, __set_blockcount)
Example #31
0
class VotingGUI:
    def __init__(self, master):  # constructor
        # master is variable for window that is created in starting of program
        self.master = master  # matster is storing window object in this class
        master.title("University of Greenwich Voting System")
        master.geometry('800x600')  # dimension
        # Start :  Menu related Configuration
        self.menubar = Menu(master)  # menu
        master.config(menu=self.menubar, bg='white', borderwidth=1)
        master.configure(background='white')
        # --menu created --
        self.menubar.add_command(label="Login with UID and password",
                                 command=self.UserLoginForm)  # A1 & A2
        self.menubar.add_command(label="Cast votes", command=self.CastVotes)
        self.menubar.add_command(label="Results", command=self.Results)
        self.menubar.add_command(label="Logout", command=self.Logout)
        # End :  Menu related Configuration
        self.Authe = 'false'  # if user is authenticated then its value would be TRUE
        self.WelcomeLabel = None
        self.UIDLabel = None
        self.PWDLabel = None
        self.UIDInput = None
        self.PWDInput = None
        self.Login = None  # UserName
        self.LoginFormDisplayed = 'false'  # if it is true then Login form is displayed on UI
        self.candidateList = []  # python list All candidates
        self.VotingPins = {}  # dict of all Positions and number of candidates
        self.CandidatePinDict = {
        }  # CandidatePositionDict stores Poistion and List Of employee contesting for that position
        self.LoadCandidates()  # A3 : Load candidate from text file
        self.voterList = []  # List of Voters
        self.listofLabels_Prf = {
        }  # List of candidate and given preference by voter
        self.voteObjectList = []  # list of vote Class Object
        self.WinnerCandidate = None
        self.winnerPinList = []
        self.DisplayedItem = []
        self.VoteDoneList = []

    def Display(self):  # Done by Shahzeb and Tejal A6
        self.removeVoteCastUI()  # Clean UI before adding element on Window
        xx = 20
        yy = 40
        hh = 20
        cc = 0
        aa = 0

        for key in self.winnerPinList:
            if key in self.DisplayedItem:
                continue
            else:
                self.DisplayedItem.append(key)
                totalVote = 0
                label = Label(
                    self.master,
                    text=
                    "************************************************************************",
                    bg='white')
                label.place(x=xx + 40, y=yy, width=230, height=hh)
                self.listofLabels_Prf[label] = ""
                yy = yy + hh
                label = Label(self.master,
                              text="Position : " + key.PinName,
                              bg='white')
                self.listofLabels_Prf[label] = ""
                label.place(x=xx + 40, y=yy, width=130, height=hh)
                yy = yy + hh
                label = Label(
                    self.master,
                    text=
                    "************************************************************************",
                    bg='white')
                self.listofLabels_Prf[label] = ""
                label.place(x=xx + 40, y=yy, width=230, height=hh)
                yy = yy + hh
                label = Label(self.master, text="Candidate ", bg='white')
                self.listofLabels_Prf[label] = ""
                label.place(x=xx + 40, y=yy, width=130, height=hh)
                cc = yy
                yy = yy + hh
                aa = xx
                for x in range(self.VotingPins[key.PinName]):
                    xx = xx + 130
                    label = Label(self.master,
                                  text="Preference " + str(x + 1),
                                  bg='white')
                    self.listofLabels_Prf[label] = ""
                    label.place(x=xx + 40, y=cc, width=130, height=hh)
                for c in self.candidateList:
                    if c.Pin == key.PinName:
                        xx = aa + 40
                        cc = cc + hh
                        label = Label(self.master,
                                      text=c.candi_name,
                                      bg='white')
                        self.listofLabels_Prf[label] = ""
                        label.place(x=xx, y=cc, width=130, height=hh)
                        for x in range(self.VotingPins[key.PinName]):
                            xx = xx + 130
                            print(c.votePrf)
                            if str(x + 1) in c.votePrf:
                                votecount = c.votePrf[str(x + 1)]
                                totalVote = totalVote + votecount
                            else:
                                votecount = 0
                            label = Label(self.master,
                                          text=votecount,
                                          bg='white')
                            self.listofLabels_Prf[label] = ""
                            label.place(x=xx + 40, y=cc, width=130, height=hh)

                label = Label(
                    self.master,
                    text=
                    "**********************************************************************",
                    bg='white')
                self.listofLabels_Prf[label] = ""
                cc = cc + hh
                label.place(x=60, y=cc, width=230, height=hh)
                label = Label(self.master,
                              text="Winner :" + key.WinnerCandidateName,
                              bg='white')
                self.listofLabels_Prf[label] = ""
                cc = cc + hh
                label.place(x=60, y=cc, width=130, height=hh)
                label = Label(self.master,
                              text="Vote Received :" + str(key.voteReceived),
                              bg='white')
                self.listofLabels_Prf[label] = ""
                cc = cc + hh
                label.place(x=60, y=cc, width=130, height=hh)
                label = Label(self.master,
                              text="Total Vote cast :" +
                              str(len(self.voterList)),
                              bg='white')
                self.listofLabels_Prf[label] = ""
                cc = cc + hh
                label.place(x=60, y=cc, width=130, height=hh)
                self.validate = Button(self.master,
                                       text="Next",
                                       command=self.Display,
                                       bg='green',
                                       fg='white')
                self.validate.place(x=80, y=cc + 20, width=100, height=25)
                break

    def Results(self):
        self.clearWindow()  # clear window
        self.CountVotes()  # A5 count vote and do manipulation
        self.Display()  # A6

    def Logout(self):
        self.removeVoteCastUI()
        self.CandidatePinDict.clear()
        self.listofLabels_Prf.clear()
        self.clearWindow()
        self.Authe = 'false'
        self.Login = None
        self.LoginFormDisplayed = 'false'
        print(self.voterList)

    # Done by Mohammed A3 -Load All candidates from GSUCandidates.txt
    def LoadCandidates(self):  # A3 -Load All candidates from GSUCandidates.txt
        self.clearWindow()
        self.msg = Label(self.master,
                         text="Welcome to UoG Voting System",
                         font=('courier', 20, 'bold'),
                         bg='white')
        self.msg.place(x=25, y=40, width=800, height=50)
        StudentVoters = open('GSUCandidates.txt', 'r')
        Lines = StudentVoters.readlines()
        for line in Lines:
            candi_name = " ".join(line.strip().split(" ")[1:])
            postn = line.strip().split(" ")[0].strip()
            recordfound = 'false'
            if len(self.candidateList) > 0:
                for c in self.candidateList:  # validate One candidate for one position
                    if c.candi_name == candi_name:
                        recordfound = 'true'
                if recordfound != 'true':
                    self.candidateList.append(candidates(candi_name, postn))
                else:
                    recordfound = 'false'

            else:
                self.candidateList.append(candidates(candi_name, postn))
                pass
            pass

        # returns candidate position and takes input as candidate name

    def findPinofCandidate(self, candi_name):
        for key in self.CandidatePinDict:
            if candi_name in self.CandidatePinDict[key]:
                return key

    # Done by Yulin, Tejal, Shahzeb and Mohammed A4 Cast votes
    def CastVotes(self):  # A.4
        if self.Authe != 'false':
            self.removeVoteCastUI()  # Clean UI before adding element on Window
            self.CandidatePinDict.clear()  # clean before initi
            self.clearWindow()  # Clear Window
            # CandidatePositionDict stores position and List Of employee contesting for that position
            for c in self.candidateList:
                if c.Pin in self.CandidatePinDict:
                    self.CandidatePinDict[c.Pin].append(c.candi_name)
                    pass
                else:
                    l = []
                    l.append(c.candi_name)
                    self.CandidatePinDict[c.Pin] = l

                    # Display list of candidate
            xx = 20
            yy = 40
            hh = 20
            byy = 0
            counter = 0
            for key in self.CandidatePinDict:
                label = Label(self.master,
                              text="For " + key,
                              bg="sea green",
                              fg='white',
                              font=('courier', 10, 'bold'))
                label.place(x=xx, y=yy, width=170, height=hh)
                yy = yy + hh
                self.listofLabels_Prf[label] = ""
                for c in self.CandidatePinDict[key]:
                    label = Label(self.master, text=c, bg="pale green")
                    label.place(x=xx, y=yy, width=120, height=hh)
                    Input = Entry(self.master, validate="key")
                    Input['validatecommand'] = (Input.register(self.testVal),
                                                '%P', '%d')
                    Input.place(x=xx + 121, y=yy, width=50, height=hh)
                    self.listofLabels_Prf[label] = Input
                    yy = yy + hh
                    counter = counter + 1
                self.VotingPins[key] = counter
                counter = 0
                xx = xx + 180
                if byy < yy:
                    byy = yy
                yy = 40
            self.validate = Button(self.master,
                                   text="Validate & Submit",
                                   command=self.ValidateVote,
                                   bg="green",
                                   fg='white')
            self.validate.place(x=xx, y=byy + 20, width=120, height=25)

        else:
            messagebox.showinfo("Error",
                                "Please first Login with UID and password.")
            self.removeVoteCastUI()  # Clean UI before adding element on Window
            self.UserLoginForm()

        pass

    # Done by Shahzeb, Tejal, Yulin and Mohammed: part of A4 - After voter user click Validate & Submit
    # Done by Shahzeb, Tejal, Yulin and Mohammed: part of A4 - It will validate preferences and validate duplicate, uniquness and other criteria
    # Done by Shahzeb, Tejal, Yulin and Mohammed: part of A4 - after validation it will store vote in votes.txt
    def ValidateVote(self):
        l = []
        for key in self.listofLabels_Prf:
            if not isinstance(self.listofLabels_Prf[key], str):
                maxCount = self.VotingPins[self.findPinofCandidate(
                    key.cget("text"))]
                if self.listofLabels_Prf[key].get() == "":
                    messagebox.showinfo("Error",
                                        key.cget("text") + " No preference?")
                    return ""
                if int(self.listofLabels_Prf[key].get()) > maxCount:
                    messagebox.showinfo(
                        "Error",
                        key.cget("text") +
                        " Preference is not correct. it should be less then or equal to  "
                        + str(maxCount))
                    return ""
                if self.listofLabels_Prf[key].get() in l:
                    messagebox.showinfo(
                        "Error",
                        key.cget("text") + " duplicate Preference issue.")
                    return ""
                else:
                    l.append(self.listofLabels_Prf[key].get())
            else:
                l = []
        self.CreateVotes()
        self.removeVoteCastUI()
        self.Logout()

    # Done by Tejal and Shahzeb A 5 : Function to count votes as per logic
    def CountVotes(self):  # A.5
        for candidate in self.candidateList:
            candidate.reSetCount()  # Reset Before doing reCount
        for votes in self.voteObjectList:
            for candidate in self.candidateList:
                if candidate.candi_name == votes.CandidateName:
                    candidate.updateVoteForCandidate(
                        votes.Preference
                    )  # Update Preference and Count in each Candidate Object
                    print(candidate.votePrf)
        self.Winner()  # A.6

    # function to get candidate name based on position and preference
    def getCandidatename(self, winnerScore, Prf, post):
        for cand in self.candidateList:
            if str(Prf) in cand.votePrf:
                if cand.votePrf[str(Prf)] == winnerScore and cand.Pin == post:
                    return cand.candi_name
                # Done by Shahzeb and Tejal: part of A 5 : Calculate winner for each position

    def Winner(self):
        winnerCandidateScoreList = []
        self.winnerPinList.clear()
        winnerScore = 0
        preference = 0
        for post in self.VotingPins:  # All position and count of candidates on position
            print("Preference for post-", post, " is ", self.VotingPins[post])
            winnerCandidateScoreList.clear()
            for Prf in range(self.VotingPins[post]
                             ):  # loop through number of preference
                for cand in self.candidateList:
                    if cand.Pin == post:
                        if str(Prf + 1) in cand.votePrf:
                            winnerCandidateScoreList.append(
                                cand.votePrf[str(Prf + 1)])
                winnerCandidateScoreList.sort(
                    reverse=True)  # Sort List in Descending Order
                print("winnerCandidateScoreList :", winnerCandidateScoreList,
                      Prf + 1)
                if len(winnerCandidateScoreList) > 1:
                    a, b, *_ = winnerCandidateScoreList
                    if a > b and a != b:
                        winnerScore = a
                        preference = Prf + 1
                        break
                else:
                    winnerScore, *_ = winnerCandidateScoreList
                    preference = Prf + 1
                    break

            self.winnerPinList.append(
                winnerPin(post,
                          self.getCandidatename(winnerScore, preference, post),
                          winnerScore))

    # Done by Shahzeb, Tejal, Yulin and Mohammed: part of A4 : Create vote object for after submit button

    def CreateVotes(self):
        for key in self.listofLabels_Prf:
            if not isinstance(self.listofLabels_Prf[key], str):
                self.voteObjectList.append(
                    votes(self.Login, key.cget("text"),
                          self.listofLabels_Prf[key].get()))
        self.writeVotetofile()  # store in file
        messagebox.showinfo(
            "Done",
            "Your vote has been written in file " + os.getcwd() + "\Votes.txt")

        pass

    # Done by Yulin: part of A2 : method to show welcome message
    def welcomeUser(self, u):  # Invoked to show  welcome Caption after login
        self.clearWindow()  # UI is clean
        # now it is adding New labals
        self.WelcomeLabel = Label(self.master,
                                  text=u + "! You are Welcome.",
                                  font=('courier', 15, 'bold'),
                                  bg='white')
        self.WelcomeLabel.place(x=30, y=40, width=920, height=25)
        pass

    # Done by Yulin: part of A2 : method  to remove UI component
    def removeVoteCastUI(self):
        if len(self.listofLabels_Prf) > 0:
            self.validate.destroy()
        for key in self.listofLabels_Prf:
            if key:
                key.destroy()
                if not isinstance(self.listofLabels_Prf[key], str):
                    self.listofLabels_Prf[key].destroy()

    # Done by Yulin: part of A2 : remove Login/password/login button from UI and show welcome message
    def clearWindow(self):
        print("clearWindow")
        if self.UIDLabel:
            self.UIDLabel.destroy()
        if self.PWDLabel:
            self.PWDLabel.destroy()
        if self.UIDInput:
            self.UIDInput.destroy()
        if self.PWDInput:
            self.PWDInput.destroy()
        if self.Login:
            self.Login.destroy()
        if self.WelcomeLabel:
            self.WelcomeLabel.destroy()

    # Done by Shahzeb, Tejal, Yulin and Mohammed: part of A4 - Write vote in votes.txt. It stores votes.txt in directory
    def writeVotetofile(self):
        f = open('Votes.txt', 'w')

        for v in self.voteObjectList:
            s = self.findPinofCandidate(
                v.CandidateName) + " " + v.CandidateName + " " + v.Preference
            f.write(s + '\n')
        f.close()

    # part of A2 this ValidateUser method will internally call from UserLoginForm method to validate if user is valid for voting
    # part of A2 - Validates Login user after click login button and it will be invoked from UserLoginForm method
    # part of A2 it will cross check login user/ password from 'StudentVoters.txt' file
    # part of A2 - if user login / password is correct then it will show welcome message by calling welcomeUser method
    def ValidateUser(self):
        if self.UIDInput.get() not in self.VoteDoneList:
            self.VoteDoneList.append(self.UIDInput.get())
            if self.UIDInput.get() != "" and self.PWDInput.get() != "":
                # Read StudentVoters.txt readlines()
                StudentVoters = open('StudentVoters.txt', 'r')
                Lines = StudentVoters.readlines()
                for line in Lines:
                    u = line.strip().split(" ")[0].strip()
                    p = line.strip().split(" ")[1].strip()
                    if u == self.UIDInput.get():
                        if p == self.PWDInput.get():
                            self.Authe = 'true'
                            break
                if self.Authe == 'false':
                    messagebox.showinfo("Error",
                                        "Person is not eligible for vote.")
                else:
                    self.welcomeUser(
                        u
                    )  # A2 method to show welcome message for logged in user
                    self.voterList.append(voters(u))

            else:
                messagebox.showinfo("Error", "Please Enter UID / Password")
        else:
            messagebox.showinfo("Error", "You have already voted.")
            self.LoginFormDisplayed = 'false'
            self.clearWindow(
            )  # Clears UI element of user Id/Password/Login button

    # this testVal method is to validate if user has input preference of candidate  must be digit
    def testVal(self, inStr, acttyp):
        if acttyp == '1':  # insert
            if not inStr.isdigit():
                return False

        return True

    # Done by Shahzeb, Tejal, Yulin and Mohammed: this is first method to show login password and part of A1 & A2
    # It will be invoked when user will click Login/Password menu
    # this method will internally call Function ValidateUser to validate if user is valid for voting
    def UserLoginForm(self):  # A1  & A2
        if self.LoginFormDisplayed == 'false':
            self.LoginFormDisplayed = 'true'
            if self.Authe == 'false':
                self.msg.destroy()
                self.UIDLabel = Label(self.master, text="UID :")
                self.UIDLabel.place(x=20, y=40, width=120, height=25)
                self.UIDInput = Entry(self.master)
                self.UIDInput.place(x=141, y=40, width=120, height=25)
                self.PWDLabel = Label(self.master, text="Password :"******"Login",
                    command=self.ValidateUser,
                    bg="green",
                    fg='white'
                )  # Login Button click will call ValidateUser user method
                self.Login.place(x=200, y=100, width=60, height=25)
            else:
                messagebox.showinfo("Warning",
                                    "You are already authenticated.")
            value = 'default text'
Example #32
0
File: bong.py Project: chboo1/games
class Bong():
    def __init__(self, width, height):
        # begin
        self.width = width
        self.height = height
        self.root = Tk()
        self.root.title('Bong')
        self.c = Canvas(self.root, width=width, height=height)
        self.root.bind('<Return>', self.kr)
        self.root.bind('<space>', self.space)
        self.dir = Direction(randint(1, 4))
        self.mouv = self.dir
        self.c.pack()
        self.start = time()
        self.freeze = None
        self.but = Button(self.root, text='PLAY', command=self.main)
        self.but.pack()
        self.but2 = None
        self.root.mainloop()
        # end

    def motion(self, event):
        # begin
        self.x, self.y = event.x, event.y
        firstx = self.x - 50
        secondx = self.x + 50
        self.platform_x = (firstx, secondx)
        self.c.coords(self.rect, firstx, self.platform_y[0], secondx,
                      self.platform_y[1])
        self.liste_bin = []
# end

    def space(self, event):
        self.freeze = True
        self.root.unbind('<space>')
        sleep(0.1)
        self.root.bind('<space>', self.unspace)
        self.c.itemconfig(self.txt, text='Paused.')
        self.but2 = Button(self.root, text='Quit', command=self.kr)
        self.but2.pack()

    def unspace(self, event):
        self.freeze = False
        self.root.after(0, self.bouger_balle)
        self.root.unbind('<space>')
        sleep(0.1)
        self.root.bind('<space>', self.space)
        self.c.itemconfig(self.txt, text='Space to pause.')
        self.but2.destroy()

    def kr(self, event=None):
        # b
        self.start = time()
        self.root.destroy()
        # e

    def touche_platforme(self, coords):
        x1, y1, x2, y2 = map(int, coords)
        if y2 < self.platform_y[0] or y2 > self.platform_y[1]:
            return False

        milieu = (x1 + x2) / 2
        if milieu < self.platform_x[0] or milieu > self.platform_x[1]:
            return False

        return True

    def quel_mur(self, coords):
        # b
        self.coords = coords
        if self.coords[1] <= 0.0 and self.coords[2] >= self.width:
            return [Mur.HAUT, Mur.DROITE]
        elif self.coords[1] <= 0.0 and self.coords[0] <= 0.0:
            return [Mur.HAUT, Mur.GAUCHE]
        elif self.coords[0] <= 0.0:
            return [Mur.GAUCHE]
        elif self.coords[1] <= 0.0:
            return [Mur.HAUT]
        elif self.coords[2] >= self.width:
            return [Mur.DROITE]
        elif self.coords[3] >= self.height:
            return [Mur.BAS]
        elif self.touche_platforme(coords):
            return [Mur.PLAT]
        # e

    def bouger_balle(self):
        # b
        if not self.freeze:
            try:
                mouv_x = 5 if self.mouv.droite() else -5
                mouv_y = -5 if self.mouv.haut() else 5
                self.c.move(self.balle, mouv_x, mouv_y)
                coords = self.c.coords(self.balle)
                murs = self.quel_mur(coords)
                if murs:
                    nouv_dir = sum([mur.value for mur in murs])
                    self.mouv = Direction(self.mouv.value + nouv_dir)
                if murs == [Mur.BAS]:
                    raise ZeroDivisionError
                else:
                    self.root.after(10, self.bouger_balle)

            except ValueError:
                self.root.after(10, self.bouger_balle)
            except ZeroDivisionError:
                self.c.delete(self.balle)
                self.c.delete(self.rect)
                self.c.delete(self.txt)
                self.but = Button(self.root, text='PLAY', command=self.main)
                self.but.pack()


# e

    def main(self):

        # b
        self.root.quit()
        self.root.after(2000, self.bouger_balle)
        self.but.destroy()
        self.root.bind('<Motion>', self.motion)
        self.balle = self.c.create_oval((self.width / 2) - 50,
                                        200, (self.width / 2) + 50,
                                        300,
                                        fill='blue',
                                        outline='blue')
        self.platform_x = ((self.width / 2) - 12, (self.width / 2) + 13)
        self.platform_y = (450, 462)
        self.txt = self.c.create_text(400,
                                      10,
                                      font=('Helvetica', 18),
                                      text='Space to pause.')
        self.rect = self.c.create_rectangle(self.platform_x[0],
                                            self.platform_y[0],
                                            self.platform_x[1],
                                            self.platform_y[1],
                                            fill='black')
        self.root.mainloop()
Example #33
0
class RootWindow:
    """
    Class used to manage the main gui window
    """
    def __init__(self, func):
        # Standard configuration
        self.root_window = Tk()
        self.root_window.title("TAXtoPEC - CherryNpl")
        self.root_window.geometry("380x150")

        # If some key was missing from environment it just shows an error code
        if func == 'MISSING_KEY':
            self.root_window.geometry("450x150")
            Label(
                self.root_window,
                text=
                "Environment variables in the .env file are missing or wrong",
                fg="red",
                font=("arial", 12)).grid(row=1)
            self.root_window.mainloop()

        # Creation of all the needed labels and input
        else:
            self.searching_label = Label(self.root_window,
                                         text="Searching...",
                                         font=("arial", 12))
            self.insert_label = Label(
                self.root_window,
                text="Insert the TAX code of the company: ",
                font=("arial", 12))
            self.error_label = Label(self.root_window,
                                     text="You should enter a valid TAX Code",
                                     fg="red",
                                     font=("arial", 12))
            self.found = False

            self.tax_input = Entry(self.root_window)
            self.tax_input.bind('<Return>', lambda x: self.thread_runner(func))

            self.next_button = Button(self.root_window,
                                      text="Start",
                                      command=self.search)
            self.submit_button = Button(
                self.root_window,
                text="Search",
                command=lambda: self.thread_runner(func))
            self.start()

    def start(self):
        """ Creates first interface"""
        Label(self.root_window,
              text="Welcome to CherryNpl PEC scraper",
              font=("arial", 16, "bold")).grid(row=1)
        self.next_button.grid(row=2)
        self.root_window.mainloop()

    def search(self):
        """ Creates the searching interface where to put the TAX code"""
        self.next_button.destroy()
        self.insert_label.grid(row=2)
        self.tax_input.grid(row=3)
        self.submit_button.grid(row=4)

        self.tax_input.focus_set()

    def validate_input(self, func, code):
        """ Checks if the TAX code is valid and call the func passed in the parameter
            (usually the scraping function)"""
        if len(code.get()) == 11:
            # Hides the interface to write a simple "Searching" animation
            self.error_label.grid_forget()
            self.insert_label.grid_forget()
            self.tax_input.grid_forget()
            self.submit_button.grid_forget()

            self.searching_label.grid(row=5)
            self.found = False
            text = Thread(target=self.searching_text,
                          args=(self.searching_label, ))
            text.start()

            # If some key was deleted or wrong shows the error message
            if func == 'MISSING_KEY':
                self.missing_var()
            # Actual computing of the code
            pec = func(code.get())
            if pec not in (0, 'MISSING_KEY'):
                # No errors path
                print(pec)
                self.found = True
                self.searching_label['text'] = 'TAX: ' + code.get(
                ) + ', PEC: ' + pec
            elif pec == 0:
                # No PEC found, probably the TAX was wrong
                self.searching_label.grid_forget()
                self.error_label.grid(row=5)
            else:
                # If some key was deleted or wrong shows the error message
                self.missing_var()
                return
        else:
            # The code was invalid
            self.searching_label.grid_forget()
            self.error_label.grid(row=5)

        self.tax_input.delete(0, END)
        # Recreate the input interface
        self.search()

    def missing_var(self):
        """ Function that stop the computation and shows an error about environment variables"""
        self.root_window.geometry("450x150")
        self.searching_label.grid_forget()
        Label(
            self.root_window,
            text="Environment variables in the .env file are missing or wrong",
            fg="red",
            font=("arial", 12)).grid(row=2)

    def thread_runner(self, func):
        """ Simple thread used to compute the TAX code multiple times without stopping the interface"""
        Thread(target=self.validate_input, args=(func, self.tax_input)).start()

    def searching_text(self, label):
        """ Simple text animation """
        while not self.found:
            if label['text'] == 'Searching':
                label['text'] = 'Searching.'
            elif label['text'] == 'Searching.':
                label['text'] = 'Searching..'
            elif label['text'] == 'Searching..':
                label['text'] = 'Searching...'
            elif label['text'] == 'Searching...':
                label['text'] = 'Searching'
            sleep(1)
Example #34
0
class Menu(Tk):
    """Create graphic menu"""
    def __init__(self, lines):  # ввод переменных с которыми будем работать
        super().__init__()
        self.geometry('600x360+560+240')  # разрешение открывающегося окна
        self.resizable(False, False)  # запрещаем изменять размер окна
        self.config(bg='#AFEEEE')  # цвет фона
        self.title('Программа для заучивания слов иностранного языка'
                   )  # заголовок окна
        self.lines = lines
        self.number = 0
        self.ent = 0
        self.view_in_menu = 0
        self.lab1 = Label(self)  # окно для вывода текста
        self.lab1.config(
            text='Программа\n для заучивания слов\n иностранного языка\n',
            font=('Arial', 21, 'bold'),
            bg='#AFEEEE')  # настройка внешнего вида
        self.lab1.pack()  # зафиксировали на окне
        self.lab2 = Label(self)  # окно для вывода текста
        self.lab2.config(text='Введите кол-во слов (от 1 до 50)',
                         fg='red',
                         font=5,
                         bg='#AFEEEE')  # настройка внешнего вида
        self.lab2.pack()  # зафиксировали на окне
        self.ent = Entry(self, bd=4)  # окно для ввода текста
        self.ent.pack()  # зафиксировали на окне
        self.start = Button(self,
                            text='Начать тестирование',
                            command=self.validation_of_input)  # кнопка
        self.start.pack()  # зафиксировали на окне
        self.view_in_menu = Button(self,
                                   text='Показать все слова',
                                   command=self.view_words)  # кнопка
        self.view_in_menu.pack()  # зафиксировали на окне

    def validation_of_input(self):  # проверка правильности ввода
        """Input 1-50"""
        check = self.ent.get()
        if check.isdigit() and check.count(' ') == 0:
            self.number = int(check)
            if self.number > 50 or self.number < 1:
                self.ent.delete(0, 'end')  # стераем текст
            elif 1 <= self.number <= 50:
                self.destroy()  # удаляем окно
                root = Program(self.number, self.lines)  # запускаем graphic.py
                root.mainloop()
        else:
            self.ent.delete(0, 'end')  # стераем текст

    def view_words(self):
        """view words in file txt"""
        self.view_in_menu.destroy()
        lab = Label(self)  # окно для вывода текста
        lab.config(text='\nВсе слова:',
                   bg='#AFEEEE')  # настройка внешнего вида
        lab.pack()
        new_tx = 0
        new_tx = Text(
            width=37,
            height=5,
        )
        new_tx.pack()
        for i in self.lines:
            new_tx.insert(END, i + '\n')  # добавили в конец
        new_tx.config(state=DISABLED)
class Tetris():
    SHAPES = (
        [(0, 0), (1, 0), (2, 0), (3, 0)],  # I
        [(2, 0), (0, 1), (1, 1), (2, 1)],  # L
        [(0, 0), (0, 1), (1, 1), (2, 1)],  # J
        [(1, 0), (0, 1), (1, 1), (2, 1)],  # T
        [(0, 0), (1, 0), (1, 1), (2, 1)],  # Z
        [(0, 1), (1, 1), (1, 0), (2, 0)],  # N
        [(0, 0), (1, 0), (0, 1), (1, 1)])  # O

    BOX_SIZE = 20

    GAME_WIDTH = 220
    GAME_HEIGHT = 500
    GAME_START_POINT = 130

    #GAME_WIDTH / 2 / BOX_SIZE * BOX_SIZE - BOX_SIZE

    def __init__(self, predictable=False):
        self._level = 1
        self._score = 0
        self._blockcount = 0
        self.speed = 200
        self.predictable = predictable

        self.root = Tk()
        self.root.geometry("500x550")
        self.root.title('Tetris')
        self.root.bind("<Key>", self.game_control)

        self.__level_score_label()
        self.__game_canvas()
        self.__next_piece_canvas()
        self.__hold_piece_canvas()
        self.first = True

    def fill_six(self):
        for y in range(25):
            for x in range(6):
                self.canvas.create_rectangle(
                    x * Tetris.BOX_SIZE + 10,
                    y * Tetris.BOX_SIZE,
                    x * Tetris.BOX_SIZE + Tetris.BOX_SIZE + 10,
                    y * Tetris.BOX_SIZE + Tetris.BOX_SIZE,
                    fill="gray",
                    tags="game")
        for x, y in [(6, 24), (6, 23), (7, 24)]:
            self.canvas.create_rectangle(x * Tetris.BOX_SIZE + 10,
                                         y * Tetris.BOX_SIZE,
                                         x * Tetris.BOX_SIZE +
                                         Tetris.BOX_SIZE + 10,
                                         y * Tetris.BOX_SIZE + Tetris.BOX_SIZE,
                                         fill="gray",
                                         tags="game")

        self.canvas.pack()

    def auto_control(self, event):
        if event == 0:  #rotate
            self.current_piece.rotate()
            self.update_predict()
        elif event == 1:  #move right
            self.current_piece.move((1, 0))
            self.update_predict()
        elif event == 2:  #move left
            self.current_piece.move((-1, 0))
            self.update_predict()
        elif event == 3:  #drop
            self.hard_drop()

        elif event == 4:  #hold
            self.hold()
            self.update_predict()

    def game_control(self, event):
        if event.keysym in ["a", "Left", "\uf702"]:
            self.auto_control(2)
        elif event.keysym in ["d", "Right", "\uf703"]:
            self.auto_control(1)
        elif event.keysym in ["s", "space", "\uf701"]:
            self.auto_control(3)
        elif event.keysym in ["w", "Up", "\uf700"]:
            self.auto_control(0)
        elif event.keysym in ["c", "C"]:
            self.auto_control(4)

    def new_game(self):
        self.level = 1
        self.score = 0
        self.blockcount = 0
        self.speed = 200
        self.first = True
        self.canvas.delete("all")
        self.next_canvas.delete("all")
        self.hold_canvas.delete("all")

        self.__draw_canvas_frame()
        self.__draw_hold_canvas_frame()
        self.__draw_next_canvas_frame()

        self.current_piece = None
        self.next_piece = None
        self.hold_piece = None

        self.game_board = [
            0 for _ in range(Tetris.GAME_HEIGHT // Tetris.BOX_SIZE)
        ]
        for i in range(len(self.game_board)):
            self.game_board[i] = [0 for _ in range(10)]


#         [[0] * ((Tetris.GAME_WIDTH - 20) // Tetris.BOX_SIZE)\
#                            for _ in range(Tetris.GAME_HEIGHT // Tetris.BOX_SIZE)]
        self.update_piece()

    def hold(self):
        self.hold_canvas.delete("all")
        if self.hold_piece == None:
            self.next_canvas.delete("all")
            self.hold_piece = self.current_piece
            self.current_piece.erase()
            self.current_piece = Piece(self.canvas,
                                       (Tetris.GAME_START_POINT, 0),
                                       self.next_piece.shape)
            self.next_piece = Piece(self.next_canvas, (20, 20))

        else:
            temp = self.current_piece
            self.current_piece.erase()
            self.current_piece = Piece(self.canvas,
                                       (Tetris.GAME_START_POINT, 0),
                                       self.hold_piece.shape)
            self.hold_piece = temp

        self.hold_piece = Piece(self.hold_canvas, (20, 20),
                                self.hold_piece.shape)

        self.__draw_hold_canvas_frame()
        self.__draw_next_canvas_frame()

    def autodrop(self):
        self.auto_control(3)

    def play_sound(self):
        if queue_count < 3:
            combo0.play()
        elif queue_count == 3:
            combo1.play()
        elif queue_count == 4:
            combo2.play()
        elif queue_count == 5:
            combo3.play()
        elif queue_count == 6:
            combo4.play()
        elif queue_count == 7:
            combo5.play()
        elif queue_count == 8:
            combo6.play()
        else:
            combo7.play()

    def update_piece(self):
        global actionlist_right, actionlist_rotate

        if len(actionlist_right) <= queue_count - 1:
            self.end_game()
            return

        if self.first:
            self.fill_six()
            self.first = False
            self.hold_piece = Piece(self.next_canvas, (20, 20))
            self.hold_piece = Piece(self.hold_canvas, (20, 20),
                                    self.hold_piece.shape)
        else:
            print("drop")
            delay = randint(150, 210)
            self.canvas.after(delay, self.play_sound)
            self.canvas.after(delay + 100, self.autodrop)

        if not self.next_piece:
            self.next_piece = Piece(self.next_canvas, (20, 20))
        self.current_piece = Piece(self.canvas, (Tetris.GAME_START_POINT, 0),
                                   self.next_piece.shape)
        self.next_canvas.delete("all")
        self.__draw_hold_canvas_frame()
        self.__draw_next_canvas_frame()
        self.next_piece = Piece(self.next_canvas, (20, 20))
        self.update_predict()

        if path[queue_count - 2][2]:
            self.auto_control(4)

        for i in range(actionlist_rotate[queue_count - 2]):
            self.auto_control(0)

        for i in range(actionlist_right[queue_count - 2]):
            self.auto_control(1)

    def start(self):
        global path, piece_queue, queue_count, actionlist_right, actionlist_rotate
        piece_queue = get_piece_queue()
        path = None
        actionlist_right = []
        actionlist_rotate = []

        for i in range(10):
            path = findpath(0, piece_queue)
            if not path:
                piece_queue = piece_queue[1:]
            else:
                break

        if path != False:
            for r in path:
                actionlist_rotate.append(r[3][0])
            for x in path:
                actionlist_right.append(x[3][1])
        print(actionlist_rotate)

        queue_count = -1
        self.new_game()
        self.root.after(self.speed, None)
        self.drop()

        self.root.mainloop()

    def drop(self):
        if not self.current_piece.move((0, 1)):
            self.current_piece.remove_predicts()
            self.completed_lines()
            self.game_board = self.canvas.game_board()
            self.update_piece()

            if self.is_game_over():
                return
            else:
                self._blockcount += 1
                self.score += 1

        self.root.after(self.speed, self.drop)

    def hard_drop(self):
        self.current_piece.move(
            self.current_piece.predict_movement(self.game_board))

    def update_predict(self):
        if self.predictable:
            self.current_piece.predict_drop(self.game_board)

    def update_status(self):
        self.status_var.set(f"Level: {self.level}, Score: {self.score}")
        self.status.update()

    def is_game_over(self):
        if not self.current_piece.move((0, 1)):

            self.play_again_btn = Button(self.root,
                                         text="Play Again",
                                         command=self.play_again)
            self.quit_btn = Button(self.root, text="Quit", command=self.quit)
            self.play_again_btn.place(x=Tetris.GAME_WIDTH + 10,
                                      y=200,
                                      width=100,
                                      height=25)
            self.quit_btn.place(x=Tetris.GAME_WIDTH + 10,
                                y=300,
                                width=100,
                                height=25)
            return True
        return False

    def end_game(self):
        print("endgame")
        self.play_again_btn = Button(self.root,
                                     text="Play Again",
                                     command=self.play_again)
        self.quit_btn = Button(self.root, text="Quit", command=self.quit)
        self.play_again_btn.place(x=Tetris.GAME_WIDTH + 10,
                                  y=200,
                                  width=100,
                                  height=25)
        self.quit_btn.place(x=Tetris.GAME_WIDTH + 10,
                            y=300,
                            width=100,
                            height=25)

    def play_again(self):
        self.play_again_btn.destroy()
        self.quit_btn.destroy()
        self.start()

    def quit(self):
        self.root.quit()

    def completed_lines(self):
        y_coords = [
            self.canvas.coords(box)[3] for box in self.current_piece.boxes
        ]

        #y_coords=[0]
        completed_line = self.canvas.completed_lines(y_coords)
        if completed_line == 1:
            self.score += 400
        elif completed_line == 2:
            self.score += 1000
        elif completed_line == 3:
            self.score += 3000
        elif completed_line >= 4:
            self.score += 12000

    def __game_canvas(self):
        self.canvas = GameCanvas(self.root,
                                 width=Tetris.GAME_WIDTH,
                                 height=Tetris.GAME_HEIGHT)

        self.canvas.pack(padx=5, pady=10, side=LEFT)

    def __level_score_label(self):
        self.status_var = StringVar()
        self.status = Label(self.root,
                            textvariable=self.status_var,
                            font=("Helvetica", 10, "bold"))
        #self.status.place(x = Tetris.GAME_WIDTH + 10, y = 100, width=100, height=25)
        self.status.pack()

    def __next_piece_canvas(self):
        self.next_canvas = Canvas(self.root, width=100, height=100)
        self.next_canvas.pack(padx=5, pady=10)

    def __hold_piece_canvas(self):
        self.hold_canvas = Canvas(self.root, width=100, height=300)
        self.hold_canvas.pack(padx=5, pady=10)

    def __draw_canvas_frame(self):
        self.canvas.create_line(10,
                                0,
                                10,
                                self.GAME_HEIGHT,
                                fill="red",
                                tags="line")
        self.canvas.create_line(self.GAME_WIDTH - 10,
                                0,
                                self.GAME_WIDTH - 10,
                                self.GAME_HEIGHT,
                                fill="red",
                                tags="line")
        self.canvas.create_line(10,
                                self.GAME_HEIGHT,
                                self.GAME_WIDTH - 10,
                                self.GAME_HEIGHT,
                                fill="red",
                                tags="line")

    def __draw_next_canvas_frame(self):
        self.next_canvas.create_rectangle(10, 10, 90, 90, tags="frame")

    def __draw_hold_canvas_frame(self):
        self.hold_canvas.create_rectangle(10, 10, 90, 90, tags="frame")

    #set & get
    def __get_level(self):
        return self._level

    def __set_level(self, level):
        self.speed = 500 - (level - 1) * 25
        self._level = level
        self.update_status()

    def __get_score(self):
        return self._score

    def __set_score(self, score):
        self._score = score
        self.update_status()

    def __get_blockcount(self):
        return self._blockcount

    def __set_blockcount(self, blockcount):
        self.level = blockcount // 5 + 1
        self._blockcount = blockcount

    level = property(__get_level, __set_level)
    score = property(__get_score, __set_score)
    blockcount = property(__get_blockcount, __set_blockcount)