Example #1
0
File: tkui.py Project: mindhog/mawb
class ProgramWidget(Frame):

    def __init__(self, parent, client):
        super(ProgramWidget, self).__init__(parent)
        self.client = client
        self.client.onProgramChange = self.programChanged

        self.programLabel = Label(self, text = 'Program:')
        self.programLabel.grid(row = 0, column = 0)
        self.programEntry = Entry(self, text = 'Program name',
                                  state = 'readonly')
        self.programEntry.grid(row = 0, column = 1)
        self.buttonPanel = Frame(self)
        self.buttonPanel.grid(row = 1, column = 0, columnspan = 2, sticky = W)
        self.newButton = Button(self.buttonPanel, text='New',
                                command = self.newProgram)
        self.newButton.pack(side = LEFT)

    def programChanged(self):
        self.__setProgramText(str(self.client.state))

    def __setProgramText(self, text):
        self.programEntry.configure(state = NORMAL)
        self.programEntry.delete(0)
        self.programEntry.insert(0, text)
        self.programEntry.configure(state = 'readonly')

    def newProgram(self):
        self.client.makeNewProgram()
Example #2
0
    def __init__(self, parent, handler):

        '''Initialization method.'''

        Frame.__init__(self, parent)

        button_frame = Frame(self)
        button_frame.pack(side=TOP)

        self.deal_button = Button(button_frame, text="Deal",
                                  command=lambda: handler("deal"))
        self.deal_button.pack(side=LEFT, padx=5, pady=5)

        self.quit_button = Button(button_frame, text="Quit",
                                  command=lambda: handler("quit"))
        self.quit_button.pack(side=RIGHT, padx=5, pady=5)

        self.exchange_button = Button(button_frame, text="Exchange",
                                      command=lambda: handler("exchange"))
        self.exchange_button.pack(side=RIGHT, padx=5, pady=5)

        self.show_button = Button(button_frame, text="Show",
                                  command=lambda: handler("show"))
        self.show_button.pack(side=RIGHT, padx=5, pady=5)

        label_frame = Frame(self)
        label_frame.pack(side=BOTTOM)

        self.status_label = Label(label_frame, relief=SUNKEN)
        self.set_status_text("No text to show")
        self.status_label.pack(side=TOP, padx=5, pady=5)
Example #3
0
class PyBooguNote(Frame):
    """Main class"""
    def __init__(self, parent):
        super().__init__(parent)
        self.parent = parent

        self.create_toolbar()
        self.sc = ScrolledCanvas(parent, bg="white", highlightthickness=0, takefocus=1)
        self.sc.frame.pack(expand=1, fill='both')

    def create_toolbar(self):
        self.toolbar = Frame(self.parent)
        self.btn_new = Button(self.toolbar, text='New', command=self.new_file)
        self.btn_new.grid(row=0, column=0)
        self.btn_open = Button(self.toolbar, text='Open', command=self.open_file)
        self.btn_open.grid(row=0, column=1)
        self.toolbar.pack(fill='both')

    def open_file(self):
        self.file_path = askopenfilename(filetypes=[('BooguNote Files', '.boo')])
        self.dom = parse(self.file_path)
        curItem = None
        pyBt = PyBooguTree(self.sc.canvas, self.file_path, self.dom)
    
    def new_file(self):
        self.file_path = asksaveasfilename()
        print(self.file_path)
class CircleBuilderPopup(BuilderPopup):
    """
    Class that launches a popup and collects user data to pass data back to the main window
    to build a circle.
    """
    def __init__(self, master):
        """
        Establish the GUI of this popup
        """
        BuilderPopup.__init__(self, master)
        self.data = (0, 0)
        self.radius = Label(self.top, text="Radius")
        self.radius_entry = Entry(self.top, width=self.width, bd=self.bd)
        self.center = Label(self.top, text="Center")
        self.center_entry = Entry(self.top, width=self.width, bd=self.bd)
        self.build_circle_submit = Button(self.top, text="Build!", command=self.cleanup)
        self.top.bind("<Return>", self.cleanup)
        self.radius.grid(row=0, column=0)
        self.radius_entry.grid(row=0, column=1)
        self.center.grid(row=1, column=0)
        self.center_entry.grid(row=1, column=1)
        self.build_circle_submit.grid(row=2, column=0, columnspan=2)
        self.top_left = 0
        self.bottom_right = 0
        self.radius_entry.focus()

    def cleanup(self, entry=None):
        """
        Collect the data from the user and package it into object variables, then close.
        """
        center = complex(0, 0)
        if self.center_entry.get():
            center = complex(allow_constants(self.center_entry.get()))
        self.data = (float(allow_constants(self.radius_entry.get())), center)
        self.top.destroy()
Example #5
0
 def create_toolbar(self):
     self.toolbar = Frame(self.parent)
     self.btn_new = Button(self.toolbar, text='New', command=self.new_file)
     self.btn_new.grid(row=0, column=0)
     self.btn_open = Button(self.toolbar, text='Open', command=self.open_file)
     self.btn_open.grid(row=0, column=1)
     self.toolbar.pack(fill='both')
Example #6
0
 def makebuttons(self):
     self.b1=Button(self, text="restart",bg="blue",fg='white',command= self.restart )
     self.b1.pack(side='right',fill='both' )
     self.b2=Button(self,text='quit',bg='green',fg='white',command=self.quit)
     self.b2.pack(side='left',fill='both')
     self.lastTime=""
     self.start_timer()
Example #7
0
class Demo(Frame):
    def __init__(self, parent, *args, **kw):
        Frame.__init__(self, parent, *args,**kw)
        self.e=Entry(self, text='Message')
        self.e.delete(0,'end')
        self.e.pack()
        self.makebuttons()        
        self.pack(expand='true',fill='x')

    def makebuttons(self):
        self.b1=Button(self, text="restart",bg="blue",fg='white',command= self.restart )
        self.b1.pack(side='right',fill='both' )
        self.b2=Button(self,text='quit',bg='green',fg='white',command=self.quit)
        self.b2.pack(side='left',fill='both')
        self.lastTime=""
        self.start_timer()
        
    def start_timer(self):
        pass

    def destroy(self):
        self.pack_forget()
    

    def restart(self):
        self.destroy()
        D=Demo(root,bg='purple')
        print ("killed")
        D.__init__(self,root)
        pass
    
    def quit(self):
        root.destroy()
 def __init__(self, master):
     self.top = Toplevel(master)
     self.entry_width = 15
     self.set_none_limits()
     self.real_max_label = Label(self.top, text="Real Max: ")
     self.real_min_label = Label(self.top, text="Real Min: ")
     self.imag_max_label = Label(self.top, text="Imag Max: ")
     self.imag_min_label = Label(self.top, text="Imag Min: ")
     self.real_max_entry = Entry(self.top, width=self.entry_width)
     self.real_min_entry = Entry(self.top, width=self.entry_width)
     self.imag_max_entry = Entry(self.top, width=self.entry_width)
     self.imag_min_entry = Entry(self.top, width=self.entry_width)
     self.submit_button = Button(self.top, text="Submit", command=self.submit)
     self.cancel_button = Button(self.top, text="Cancel", command=self.top.destroy)
     self.real_max_label.grid(row=0, column=0)
     self.real_min_label.grid(row=1, column=0)
     self.imag_max_label.grid(row=2, column=0)
     self.imag_min_label.grid(row=3, column=0)
     self.real_max_entry.grid(row=0, column=1)
     self.real_min_entry.grid(row=1, column=1)
     self.imag_max_entry.grid(row=2, column=1)
     self.imag_min_entry.grid(row=3, column=1)
     self.submit_button.grid(row=4, column=0)
     self.cancel_button.grid(row=4, column=1)
     self.top.bind("<Return>", self.submit)
     self.top.bind("<Escape>", self.top.destroy)
     self.real_max_entry.focus()
Example #9
0
    def __init__(self, master=None):
        # Avoiding to send it continuously.
        self.lock = False

        Frame.__init__(self, master)
        self.grid()
        self.master = master
        # Setting for ComboBox.
        self.url_lang_combobox_str = StringVar()
        self.url_lang_combobox_list = lang_list
        # UI components.
        self.receiver_email_text = Label(self, text="Receiver:")
        self.receiver_email_field = Entry(self, width=50)
        self.subject_text = Label(self, text='Subject:')
        self.subject_field = Entry(self, width=50)
        self.receiver_name_text = Label(self, text='Name:')
        self.receiver_name_field = Entry(self, width=50)
        self.url_lang_text = Label(self, text='Link lang:')
        self.url_lang_combobox = Combobox(self, textvariable=self.url_lang_combobox_str, values=self.url_lang_combobox_list, state='readonly')
        self.send_progressbar = Progressbar(self, orient='horizontal', length=500, mode='determinate', maximum=300)
        self.send_button = Button(self, text='Send', command=self._send_mail)
        self.quit_button = Button(self, text='Exit', command=self.__exit)
        self.log_msg_text = ScrolledText(self)
        # Attachment.
        self.mail_attachment_list = attachment_list[:]
        self.url_lang_link_title = None
        self.url_lang_link = copy.deepcopy(content_link)
        # Mailer
        self._mailer = None

        # Let Mailer can control components.
        Mailer.window_content = self

        self.__create_widgets()
	def createWidgets(self):
		self.title = Label(self, text="Image!", font=("Helvetica", 16))
		self.title.grid(row=0, column=1, columnspan=2)

		self.open_file = Button(self)
		self.open_file['text'] = "OPEN"
		self.open_file["command"] = self.openfile
		self.open_file.grid(row=1, column=0)

		self.save_button = Button(self, text='SAVE',
									command=self.save_file)
		self.save_button.grid(row=1, column=1)

		self.canvas = Canvas(self, width=400, height=300)
		self.canvas.grid(row=2, column=0, rowspan=5, columnspan=4)

		self.convert_grayscale_button= Button(self)
		self.convert_grayscale_button['text'] = "Convert to\n grayscale"
		self.convert_grayscale_button["command"] = self.convert_grayscale
		self.convert_grayscale_button.grid(row=7, column=0)

		self.variable = StringVar(self)
		self.variable.set("gray") 
		self.choose_color_menu = OptionMenu(self, self.variable,"gray", "blue", "green", "red")
		self.choose_color_menu['text'] = "Choose Color"
		self.choose_color_menu.grid(row=7, column=1)
					
		self.color_button = Button(self, text="COLOR", command=self.color_image)
		self.color_button.grid(row=7, column=2)

		self.quit_button = Button(self, text="QUIT", command=self.quit)
		self.quit_button.grid(row=7, column=3)
Example #11
0
    def __init__(self, client):
        # Basic setup
        super(Preferences, self).__init__()
        self.client = client

        # Setup the variables used
        self.echo_input = BooleanVar()
        self.echo_input.set(self.client.config['UI'].getboolean('echo_input'))
        self.echo_input.trace("w", self.echo_handler)
        self.logging = BooleanVar()
        self.logging.set(self.client.config['logging'].getboolean('log_session'))
        self.logging.trace('w', self.logging_handler)
        self.log_dir = self.client.config['logging']['log_directory']

        # Build the actual window and widgets
        prefs = Toplevel(self)
        prefs.wm_title("Preferences")
        echo_input_label = Label(prefs, text="Echo Input:")
        logging_label = Label(prefs, text='Log to file:')
        echo_checkbox = Checkbutton(prefs, variable=self.echo_input)
        logging_checkbox = Checkbutton(prefs, variable=self.logging)
        logging_button_text = 'Choose file...' if self.log_dir == "" else self.log_dir
        logging_button = Button(prefs, text=logging_button_text, command=self.logging_pick_location)

        # Pack 'em in.
        echo_input_label.grid(row=0, column=0)
        echo_checkbox.grid(row=0, column=1)
        logging_label.grid(row=1, column=0)
        logging_checkbox.grid(row=1, column=1)
        logging_button.grid(row=1, column=2)
Example #12
0
    def _reset_controls(self):
        """ Resets the controls on the form. """
        image = ImageTk.PhotoImage(file="bg.png")
        
        # Initialize controls
        self.lbl_bg = Label(self, image=image)
        self.lbl_dir = Label(self, bg="white", fg="#668FA7", font=("Courier", 14))
        self.lbl_anon = Label(self, bg="white", fg="#668FA7", font=("Courier", 14))
        self.lbl_id = Label(self, bg="white", fg="#668FA7", font=("Courier", 14))
        self.btn_dir_select = Button(self, text="Select data folder", command=self._btn_dir_press)
        self.btn_id = Button(self, text="Identify data", command=self._btn_id_press)
        self.btn_anon = Button(self, text="Anonymize data", command=self._btn_anon_press)
        self.tb_study = Entry(self, bg="#668FA7", fg="white")
        self.prg_id = Progressbar(self, orient="horizontal", length=200, mode="determinate")
        self.prg_anon = Progressbar(self, orient="horizontal", length=200, mode="determinate")

        # Place controls
        self.lbl_bg.place(x=0, y=0, relwidth=1, relheight=1)
        self.lbl_anon.place(x=400, y=400)
        self.lbl_id.place(x=400, y=325)
        self.btn_dir_select.place(x=250, y=250)
        self.btn_id.place(x=250, y=325)
        self.btn_anon.place(x=250, y=400)
        self.tb_study.place(x=250, y=175)
        self.prg_id.place(x=410, y=290)
        self.prg_anon.place(x=410, y=370)

        # Other formatting
        self.lbl_bg.image = image
        self.btn_id['state'] = "disabled"
        self.btn_anon['state'] = "disabled"
        self.prg_id['maximum'] = 100
        self.prg_anon['maximum'] = 100
 def make_button(self, label, command, isdef=0):
     "Return command button gridded in command frame."
     b = Button(self.buttonframe, text=label, command=command, default=isdef and "active" or "normal")
     cols, rows = self.buttonframe.grid_size()
     b.grid(pady=1, row=rows, column=0, sticky="ew")
     self.buttonframe.grid(rowspan=rows + 1)
     return b
Example #14
0
    def initUI(self):
        self.parent.title('PyZilla')
        self.padding = 5

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

        # Create a menubar
        mnuMenu = Menu(self.parent)
        self.parent.config(menu=mnuMenu)

        # Create menubar
        mnuFileMenu = Menu(mnuMenu)

        # Add File menu items
        mnuFileMenu.add_command(label='Open', command=self.onBtnOpenFile)
        mnuFileMenu.add_command(label='Exit', command=self.quit)

        # Add File menu items to File menu
        mnuMenu.add_cascade(label='File', menu=mnuFileMenu)

        # Create frame for all the widgets
        frame = Frame(self)
        frame.pack(anchor=N, fill=BOTH)

        # Create file open dialog
        btnOpenFile = Button(frame, text="Load file", command=self.onBtnOpenFile)
        btnOpenFile.pack(side=RIGHT, pady=self.padding)

        # Create filename label
        self.lblFilename = Label(frame, text='No filename chosen...')
        self.lblFilename.pack(side=LEFT, pady=self.padding, padx=self.padding)

        # Create the text widget for the results
        self.txtResults = Text(self)
        self.txtResults.pack(fill=BOTH, expand=1, pady=self.padding, padx=self.padding)
Example #15
0
class   Application(Frame): 
    def __init__(self,  master=None):
        Frame.__init__(self, master)    
        self.grid(sticky=N+S+E+W)   
        self.mainframe()

    def mainframe(self):                
        self.data = Listbox(self, bg='red')
        self.scrollbar = Scrollbar(self.data, orient=VERTICAL)
        self.data.config(yscrollcommand=self.scrollbar.set)
        self.scrollbar.config(command=self.data.yview)

        for i in range(1000):
            self.data.insert(END, str(i))

        self.run = Button(self, text="run")
        self.stop = Button(self, text="stop")
    
        self.data.grid(row=0, column=0, rowspan=4,
                       columnspan=2, sticky=N+E+S+W)
        self.data.columnconfigure(0, weight=1)
    
        self.run.grid(row=4,column=0,sticky=EW)
        self.stop.grid(row=4,column=1,sticky=EW)
    
        self.scrollbar.grid(column=2, sticky=N+S)
Example #16
0
    def setupSelectMachineButtons(self):

        numDevices = len(self.supportedDevices)
        numColumns = 3
        numRows = math.ceil((numDevices+1)/3)
        
        self.photo = PhotoImage(file="eguana.gif")
        self.photo = self.photo.subsample(2);
        self.photo_label = Label(self.selectMachineFrame,image=self.photo,borderwidth=0,highlightthickness=0)
        self.photo_label.configure(bg='#FADC46')
        self.photo_label.grid(row=int(numRows/2),column=1, sticky=N+S+E+W,padx=2,pady =2)
        self.photo_label.image = self.photo        
        
        index = 0
        for i in range(numRows):
            for j in range(numColumns):
                
                if not(j == 1 and i == int(numRows/2)) and (index < numDevices):
                    device = self.supportedDevices[index]
                    b = Button(self.selectMachineFrame,text=device.name,relief=RAISED, command=lambda device=device :self.machineButtonPressed(device))
                    b.grid(row=i,column=j, sticky=N+S+E+W,padx=2,pady =2)
                    index += 1

            
        for i in range(numRows):
            self.selectMachineFrame.rowconfigure(i,weight=1)
         
        for i in range(numColumns):
            self.selectMachineFrame.columnconfigure(i,weight=1)
Example #17
0
class MessageTester:
    def __init__(self, root):
        root.title("Message tester")
        Label(root, text="Enter message event below", bg="light green").pack()
        self.event_field = ScrolledText(root, width=180, height=10)
        self.event_field.pack()

        Label(root, text="Enter test case below", bg="light green").pack()
        self.test_case_field = ScrolledText(root, width=180, height=20)
        self.test_case_field.pack()

        Label(root, text="Test result:", bg="light green").pack()

        self.result_field = ScrolledText(root, width=180, height=10)
        self.result_field.pack()
        self.result_field.config(state=DISABLED)
        self.button = Button(root, text="Evaluate", fg="red",
                             command=self._clicked)
        self.button.pack()

        self.event_field.delete('1.0', END)
        self.event_field.insert('insert', EXAMPLE_EVENT)
        self.test_case_field.delete('1.0', END)
        self.test_case_field.insert('insert', EXAMPLE_TEST_CASE)

    def _clicked(self):
        event = self.event_field.get('1.0', END)
        test_case = self.test_case_field.get('1.0', END)

        evaluation = skill_tester.EvaluationRule(ast.literal_eval(test_case))
        evaluation.evaluate(ast.literal_eval(event))
        self.result_field.config(state=NORMAL)
        self.result_field.delete('1.0', END)
        self.result_field.insert('insert', evaluation.rule)
        self.result_field.config(state=DISABLED)
Example #18
0
 def view_new_title(self, Medikom, entry_type):
     self.selected_id = False
     self.overview(Medikom)
     if entry_type == 0:
         text = "Titel der neuen Aufgabe:"
     elif entry_type == 1:
         text = "Titel der neuen Information:"
     details_label = Label(
         self, text=text, font='Liberation 10',
         fg='Black')
     details_label.place(
         x=self.SPACE_TWO / 2,
         y=(self.n + 2) * (self.ROW_HIGHT + self.ROW_SPACE),
         width=self.WIN_WIDTH - self.SPACE_TWO, height=self.ROW_HIGHT)
     textframe = Text(self, font='Liberation 12', height=1, width=int(self.WIN_WIDTH / 4))
     textframe.place(
         x=self.SPACE_TWO, y=(self.n + 3) * (self.ROW_HIGHT + self.ROW_SPACE),
         width=self.WIN_WIDTH - self.SPACE_ONE - 10, height=self.ROW_HIGHT)
     create_button = Button(
         self, text='Erstellen',
         command=lambda: self.add_entry(Medikom, entry_type, textframe.get(1.0, END).strip()))
     create_button.place(
         x=(self.WIN_WIDTH / 2) - (self.WIN_WIDTH / 16),
         y=(self.n + 4) * (self.ROW_HIGHT + self.ROW_SPACE),
         width=self.WIN_WIDTH / 8, height=self.ROW_HIGHT)
Example #19
0
class Example(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)

        self.toolbar = Frame(self, bg="#eee")
        self.toolbar.pack(side="top", fill="x")

        self.bold = Button(self.toolbar, text="Bold", command=self.make_bold)
        self.bold.pack(side="left")

        self.clear = Button(self.toolbar, text="Clear", command=self.clear)
        self.clear.pack(side="left")

        # Creates a bold font.
        self.bold_font = Font(family="Helvetica", size=14, weight="bold")

        self.text = Text(self)
        self.text.insert("end", "Select part of text and then click 'Bold'...")
        self.text.focus()
        self.text.pack(fill="both", expand=True)

        # Configures a tag called BOLD.
        self.text.tag_configure("BOLD", font=self.bold_font)

    def make_bold(self):
        # tk.TclError exception is raised if not text is selected.
        try:
            self.text.tag_add("BOLD", "sel.first", "sel.last")
        except TclError:
            pass

    def clear(self):
        self.text.tag_remove("BOLD", "1.0", 'end')
Example #20
0
    def test_gui(self):
        """
        The GUI interactions by simulating user actions
        """
        tl = Toplevel()
        gui = ClassicGUI(tl)
        gui.colorPicker = DummyColorPicker(tl)
        controller = DrawController(gui)
        self.assertEquals(gui.ioButtons.__len__(), 5, "There should be 5 IO buttons")
        self.assertEquals(gui.commandButtons.__len__(), 4, "There should be 4 draw command buttons")

        gui.onChangeColor(gui.colorPickerButton)
        self.assertEquals(gui.colorPickerButton.cget('bg'), gui.colorPicker.getColor())

        dummyButton = Button()
        gui.onDrawCommandButtonClick(dummyButton, LineDrawCommand)
        self.assertEquals(dummyButton.cget('relief'), SUNKEN, "Selected button should have style SUNKEN")

        for btn in gui.commandButtons:
            self.assertEquals(btn.cget('relief'), FLAT, "Selected button should have style FLAT")

        self.assertEquals(type(controller.activeCommand), LineDrawCommand, "Active command should be LineDrawCommand")

        for cmd in controller.commands:
            controller.canvas.getDrawArea().delete(ALL)
            self.assertCommandOperations(controller, cmd)

        clearCmd = NewDrawCommand()
        gui.onIOCommandClick(dummyButton, clearCmd)
        self.assertEquals(gui.canvas.getDrawArea().find_all().__len__(), 0,
                          "The canvas should be cleared on NewDrawCommand")
Example #21
0
 def playerbox(event, player):
     
     togglebutton = event.widget
     
     bleh = Label(self, cursor = 'hand1',
                  highlightthickness = 0, bd = 0,
                  image = self.emptylist[togglebutton.slot -1])
     self.canvas.create_window((togglebutton.winfo_x() + 86,
                                togglebutton.winfo_y() + 122),
                               window = bleh,
                               tags = ('p{}empty'
                                       .format(togglebutton.slot),
                                      'p{}'
                                       .format(togglebutton.slot)))
     namebutton = TkButton(self, text = 'SELECT A NAME',
                           compound = CENTER, 
                           bd = 0, fg = 'white',
                           font = ('Arial Black', 8),
                           highlightthickness = 0, 
                           cursor = 'hand2',
                           highlightbackground = 'black',
                           image = self.nameboxpreimage)
     namebutton.bind('<Button-1>',
                     lambda event:
                     nameselectbox(self, togglebutton,
                                   namebutton, player))
     self.canvas.create_window((togglebutton.winfo_x() + 90,
                                togglebutton.winfo_y() + 185),
                               window = namebutton,
                               tags = ('namebutton',
                                       'p{}'
                                       .format(togglebutton.slot)))
     togglebutton.lift()
     self.canvas.tag_raise('p{}coin'.format(togglebutton.slot))
Example #22
0
class MyFirstGUI:
    LABEL_TEXT = [
        "This is our first GUI!",
        "Actually, this is our second GUI.",
        "We made it more interesting...",
        "...by making this label interactive.",
        "Go on, click on it again.",
    ]
    def __init__(self, master):
        self.master = master
        master.title("A simple GUI")

        self.label_index = 0
        self.label_text = StringVar()
        self.label_text.set(self.LABEL_TEXT[self.label_index])
        self.label = Label(master, textvariable=self.label_text)
        self.label.bind("<Button-1>", self.cycle_label_text)
        self.label.pack()

        self.greet_button = Button(master, text="Greet", command=self.greet)
        self.greet_button.pack()

        self.close_button = Button(master, text="Close", command=master.quit)
        self.close_button.pack()

    def greet(self):
        print("Greetings!")

    def cycle_label_text(self, event):
        self.label_index += 1
        self.label_index %= len(self.LABEL_TEXT) # wrap around
        self.label_text.set(self.LABEL_TEXT[self.label_index])
Example #23
0
 def __init__(self, master, line_collection):
     try:
         self.width_of_entry = len(line_collection[0])
     except IndexError:
         self.width_of_entry = 0
     self.top = Toplevel(master)
     self.current_lines_listbox = Listbox(self.top)
     self.removed_lines_listbox = Listbox(self.top)
     self.submit = Button(self.top, text = "Ok", command=self.submit)
     self.remove_button = Button(self.top, text = "Remove", command=self.remove_line)
     self.cancel = Button(self.top, text = "Cancel", command=self.top.destroy)
     self.top.bind("<Return>", func=self.submit)
     self.current_lines = line_collection
     self.removed_lines = []
     self.ids_internal = []
     self.ids = []
     for index, line in enumerate(self.current_lines):
         #removes the point data and converts the rest to strings
         id = line[1]
         if id not in self.ids_internal:
             self.ids_internal.append(id)
             self.ids.append(id)
             line = [str(element) for element in line[1:]]
             
             #put into the list
             self.current_lines_listbox.insert(index, " ".join(line))
     self.current_lines_listbox.grid(row=0, column=0, columnspan=3)
     self.submit.grid(row=1, column=1)
     self.cancel.grid(row=1, column=2)
     self.remove_button.grid(row=1, column=0)
Example #24
0
 def __init__(self, method=None, master=None):
     self.method = method
     self.picframe = Frame.__init__(self, master)
     self.master.title("Robobackup")
     self.image = PhotoImage()
     self.image["file"] = os.path.join(os.path.dirname(\
         os.path.relpath(__file__)), "resources", "ASK.png")
     self.piclabel = Label(self.picframe, image=self.image)
     self.piclabel.grid(row=0, column=0, columnspan=4, rowspan=6)
     self.clocklabel = Label(self.picframe, text=_("Elapsed time:"))
     self.clocklabel.grid(row=0, column=4, sticky="NSEW")
     self.clock = Label(self.picframe, text="")
     self.clock.grid(row=1, column=4, sticky="NSEW")
     self.start = Button(self.picframe, text=_("Start Backup"), command=self.__clk)
     self.start.grid(row=3, column=4, sticky="NSEW")
     self.errorlabel = Label(self.picframe)
     self.errorlabel.grid(row=4, column=4, sticky="NSEW")
     self.close = Button(self.picframe, text=_("Close"), command=self.__cls)
     self.close.grid(row=5, column=4, sticky="NSEW")
     self.loglabel = Label(self.picframe, text=_("Log:"), justify="left")
     self.loglabel.grid(row=6, column=0, columnspan=5, sticky="NSEW")
     self.text = Text(self.picframe)
     self.text.grid(row=7, column=0, rowspan=6, columnspan=5, sticky="NSEW")
     self.timeout = False
     self.starttime = -1
Example #25
0
File: main.py Project: kr1/roqba
 def create_monitor(self):
     self.monitor_frame = LabelFrame(self, text="Monitor and Transport")
     this_cycle = Scale(self.monitor_frame, label='cycle_pos', orient=HORIZONTAL,
                        from_=1, to=16, resolution=1)
     this_cycle.disable, this_cycle.enable = (None, None)
     this_cycle.ref = 'cycle_pos'
     this_cycle.grid(column=0, row=0, sticky=E + W)
     self.updateButton = Button(self.monitor_frame,
                                text='Reload all Settings',
                                command=self.request_update)
     self.updateButton.grid(row=1, sticky=E + W)
     self.ForceCaesuraButton = Button(self.monitor_frame,
                                      text='Force Caesura',
                                      command=self.force_caesura)
     self.ForceCaesuraButton.grid(row=2, sticky=E + W)
     self.saveBehaviourButton = Button(self.monitor_frame,
                                       text='Save current behaviour',
                                       command=self.request_saving_behaviour)
     self.saveBehaviourButton.grid(row=3, sticky=E + W)
     self.saveBehaviourNameEntry = Entry(self.monitor_frame)
     self.saveBehaviourNameEntry.grid(row=4, sticky=E + W)
     self.saveBehaviourNameEntry.bind('<KeyRelease>', self.request_saving_behaviour)
     self.selected_behaviour = StringVar()
     self.selected_behaviour.trace('w', self.new_behaviour_chosen)
     self.savedBehavioursMenu = OptionMenu(self.monitor_frame,
                                           self.selected_behaviour, None,)
     self.savedBehavioursMenu.grid(row=5, sticky=E + W)
     self.monitor_frame.grid(column=0, row=10, sticky=E + W)
Example #26
0
    def __init__(self, parent):
       
        # super(createSets,self).__init__(parent)
        Frame.__init__(self, parent)
        self.parent = parent
        self.grid(row=0, column=0)

        self.parentWindow = 0

        self.listBox = Listbox(self, selectmode=EXTENDED)
        self.listBox.grid(row=1, column=1)
        for item in ["one", "two", "three", "four"]:
            self.listBox.insert(END, item)
        
        self.buttonDel = Button(self,
                                text="delite selected class",
                                command=self.del_selected)  # lambda ld=self.listBox:ld.delete(ANCHOR))
        self.buttonDel.grid(row=0, column=0)
            
        self.entry = Entry(self, state=NORMAL)
        # self.entry.focus_set()
        self.entry.insert(0, "default")
        self.entry.grid(row=1, column=0)
        
        self.buttonInsert = Button(self, text="add new class",
                                   command=self.add)
        self.buttonInsert.grid(row=0, column=1)
        
        self.buttonDone = Button(self, text="done", command=self.done)
        self.buttonDone.grid(row=2, column=0)
class Example(Frame):

	def __init__(self, parent):
		Frame.__init__(self, parent)

		self.parent = parent
		self.initUI()

	def initUI(self):

		self.parent.title("test")
		self.pack(fill=BOTH, expand=1)

		self.cal = Button(self)
		self.cal["text"] = "Calculate"
		self.cal["command"] = self.cal_frequency
		self.cal.pack(fill=BOTH, expand=1)

	def cal_frequency(self):
		# use the dialog to find the route of the file
		file_path = filedialog.askopenfilename()
		frequency = [ 0 for i in range(26)]
		f = open(file_path, 'r')
		article = f.read()
		for i in article:
			seq = alpha_to_num(i)
			if seq != -1:
				frequency[seq] += 1
		print (frequency)
Example #28
0
    def __init__(self, master):
        self.master = master
        master.title("Calculator")

        self.total = 0
        self.entered_number = 0

        self.total_label_text = IntVar()
        self.total_label_text.set(self.total)
        self.total_label = Label(master, textvariable=self.total_label_text)

        self.label = Label(master, text="Total:")

        vcmd = master.register(self.validate)  # we have to wrap the command
        self.entry = Entry(master, validate="key", validatecommand=(vcmd, "%P"))

        self.add_button = Button(master, text="+", command=lambda: self.update("add"))
        self.subtract_button = Button(master, text="-", command=lambda: self.update("subtract"))
        self.multiply_button = Button(master, text="*", command=lambda: self.update("multiply"))
        # self.divide_button = Button(master, text="/", command=lambda: self.update("divide"))
        self.reset_button = Button(master, text="Reset", command=lambda: self.update("reset"))

        # LAYOUT
        self.label.grid(row=0, column=0, sticky=W)
        self.total_label.grid(row=0, column=1, columnspan=2, sticky=E)
        self.entry.grid(row=1, column=0, columnspan=5, sticky=W + E)
        self.add_button.grid(row=2, column=0)
        self.subtract_button.grid(row=2, column=1)
        self.multiply_button.grid(row=2, column=2)
        # self.divide_button.grid(row=2, column=3)
        self.reset_button.grid(row=2, column=4, sticky=W + E)
class InfoFrame(Frame):
    def __init__(self,master=None, thread=None):
        Frame.__init__(self, master)
        self.controlThread=thread
        
        self.stringVar=StringVar()
        
        self.grid()
        self.createWidgets()
        
    def createWidgets(self):
        self.inputText=Label(self)
        if self.inputText != None:
            self.inputText['textvariable']=self.stringVar
            self.inputText["width"] = 50
            self.inputText.grid(row=0, column=0, columnspan=6)
        else:
            pass
        
        
        self.cancelBtn = Button(self, command=self.clickCancelBtn)   # need to implement
        if self.cancelBtn !=None:
            self.cancelBtn["text"] = "Cancel"
            self.cancelBtn.grid(row=0, column=6)
        else:
            pass
        
    def clickCancelBtn(self):
        print("close the InfoDialog")
        self.controlThread.setStop()
            
    def updateInfo(self, str):
        self.stringVar.set(str)
Example #30
0
    def add_pairs( self, parent ) :
        if not self.pairs :
            self.pairs = LabelFrame(parent, text='Pairs')
            self.pairs_text = Text( self.pairs,
                             width=50,
                             height=8,
                             #bg=projectBgColor,
                             #fg=projectFgColor,
                             font=("nimbus mono bold","11")
                            )

            self.pairs_save_button = Button(self.pairs, 
                                            text="Save", 
                                            command = self.writepair )
            
            self.pairs_load_button = Button(self.pairs,
                                            text="Load",
                                            command = self.readpair )
            
            #self.pairs_load_button.pack( side=BOTTOM, padx=5, pady=5 )
            #self.pairs_save_button.pack( side=BOTTOM, padx=5, pady=5 )

            self.pairs_load_button.grid( row=5, column=5, padx=10, pady=5 )
            self.pairs_save_button.grid( row=5, column=6, padx=10, pady=5 )
            self.pairs_text.grid( row=1,  rowspan=3, 
                                 column=1,  columnspan=7,
                                 padx=5, pady=5 )

        self.pairs.grid(row=7,column=0, columnspan=6, sticky=W, padx=20, pady=10 )
Example #31
0
# Grpahic Interface
fenetre = Tk()
fenetre.title("Fire propagation")
canvas = Canvas(fenetre,
                width=a * NbC + 1,
                height=a * NbL + 1,
                highlightthickness=0)
fenetre.wm_attributes("-topmost", True)

canvas.bind("<Button-1>", TreeCell)
canvas.bind("<Button-3>", FireCell)

canvas.pack()
canvas.create_text(100, 400, text="ash")

bou1 = Button(fenetre, text='Exit', width=8, command=fenetre.destroy)
bou1.pack(side=RIGHT)
bou2 = Button(fenetre, text='Start', width=8, command=start)
bou2.pack(side=LEFT)
bou3 = Button(fenetre, text='Stop', width=8, command=stop)
bou3.pack(side=LEFT)
bou4 = Button(fenetre, text='Step', width=8, command=stepbystep)
bou4.pack(side=LEFT)
canvas.create_text(100, 10, text="ash")

# Launching automata
ash = 0
flag = 0
initialize_map()
draw()
iterate()
Example #32
0
def kali():
    p = float(str1.get())
    q = float(str2.get())
    r = p * q
    L.config(text=r)


def bagi():
    p = float(str1.get())
    q = float(str2.get())
    r = p / q
    L.config(text=r)


B1 = Button(my_app, text='+', command=tambah)
B1.grid(row=2, column=0)
B2 = Button(my_app, text='-', command=kurang)
B2.grid(row=2, column=1)
B3 = Button(my_app, text='x', command=kali)
B3.grid(row=2, column=2)
B4 = Button(my_app, text=':', command=bagi)
B4.grid(row=2, column=3)

L3 = Label(my_app, text='Hasil')
L3.grid(row=3, column=1)
L = Label(my_app, text='0')
L.grid(row=3, column=2)

my_app.mainloop()
title = Label(window, text='Basic Converter', font='Calibri 16')
title.grid(columnspan=3)

result = StringVar()

# Input and output entry fields.
inputEntry = Entry(window)
inputEntry.grid(row=1, column=0)

arrow = Label(window, text='--->', font='Calibri 20')
arrow.grid(row=1, column=1)

outputEntry = Entry(window, textvariable=result)
outputEntry.grid(row=1, column=2)

convertButton = Button(window, text='Convert!', command=converter)
convertButton.grid(row=2, column=1)

scrollbar = Scrollbar(window)  #left scrollbar
scrollbar.grid(row=2, column=0, sticky=NE + SE)

listbox = Listbox(window, exportselection=False)  # Left listbox.
# exportselection option in order to select 2 different listbox at same time.
listbox.grid(row=2, column=0)

measurement_list = [
    'Meter', 'Kilometer', 'Centimeter', 'Millimeter', 'Micrometer', 'Mile',
    'Yard', 'Foot', 'Inch'
]

for measurement in measurement_list:
# Add show section


LatestInfo = pickle.load(
    open("pythonWtachListGenerator\\watchListGenerator\\Files\\OldInfo.p", "rb"))
lastDateReached = LatestInfo["colB"]
LDR = conversionFunctions.StrToDate(lastDateReached)

lastTodaysDate = LatestInfo["colD"]
LTD = conversionFunctions.StrToDate(lastTodaysDate)

# ----------------------------------------------------------------------------------

frame = Frame(window)

createNewFileBtn = Button(
    frame, text="Create New Raw File", command=intializeRawFileFunc, width=18)

createNewFileBtn.pack(side=LEFT, padx=7, pady=7)

frame.pack()

# ----------------------------------------------------------------------------------

frame2 = Frame(window)

convertRawFileBtn = Button(
    frame2, text="Convert Raw File to Excel", command=turnRawFileIntoExcelFunc, width=22)

convertRawFileBtn.pack(side=LEFT, padx=10, pady=7)

frame2.pack()
Example #35
0
root.state('zoomed')
root.iconbitmap('images/logo.ico')

linearPhoto = PhotoImage(file="images/Linear_shadow.png")
binaryPhoto = PhotoImage(file="images/Binary_shadow.png")
bubblePhoto = PhotoImage(file="images/Bubble_shadow.png")
selectionPhoto = PhotoImage(file="images/Selection_shadow.png")
insertionPhoto = PhotoImage(file="images/Insertion_shadow.png")
heapPhoto = PhotoImage(file="images/Heap_shadow.png")
mergePhoto = PhotoImage(file="images/Merge_shadow.png")
quickPhoto = PhotoImage(file="images/Quick_shadow.png")

#global objects
entry = Entry(root)
entry1 = Entry(root)
startButton = Button(root, text='')
label = Label(root, text='')
label1 = Label(root, text='')
label3 = Label(root, text='')

searchLabel = Label(root,
                    text='Searching Algorithm',
                    font=('Comic Sans MS', 20),
                    fg='black')
searchLabel.place(x=20, y=10)

linearButton = Button(root,
                      image=linearPhoto,
                      command=linearSearchClicked,
                      border=0,
                      height=190,
Example #36
0
    test_image = test_image.resize((128, 128))
    img = ImageTk.PhotoImage(put_image)
    pic = Label(image=img)
    pic.pack()
    pic.image = img
    test_image = image_utils.img_to_array(test_image)
    test_image = np.expand_dims(test_image, axis=0)

    result = model.predict_on_batch(test_image)

    if result[0][0] == 1:
        ans = 'french fries'
    elif result[0][1] == 1:
        ans = 'pizza'
    elif result[0][2] == 1:
        ans = 'samosa'
    out = Label(window,
                text='Predicted answer : ' + ans,
                font=("Helvetica", 16))
    out.pack()


User_input = Entry(width=100)
User_input.pack()
btn = Button(window,
             text="Detect Image",
             font=("Helvetica", 12),
             command=clicked)
btn.pack()
window.mainloop()
Example #37
0
 def GUIItemsTab(self):
     
     
     self.itemSFrame = FrameScrollbar(self.tabItems)
         
     self.itemid=0
     self.Items = []
     
     for item in self.playerdata["items"]:
         
         self.Items.append({})
         self.Items[self.itemid]["id"]=self.itemid
         self.Items[self.itemid]["frame"] = Frame(self.itemSFrame.frame,relief=RIDGE,bg="grey",padx=1,pady=1)
         self.Items[self.itemid]["button_delete"] = Button(self.Items[self.itemid]["frame"],text="X",fg="white",bg="red",command=lambda Itemid=self.itemid:delItem(Itemid))
         self.Items[self.itemid]["name"] = Entry(self.Items[self.itemid]["frame"])
         self.Items[self.itemid]["name"].insert(END, item["name"])
         self.Items[self.itemid]["description"] = Text(self.Items[self.itemid]["frame"],width=10,height=5,wrap=WORD)
         self.Items[self.itemid]["description"].insert(END,item["description"])
         
         self.Items[self.itemid]["name"].grid(row=0,column=0)
         self.Items[self.itemid]["button_delete"].grid(row=0,column=0,sticky="E")
         self.Items[self.itemid]["description"].grid(row=1,column=0,sticky="NSEW")
         self.Items[self.itemid]["frame"].grid(padx=10,pady=10,sticky="EW")
         
         self.Items[self.itemid]["frame"].grid_columnconfigure(0, weight=1)
         
         
         
         self.itemid+=1
         
     def addItem():
         item={}
         item["id"]=self.itemid
         item["frame"] = Frame(self.itemSFrame.frame,relief=RIDGE,bg="grey",padx=1,pady=1)
         item["button_delete"] = Button(item["frame"],text="X",fg="white",bg="red",command=lambda Itemid=self.itemid:delItem(Itemid))
         item["name"] = Entry(item["frame"])
         item["description"] = Text(item["frame"],width=10,height=5,wrap=WORD)
         item["name"].grid(row=0,column=0)
         item["button_delete"].grid(row=0,column=0,sticky="E")
         item["description"].grid(row=1,column=0,sticky="NSEW")
         item["frame"].grid(padx=20,pady=10,sticky="EW")
         item["frame"].grid_columnconfigure(0, weight=1)
         
         self.itemSFrame.frame.update_idletasks()
         self.itemSFrame.onCanvasConfigure(None)
         
         
         
         self.Items.append(item)
         
         self.itemid+=1
         
 
         
     def delItem(Itemid):
         item=""
         index=0
         for item in self.Items:
             if item["id"]==Itemid:
                 index=self.Items.index(item)
                 break
             else:
                 item=""
         if item:
             self.Items[index]["frame"].grid_remove()
             self.Items.remove(item)
             
         self.itemSFrame.frame.update_idletasks()
         self.itemSFrame.onCanvasConfigure(None)
     
     self.addItemButton = Button(self.itemSFrame.canvas_frame,text="+",bg="grey",command=addItem).place(rely=1.0, relx=0.0, x=5, y=-5, anchor="sw")
def open_settings():
  global top_settings
  top_settings = Toplevel(root)
  center_window(top_settings, 520, 240)
  top_settings.iconbitmap('settings.ico')
  top_settings.resizable(False, False)
  top_settings.title("Settings")
  
  check_automation_checking(top_settings)
  frequency_checking_new_messages(top_settings)
  set_new_time_or_continue_after_manual_check(top_settings)
  ask_if_close_application(top_settings)

  save_settings_button = Button(top_settings, text = "Save settings", font=('Verdana', 9,'bold'), background = "blue", command = save_settings)
  save_settings_button.grid(column = 1, row = 10, sticky = E, padx = 9, pady = 9)

  cancel_settings_button = Button(top_settings, text = "Close settings", command = exit_from_settings)
  cancel_settings_button.grid(column = 0, row = 10, sticky = E, padx = 10, pady = 10)

  default_settings_button = Button(top_settings, text = "Default settings (no save)", command = set_default_settings)
  default_settings_button.grid(column = 0, row = 10, sticky = W, padx = 11, pady = 11)

  top_settings.mainloop()
Example #39
0
class SettingScreen(Screen):
    ROUTENAME = "/setting"
    INDEX_TIME_LIST = [60, 600, 3600]

    def backButton(self):
        self._screenManager.navigate("/")

    def clickButton(self):
        self._screenManager.navigate("/chess", self.time)

    def clickTimeSelect(self, index):
        if self.time == None:
            self.ButtonStart.config(state="normal")

        self.time = self.INDEX_TIME_LIST[index]

        for buttonIndex in range(len(self.timeButtons)):
            if buttonIndex == index:
                self.timeButtons[buttonIndex].config(
                    bg="#265B78",
                    fg="#FFF",
                )
            else:
                self.timeButtons[buttonIndex].config(
                    bg="#FFF",
                    fg="#265B78",
                )

    def initBuild(self):
        self.time = None

        self.frame = Frame(width=1000, height=800)
        self.frame.place(x=0, y=0)
        LabelCreate = Label(master=self.frame,
                            text="Spiel erstellen",
                            fg="#417D9E")
        LabelCreate["font"] = font.Font(family='Arial', size=50, weight='bold')
        LabelCreate.place(anchor="center", relx=0.5, rely=0.1)

        img = self._screenManager.imageHandler.images["Back"]

        self.buttonBack = Button(command=self.backButton,
                                 master=self.frame,
                                 image=img,
                                 borderwidth=0)
        self.buttonBack.place(anchor="center",
                              relx=0.1,
                              rely=0.1,
                              width=85,
                              height=85)

        LabelTime = Label(master=self.frame, text="Zeitlimit", fg="#000000")
        LabelTime["font"] = font.Font(family='Arial', size=30)
        LabelTime.place(anchor="center", relx=0.5, rely=0.38)

        self.timeButtons = []
        self.timeButtons.append(
            Button(master=self.frame,
                   text="1 min",
                   bg="#fff",
                   command=lambda: self.clickTimeSelect(0),
                   activebackground="#fff",
                   fg="#265B78",
                   activeforeground="#265B78",
                   borderwidth=0))

        self.timeButtons[0]["font"] = font.Font(family='Arial',
                                                size=40,
                                                weight='bold')
        self.timeButtons[0].place(anchor="center",
                                  relx=0.2,
                                  rely=0.5,
                                  width=190,
                                  height=110)

        self.timeButtons.append(
            Button(master=self.frame,
                   text="10 min",
                   bg="#fff",
                   command=lambda: self.clickTimeSelect(1),
                   activebackground="#fff",
                   fg="#265B78",
                   activeforeground="#265B78",
                   borderwidth=0))

        self.timeButtons[1]["font"] = font.Font(family='Arial',
                                                size=40,
                                                weight='bold')
        self.timeButtons[1].place(anchor="center",
                                  relx=0.5,
                                  rely=0.5,
                                  width=190,
                                  height=110)

        self.timeButtons.append(
            Button(master=self.frame,
                   text="60 min",
                   command=lambda: self.clickTimeSelect(2),
                   bg="#fff",
                   activebackground="#fff",
                   fg="#265B78",
                   activeforeground="#265B78",
                   borderwidth=0))

        self.timeButtons[2]["font"] = font.Font(family='Arial',
                                                size=40,
                                                weight='bold')
        self.timeButtons[2].place(anchor="center",
                                  relx=0.8,
                                  rely=0.5,
                                  width=190,
                                  height=110)

        self.ButtonStart = Button(master=self.frame,
                                  text="Starten",
                                  command=self.clickButton,
                                  bg="#265B78",
                                  activebackground="#265B78",
                                  fg="#ffffff",
                                  activeforeground="#ffffff",
                                  state="disabled",
                                  borderwidth=0)
        self.ButtonStart["font"] = font.Font(family='Arial',
                                             size=20,
                                             weight='bold')
        self.ButtonStart.place(anchor="center",
                               relx=0.5,
                               rely=0.9,
                               width=210,
                               height=80)

    def clear(self):
        self.frame.destroy()
Example #40
0
class MyFirstGUI:
    def __init__(self, master):
        self.master = master
        master.title("URBAN SOUND CLASSIFICATION---DHARMESH SINGH")
        self.msg = "Load the sound and predict the class"
        self.label = Label(master, text=self.msg)
        self.label.pack(pady=10)

        self.load_sound_button = Button(master,
                                        text="Load",
                                        command=self.load_sound,
                                        bg="light green",
                                        fg="black")
        self.load_sound_button.pack(pady=10)

        self.fileLabel = Label(master,
                               text="no file selected",
                               bg="white",
                               fg="black")
        self.fileLabel.pack(pady=10)

        self.play_sound_button = Button(master,
                                        text="PLAY TO LISTEN",
                                        command=self.play_sound,
                                        bg="light green",
                                        fg="black")
        self.play_sound_button.pack(pady=10)

        self.playLabel = Label(master, text="", bg="white", fg="black")
        self.playLabel.pack(pady=10)

        self.predict_button = Button(master,
                                     text="Predict",
                                     command=self.predict_class,
                                     bg="yellow",
                                     fg="black")
        self.predict_button.pack(pady=10)

        self.outlabel = Label(master, bg="white", fg="black")
        self.outlabel.pack(pady=10)

        self.close_button = Button(master,
                                   text="Close",
                                   command=master.quit,
                                   bg="red",
                                   fg="white")
        self.close_button.pack(pady=10)

    def load_sound(self):
        root.filename = filedialog.askopenfilename(
            initialdir=
            "/PycharmProjects/NITtrichy/SOUND-CLASSFICATION/UrbanSound8K/audio",
            title="Select file",
            filetypes=(("wav files", "*.wav"), ("all files", "*.*")))
        l = root.filename.split("/")
        self.fileLabel["text"] = l[-1] + " is loaded"

    def play_sound(self):
        l = root.filename.split("/")
        self.playLabel.config(text=l[-1] + " is played!!")
        playsound(root.filename)

    def predict_class(self):
        features = extract_features(root.filename)
        l = root.filename.split("/")
        features = np.reshape(features, (1, 7, 7, 1))
        res = class_model.predict_classes(features)
        sound_class = get_class(res[0])
        self.outlabel.config(text="CLASS: " + sound_class)
        print("%s %d %s" % (l[-1], res[0], sound_class))
Example #41
0
#!/usr/bin/env python
#-*- coding: utf-8 -*-

import GUI
import tkinter
import os
from tkinter import Button


def callback():
    cmd = 'python main.py'
    os.system(cmd)
    exit(0)


if __name__ == '__main__':
    window = tkinter.Tk()
    gui_chess_board = GUI.Chess_Board_Frame(window)

    b = Button(window, text="Restart", command=callback)

    gui_chess_board.pack()
    b.pack()
    window.mainloop()
  screen_height = root.winfo_screenheight()
  x = (screen_width/2) - (width/2)
  y = (screen_height/2) - (height/2)
  root.geometry('%dx%d+%d+%d' % (width, height, x, y))

if __name__ == "__main__":
  width_application = 350
  height_application = 150
  root = Tk()
  center_window(root, width_application, height_application)
  root.iconbitmap('main.ico')
  root.title("Check_GIF")
  root.minsize(width_application,height_application)
  menubar = create_menu()
  root.config(menu = menubar)
  label_new_communicates = Label(root)
  label_last_check = Label(root)
  write_information_about_new_messages()
  write_date_time_last_check_new_information()
  check_icon_svg = PhotoImage(file = "check_icon.svg")
  check_button = Button(root, text = "Check new communicates", image = check_icon_svg, compound = "left", 
    activebackground = "green", bg = "white", command = manually_check_new_messages)
  check_button.place(x = 35, y = 150)
  check_button.pack()
  label = Label(root)
  label.pack(side = BOTTOM)
  counter_label(label)
  check_new_messages()
  root.protocol("WM_DELETE_WINDOW", confirm_quit)
  root.mainloop()
from tkinter import Tk, Button
# alternate version
# from tkinter.messagebox import showinfo
from time import strftime, localtime


def clicked():
    'prints day and time info'
    time = strftime('Day:  %d %b %Y\nTime: %H:%M:%S %p\n', localtime())
    print(time)
    # alternate version:
    # showinfo(message = time)


root = Tk()

# create button labeled 'Click it' and event handler clicked()
button = Button(
    root,
    text='Click it',  # text on top of button
    command=clicked)  # button click event handler

button.pack()
root.mainloop()
Example #44
0
    def initBuild(self):
        self.time = None

        self.frame = Frame(width=1000, height=800)
        self.frame.place(x=0, y=0)
        LabelCreate = Label(master=self.frame,
                            text="Spiel erstellen",
                            fg="#417D9E")
        LabelCreate["font"] = font.Font(family='Arial', size=50, weight='bold')
        LabelCreate.place(anchor="center", relx=0.5, rely=0.1)

        img = self._screenManager.imageHandler.images["Back"]

        self.buttonBack = Button(command=self.backButton,
                                 master=self.frame,
                                 image=img,
                                 borderwidth=0)
        self.buttonBack.place(anchor="center",
                              relx=0.1,
                              rely=0.1,
                              width=85,
                              height=85)

        LabelTime = Label(master=self.frame, text="Zeitlimit", fg="#000000")
        LabelTime["font"] = font.Font(family='Arial', size=30)
        LabelTime.place(anchor="center", relx=0.5, rely=0.38)

        self.timeButtons = []
        self.timeButtons.append(
            Button(master=self.frame,
                   text="1 min",
                   bg="#fff",
                   command=lambda: self.clickTimeSelect(0),
                   activebackground="#fff",
                   fg="#265B78",
                   activeforeground="#265B78",
                   borderwidth=0))

        self.timeButtons[0]["font"] = font.Font(family='Arial',
                                                size=40,
                                                weight='bold')
        self.timeButtons[0].place(anchor="center",
                                  relx=0.2,
                                  rely=0.5,
                                  width=190,
                                  height=110)

        self.timeButtons.append(
            Button(master=self.frame,
                   text="10 min",
                   bg="#fff",
                   command=lambda: self.clickTimeSelect(1),
                   activebackground="#fff",
                   fg="#265B78",
                   activeforeground="#265B78",
                   borderwidth=0))

        self.timeButtons[1]["font"] = font.Font(family='Arial',
                                                size=40,
                                                weight='bold')
        self.timeButtons[1].place(anchor="center",
                                  relx=0.5,
                                  rely=0.5,
                                  width=190,
                                  height=110)

        self.timeButtons.append(
            Button(master=self.frame,
                   text="60 min",
                   command=lambda: self.clickTimeSelect(2),
                   bg="#fff",
                   activebackground="#fff",
                   fg="#265B78",
                   activeforeground="#265B78",
                   borderwidth=0))

        self.timeButtons[2]["font"] = font.Font(family='Arial',
                                                size=40,
                                                weight='bold')
        self.timeButtons[2].place(anchor="center",
                                  relx=0.8,
                                  rely=0.5,
                                  width=190,
                                  height=110)

        self.ButtonStart = Button(master=self.frame,
                                  text="Starten",
                                  command=self.clickButton,
                                  bg="#265B78",
                                  activebackground="#265B78",
                                  fg="#ffffff",
                                  activeforeground="#ffffff",
                                  state="disabled",
                                  borderwidth=0)
        self.ButtonStart["font"] = font.Font(family='Arial',
                                             size=20,
                                             weight='bold')
        self.ButtonStart.place(anchor="center",
                               relx=0.5,
                               rely=0.9,
                               width=210,
                               height=80)
Example #45
0
def showLeaderboard():  #this functions outputs the leaderboard on screen
    authentication.pack_forget()  #hiding the past canvas

    players = [
    ]  #here will be stored the players with their score in format (score, player_name)

    try:
        with open("leaderboard.txt",
                  "r") as file:  #opening the leaderboard file
            for line in file:
                elements = line.rstrip("\n").split(
                    separator)  #parsing the input
                players.append(
                    (int(elements[1]), elements[0]))  #storing each player
    except:
        pass

    players.sort(
        reverse=True
    )  #sorting the players after their score so that the best score will be the first

    leaderboard.create_text(width / 2,
                            50,
                            text="Hall of Fame",
                            fill="yellow",
                            font=("Arial Bold",
                                  60))  #informations for the user
    leaderboard.create_text(
        width / 2,
        100,
        text="Displaying best score for each of the top 10 players",
        fill="white",
        font=("Arial Bold", 20))

    seenPlayers = set(
    )  #this set helps us to output only the best score of each player
    index = 0
    for element in players:
        score, name = element
        if name in seenPlayers:  #here we ensure that we did not output this player before with a higher score
            continue
        seenPlayers.add(name)  #marking that we will output this player
        leaderboard.create_text(
            width / 3 + 50,
            index * 40 + 140,
            text=str(index + 1) + ". " + str(name) + " -> " + str(score) +
            " points",
            anchor="nw",
            fill="white",
            font=("Arial Bold", 30))  #printing the player with their score
        index += 1
        if index == 10:  #ensuring we print only top 10 players
            break

    global goBackToMainMenu
    goBackToMainMenu = False
    backButton = Button(
        text="Go to Main Menu",
        highlightbackground="black",
        command=setGoBackToMainMenu)  #setting the go back to main menu button
    leaderboard.create_window(100, 40,
                              window=backButton)  #placing the button on screen

    leaderboard.pack()  #showing the leaderboard canvas on screen
    leaderboard.focus_set(
    )  #focusing on it in order to ensure that every key pressed will be registered in this canvas
    window.update()  #refreshing the screen
    while not goBackToMainMenu:  #we remain in this screen until the user prompts us to go back to main menu by pressing the button
        sleep(0.0001)
        window.update()

    leaderboard.pack_forget()  #hiding the canvas of the leaderboard

    authentication.pack()  #showing the old canvas of the main menu
    authentication.focus_set()  #focusing on it
    window.update()  #refreshing the screen
Example #46
0
def PigLatinWrapper():
    inString = EngWord.get()
    PLWord = PigLatin(inString)
    OutWord.set(PLWord)


root = Tk()

EngWord = StringVar()
OutWord = StringVar()

t1 = Label(root, text="English to Pig Latin translator")
t1.grid(row=0, column=0, columnspan=2)

t2 = Label(root, text="English:")
t2.grid(row=1, column=0)

e1 = Entry(root, textvariable=EngWord)
e1.grid(row=1, column=1)

t3 = Label(root, text='Pig Latin:')
t3.grid(row=2, column=0)

t4 = Label(root, textvariable=OutWord)
t4.grid(row=2, column=1)

b1 = Button(root, text='Translate', command=PigLatinWrapper)
b1.grid(row=3, column=1)

root.mainloop()
Example #47
0
canvas.bind(fireKey, fire)  #binding the fire key of the ship
canvas.bind("<Key>", saveLastKey)  #registering the last key pressed

txt = "Score: " + str(score)
scoreText = canvas.create_text(width / 2,
                               20,
                               fill="white",
                               font=("Times 20 italic bold", 30),
                               text=txt)  #displaying the score on the screen

isPaused = False
pauseImage = PhotoImage(
    file="pause.gif")  #importing the image for the pause button
pauseButton = Button(image=pauseImage,
                     highlightbackground="black",
                     bg="black",
                     fg="black",
                     bd=0,
                     command=changePause)  #creating the pause button
canvas.create_window(width - 50, 30,
                     window=pauseButton)  #placing the pause button

while True:  #the actual game loop
    gameActive = True

    if (
            isPaused
    ):  #if the pause button is pressed then the pause screen should be displayed
        gameActive = False
        pauseScreen()

    cheatCode()  #checking if the last 4 keys pressed are cheat codes
Example #48
0
def saveLoadGame(canSave):  #this is the actual save/load menu
    saveLoadCanvas.pack()  #showing the menu
    saveLoadCanvas.focus_set(
    )  #focusing on the menu so that every key registered will we on that screen

    global goBackToMainMenu
    goBackToMainMenu = False
    backButton = Button(text="Go back",
                        highlightbackground="black",
                        command=setGoBackToMainMenu
                        )  #this button prompts the iser back to the old menu
    saveLoadCanvas.create_window(
        100, 40, window=backButton)  #placing the button on the screen

    saveLoadCanvas.create_text(width / 2,
                               40,
                               text="Type the save's name",
                               fill="white",
                               font=("Arial Bold",
                                     30))  #information for the user
    searchBar = Entry(window, highlightbackground="black"
                      )  #the box where the user will type the name of the save
    saveLoadCanvas.create_window(width / 2, 70,
                                 window=searchBar)  #placing it on the screen

    loadButton = Button(
        text="Load Game",
        highlightbackground="black",
        command=loadGame,
        width=10
    )  # #this button will load the game with the name typed by the user
    saveLoadCanvas.create_window(width / 2, 130,
                                 window=loadButton)  #placing the button
    saveLoadCanvas.create_text(
        width / 2,
        160,
        text="After loading just return to the game and start playing",
        fill="white",
        font=("Arial Bold", 20))  #information for the user

    if canSave:  #this ensure that we don't have the save game option when this window is opened from the main menu of the game because we do not have anything to save at that moment
        saveButton = Button(text="Save Game",
                            highlightbackground="black",
                            command=saveGame,
                            width=10)  #save game button
        saveLoadCanvas.create_window(width / 2, 100,
                                     window=saveButton)  #placing the button

    saveLoadCanvas.create_text(width / 2,
                               250,
                               text="Saved games: ",
                               fill="white",
                               font=("Arial Bold",
                                     30))  #information for the user
    while not goBackToMainMenu:  #we remain into this window until the user wants to go back to the old menu
        global gameName
        gameName = searchBar.get()  #getting the game name typed by the user

        loadedGames = {
        }  # every element will have the form {gamename : [score, speed[0], speed[1], x1, y1, x2, y2, ....] } where xi and yi are coordinates of the invaders
        try:  #we use try except block because it is possible that we don't have any save yet, so the file is not created and the game should not crash
            with open("saves.txt",
                      "r") as file:  #loading the old saves from the file
                for index, line in enumerate(file):
                    line = line.rstrip("\n").split(
                        separator)  #parsing the input
                    newElement = []
                    for index in range(1, len(line)):
                        newElement.append(float(
                            line[index]))  #saving this save's data
                    loadedGames[line[0]] = newElement
        except:
            pass

        for index, saveName in enumerate(
                loadedGames.keys()):  #printing to the screen every save made
            saveLoadCanvas.create_text(width / 2,
                                       295 + index * 35,
                                       text=saveName,
                                       fill="white",
                                       font=("Arial", 25))

        sleep(0.0001)
        window.update()  #refreshing screen

    saveLoadCanvas.pack_forget()  #hiding the save/load menu
Example #49
0
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.ranking = []
        ## Define os três frames existentes na janela principal
        ## A janela principal foi dividida em 3 frames (esquerda, central e direita)
        self.leftframe = Frame(self)
        self.leftframe.grid(row=0, column=0, stick=Tk.NS + Tk.E)
        self.centerframe = Frame(self)
        self.centerframe.grid(row=0, column=1, stick=Tk.NS)
        self.rightframe = Frame(self)
        self.rightframe.grid(row=0, column=2, stick=Tk.NS + Tk.W)
        # Inicializei as instancias aqui porque senão self.botaoSelecionaEntrada\
        # não existe quando da criação dos botoes do frame esquerdo
        # container 1 - contem os objetos para leitura de arquivo
        # container 2 - contem os objetos para entrada de dados manual
        # container 3 - contem os objetos para escolha aleatoria dos rankings
        self.container1 = LabelFrame(self.centerframe,
                                     text="Escolha o arquivo",
                                     padx=5,
                                     pady=5)
        self.container2 = LabelFrame(self.centerframe,
                                     text="Entrada de dados",
                                     padx=5,
                                     pady=5)
        self.container3 = LabelFrame(self.centerframe,
                                     text="Escolha aleatória",
                                     padx=5,
                                     pady=5)

        ###
        #### Monta frame esquerdo
        #### Frame dos botões
        ###
        lblframe = LabelFrame(self.leftframe,
                              text="Selecione entrada",
                              padx=5,
                              pady=5)
        lblframe.grid(row=0, column=0)
        button1 = Button(lblframe,
                         text="Arquivo",
                         width=20,
                         command=lambda: self.botaoSelecionaEntrada(1))
        button1.grid(row=0, column=0)
        button2 = Button(lblframe,
                         text="Manual",
                         width=20,
                         command=lambda: self.botaoSelecionaEntrada(2))
        button2.grid(row=1, column=0)
        button3 = Button(lblframe,
                         text="Aleatório",
                         width=20,
                         command=lambda: self.botaoSelecionaEntrada(3))
        button3.grid(row=2, column=0)
        lblframe = LabelFrame(self.leftframe,
                              text="Calculadora",
                              padx=5,
                              pady=5)
        lblframe.grid(row=3, column=0, pady=20)
        button1 = Button(lblframe,
                         text="Calculadora",
                         width=20,
                         command=lambda: self.Calculadora())
        button1.grid(row=0, column=0)
        button2 = Button(lblframe,
                         text="Reset",
                         width=20,
                         command=lambda: self.resetDisplayResults())
        button2.grid(row=1, column=0)

        ###
        ### Monta Frame central
        ###
        ### O Frame central contém 3 "containers" que serão ligados e desligados em tempo
        ### de execução através dos botões existentes no frame esquerdo
        ###
        ##Entrada através de arquivo
        ##
        self.mySelectionF = Tk.StringVar()
        labelvalue = self.mySelectionF
        self.container1.grid(row=0, column=0)
        buttonFile = Tk.Button(self.container1,
                               text='Ler arquivo',
                               width=10,
                               command=self.askopenfilename)
        buttonFile.grid(row=0, column=0, sticky='N')
        self.displayRanking1()
        ### Desliga objeto do frame da tela
        self.container1.isgridded = True
        #self.container1.grid_forget()

        #
        # Entrada manual
        #
        #### DESISTI DE FAZER ASSIM SE DER TEMPO VOLTO A FAZER SENAO
        #### FAÇO DEPOIS DA ENTRAGA DA AD
        ####
        #self.mySelection = Tk.StringVar()
        #labelvalue = self.mySelection
        #self.container2 = LabelFrame(self.centerframe, text="Entrada de dados", padx=5, pady=5) ## Foi criado la em cima
        #self.container2.grid(row=0, column=0)
        # label com nome do ranking
        #self.label = Label(self.container2, text=labelvalue)
        #self.label.grid(row=0,column=1)
        # campo de entrada
        #entryA = Entry(self.container2,width=6)               #criamos o campo de texto
        #entryA.grid(column=0,row=1,sticky='EW'+'S')
        # Botao
        #button4 = Tk.Button(self.container2, text = '->', width = 10)
        #button4.grid( row=2,column=0,sticky='EW'+'N')
        #Combobox
        #self.comboboxM = ttk.Combobox(self.container2, width= 15, state="readonly", textvariable = self.mySelection)
        #self.comboboxM["values"] = ("Ranking 1", "Ranking 2")
        #self.comboboxM.grid(row=0, column=0)
        #self.comboboxM.bind("<<ComboboxSelected>>", self.callbackFunc)
        #ListBox
        #value=["one", "two", "three", "four", "five", "six", "seven","eight","nine","ten","eleven","twelve"] ### Somente para teste
        #value = []
        #self.listbox = Listbox(self.container2,selectmode=Tk.SINGLE)
        #scrollbar = Tk.Scrollbar(self.container2, orient=Tk.VERTICAL)
        #self.listbox.config( yscrollcommand=scrollbar.set)
        #scrollbar.configure(command=self.listbox.yview)
        #scrollbar.config(command=self.listbox.yview)
        #self.listbox.insert(Tk.END, None)
        #for item in value:
        #    self.listbox.insert(Tk.END, item)
        #self.listbox.grid(row=1, column=1,stick=Tk.W)
        #scrollbar.grid(row=1,column=2,stick=Tk.NS+Tk.W)

        ### Aqui resolvi fazer assim, senão não ia dar tempo para fazer do jeito que eu queria
        ### Caminho mais fácil, senão nao consigo fazer os testes se é que vou conseguir
        self.container2.grid(row=0, column=0)
        self.v1 = Tk.IntVar(value=1)
        #self.v1 = Tk.StringVar(value="1")
        self.v1.set(1)
        self.v2 = Tk.IntVar(value=1)
        #self.v2 = Tk.StringVar(value="1")
        self.v2.set(1)

        self.displayEntradaManual()
        #self.label = Label(self.container2, text="Escolha o tipo de entrada")
        #self.label.grid(row=0,column=0, columnspan=2)
        #self.rb1 = Tk.Radiobutton(self.container2, text="Ranking", variable=self.v1, value=1,state=Tk.ACTIVE,indicatoron=1)
        #self.rb1.grid(row=1,column=0)
        #self.rb2 = Tk.Radiobutton(self.container2, text="Score", variable=self.v1, value=2,state=Tk.ACTIVE,indicatoron=1)
        #self.rb2.grid(row=1,column=1)
        #self.label = Label(self.container2, text="Ranking / Score 1")
        #self.label.grid(row=2,column=0)
        #self.entryM1 = Entry(self.container2,width=30)               #criamos o campo de texto
        #self.entryM1.grid(row=3,column=0,sticky='EW'+'S',columnspan=2)

        #self.rb3 = Tk.Radiobutton(self.container2, text="Ranking", variable=self.v2, value=1,state=Tk.ACTIVE,indicatoron=1)
        #self.rb3.grid(row=4,column=0)
        #self.rb4 = Tk.Radiobutton(self.container2, text="Score", variable=self.v2, value=2,state=Tk.ACTIVE,indicatoron=1)
        #self.rb4.grid(row=4,column=1)
        #self.label = Label(self.container2, text="Ranking / Score 2")
        #self.label.grid(row=5,column=0)
        #self.entryM2 = Entry(self.container2,width=30)               #criamos o campo de texto
        #self.entryM2.grid(row=6,column=0,sticky='EW'+'S',columnspan=2)
        self.container2.isgridded = False
        self.container2.grid_forget()

        ##entrada aleatoria
        #self.container3 = LabelFrame(self.centerframe, text="Entrada de dados", padx=5, pady=5)
        self.mySelectionA = Tk.StringVar()
        self.container3.grid(row=0, column=0)
        self.container3A = LabelFrame(self.container3,
                                      text="Define tamanho",
                                      padx=5,
                                      pady=5)
        self.container3A.grid(row=0, column=0)
        # label com nome do ranking
        self.label = Label(self.container3A,
                           text='Selecione o tamanho dos rankings')
        self.label.grid(row=0, column=0, sticky="S")
        self.entryB = Entry(self.container3A,
                            width=6)  #criamos o campo de texto
        self.entryB.grid(row=1, column=0, sticky='EW' + 'S')
        button5 = Tk.Button(self.container3A,
                            text='Gerar',
                            width=10,
                            command=self.gerarRankingAleatorio)
        button5.grid(row=2, column=0, sticky='EW' + 'N')

        self.displayRanking()
        #self.container3B = LabelFrame(self.container3,text="Visualiza RANKINGs", padx=5, pady=5)
        #self.container3B.grid(row=0, column=1)
        self.container3.isgridded = False
        self.container3.grid_forget()
        ####self.container3B = LabelFrame(self.container3, text="Visualiza RANKINGs", padx=5, pady=5)
        ####self.container3B.grid(row=0, column=1)
        ####self.comboboxA = ttk.Combobox(self.container3B, width= 15, state="readonly", textvariable = self.mySelectionA)
        ####self.comboboxA["values"] = ("Ranking 1", "Ranking 2")
        ####self.comboboxA.grid(row=0, column=1)
        ####self.comboboxA.bind("<<ComboboxSelected>>", self.callbackRandom)
        #value=["one", "two", "three", "four", "five", "six", "seven","eight","nine","ten","eleven","twelve"] ### Somente para teste
        ####value = []
        ####self.listbox = Listbox(self.container3B,selectmode=Tk.SINGLE)
        ####scrollbar = Tk.Scrollbar(self.container3B, orient=Tk.VERTICAL)
        ####self.listbox.config( yscrollcommand=scrollbar.set)
        ####scrollbar.configure(command=self.listbox.yview)
        ####scrollbar.config(command=self.listbox.yview)
        ####self.listbox.insert(Tk.END, None)
        ####for item in value:
        ####    self.listbox.insert(Tk.END, item)
        ####self.listbox.grid(row=1, column=1,stick=Tk.W)
        ####scrollbar.grid(row=1,column=2,stick=Tk.NS+Tk.W)
        ####self.container3.isgridded = False
        ####self.container3.grid_forget()

        ###
        #### Monta frame direito
        ###
        self.lblframe = LabelFrame(self.rightframe,
                                   text="RESULTADOS",
                                   padx=5,
                                   pady=5)
        self.lblframe.grid(row=0, column=0)
        self.label = Label(self.lblframe, text="Kemeny = ")
        self.label.grid(row=0, column=0, sticky=Tk.W)
        result = str(0)
        self.labelkemeny = Label(self.lblframe, text=result)
        self.labelkemeny.grid(row=0, column=1)
        self.label = Label(self.lblframe, text="Footrule = ")
        self.label.grid(row=1, column=0, sticky=Tk.W)
        self.labelfootrule = Label(self.lblframe, text=result)
        self.labelfootrule.grid(row=1, column=1)
        self.label = Label(self.lblframe, text="*** Inversões ***")
        self.label.grid(row=2, column=0)
        self.label = Label(self.lblframe, text="Inversões Ranking 1 = ")
        self.label.grid(row=3, column=0, sticky=Tk.W)
        self.label = Label(self.lblframe, text="Inversões Ranking 2 = ")
        self.label.grid(row=4, column=0, sticky=Tk.W)
        self.labelinv1 = Label(self.lblframe, text=result)
        self.labelinv1.grid(row=3, column=1)
        self.labelinv2 = Label(self.lblframe, text=result)
        self.labelinv2.grid(row=4, column=1)
        self.bye = Button(self.rightframe, text="Bye Bye", command=self.quit)
        self.bye.grid(row=5, column=0)
        self.pack()
Example #50
0
def customizeKeys(
):  #this functions prompts the screen where the key customizations are done
    global leftKey, rightKey, fireKey

    authentication.pack_forget()  #hiding the old canvas from the main menu

    customization.pack()  #showing the new canvas for the customization screen
    customization.focus_set(
    )  #this is to ensure we process every key pressed on this canvas and not on others

    customization.create_text(width / 3,
                              150,
                              text="Choose a key by pressing it!",
                              fill="white",
                              anchor="nw",
                              font=("Arial Bold",
                                    30))  #informative text for the user
    global chosenKeyText
    chosenKeyText = customization.create_text(
        width / 3,
        200,
        text="You chose: ",
        fill="white",
        anchor="nw",
        font=("Arial Bold", 30)
    )  #informative text for the user that shows the last key pressed
    aux = Entry(
        window,
        bg="black",
        fg="black",
        borderwidth=0,
        highlightthickness=0,
        highlightbackground="black"
    )  #this entry is made to capture the last key pressed and is hidden from the user's view
    customization.create_window(
        width - 100, height - 100, window=aux
    )  #the entry seems to be placed on the screen but is fully black as the background so it is hidden
    aux.focus_set(
    )  #focusing on the entry in order to register every key pressed without clicking on the specific entry because is hidden

    changeLeftButton = Button(
        text="Change Left Key",
        highlightbackground="black",
        command=changeLeftKey,
        width=15)  #this button changes left key when pressed
    changeRightButton = Button(
        text="Change Right Key",
        highlightbackground="black",
        command=changeRightKey,
        width=15)  #this button changes right key when pressed
    changeFireButton = Button(
        text="Change Fire Key",
        highlightbackground="black",
        command=changeFireKey,
        width=15)  #this button changes fire key when pressed
    customization.create_window(
        width / 2, 270,
        window=changeLeftButton)  #placing buttons on the screen
    customization.create_window(width / 2, 300, window=changeRightButton)
    customization.create_window(width / 2, 330, window=changeFireButton)

    currentLeft = customization.create_text(
        width / 3,
        390,
        text="Current left key: " + str(leftKey),
        fill="white",
        anchor="nw",
        font=("Arial Bold", 30)
    )  #displaying current keys chosen by the use for left, right and fire
    currentRight = customization.create_text(width / 3,
                                             430,
                                             text="Current right key: " +
                                             str(rightKey),
                                             fill="white",
                                             anchor="nw",
                                             font=("Arial Bold", 30))
    currentFire = customization.create_text(width / 3,
                                            470,
                                            text="Current fire key: " +
                                            str(fireKey),
                                            fill="white",
                                            anchor="nw",
                                            font=("Arial Bold", 30))

    global newKey, goBackToMainMenu
    goBackToMainMenu = False
    newKey = None
    backButton = Button(
        text="Go to Main Menu",
        highlightbackground="black",
        command=setGoBackToMainMenu
    )  #this button is made to let the user go back to main menu when pressed
    customization.create_window(100, 40,
                                window=backButton)  #button is placed here
    while not goBackToMainMenu:  #this loop waits for the user until they want to go back to main menu
        aux.bind('<Key>', processKey)  #here is registered the last key pressed
        customization.itemconfig(
            currentLeft, text="Current left key: " + str(leftKey)
        )  #here are updated the key mappings on the screen so that the user can see their current choices
        customization.itemconfig(currentRight,
                                 text="Current right key: " + str(rightKey))
        customization.itemconfig(currentFire,
                                 text="Current fire key: " + str(fireKey))

        sleep(
            0.0001
        )  #this has the purpose to let the screen be updated almost instantly
        window.update()  #refresh the window to see the changes

    customization.pack_forget()  #we hide the customize key canvas

    authentication.pack()  #here we return to the main menu
    authentication.focus_set(
    )  #this is to ensure we process every key pressed on this canvas and not on others
    window.update()  #refresh the window to see the new canvas
Example #51
0

def satis():
    x = nm
    x.satis()


def urunekle():
    global nm

    def ekle(name):
        global nm
        nm = urun(str(name))
        print("basarili")
        urunlistesi.append(nm)
        addp.destroy()

    addp = tkinter.Toplevel()
    addp.title(" URUN EKLE ")
    x = Entry(addp, width=4)
    x.bind("<Return>", (lambda event: ekle(x.get())))
    x.pack()


Button(text="Urünleri Listele", command=listele).place(x=140, y=120)
Button(text="Alım", command=alim).place(x=300, y=120)
Button(text="Satis", command=satis).place(x=400, y=120)
Button(text="URUN EKLE", command=urunekle).place(x=400, y=200)

asn.mainloop()

def generate():
    password = rnd_pwd()
    entry.insert(10, password)


#Function to copy strin to clipboard
def copy_():
    random_pass = entry.get()
    copy(random_pass)


#Buttons
cpy_btn = Button(labelBg,
                 text='Copy to Clipboard',
                 bg=color,
                 activebackground=color2,
                 borderwidth=0,
                 command=copy_)
cpy_btn.place(x=105, y=368)
gn_btn = Button(labelBg,
                text='Generate Password',
                bg=color,
                activebackground=color2,
                borderwidth=0,
                command=generate)
gn_btn.place(x=418, y=368)

root.mainloop()
Example #53
0
    def build(self):
        """
        Method for building program interface.
        """

        # Creates a title for the entry of the text to be translated.
        Label(
            self.__root,
            bg=self.window_bg,
            font=self.__label_font,
            fg=self.__label_fg,
            text="Text:",
            pady=10
        ).pack()

        # Creates a frame to place the input field.
        input_frame = Frame(self.__root, bg=self.window_bg)
        input_frame.pack()

        # Creates a field for the user to enter the text.
        self.__inputText = Text(
            input_frame,
            width=self.__text_width,
            height=self.__inputText_height,
            bg=self.__text_bg,
            fg=self.__text_fg,
            font=self.__text_font,
            wrap="word"
        )
        self.__inputText.insert(0.0, " Enter text here...")

        # Creates a scroll bar for the input field.
        scrollbar = Scrollbar(input_frame)
        scrollbar.pack(side="right", fill="y")
        self.__inputText.config(yscrollcommand=scrollbar.set)
        scrollbar.config(command=self.__inputText.yview)

        self.__inputText.pack()

        # Creates field title where the translated text will be placed.
        Label(
            self.__root,
            bg=self.window_bg,
            font=self.__label_font,
            fg=self.__label_fg,
            text="Morse Code:",
            pady=10
        ).pack()

        # Creates frame to place the output field.
        output_frame = Frame(self.__root, bg=self.window_bg)
        output_frame.pack()

        # Field to place the translated text.
        self.__outputText = Text(
            output_frame,
            width=self.__text_width,
            height=self.__outputText_height,
            bg=self.__text_bg,
            fg=self.__text_fg,
            font=self.__text_font,
            wrap="word"
        )
        self.__outputText.insert(0.0, " The morse code will appear here.")

        # Creates a scroll bar for the output field.
        scrollbar = Scrollbar(output_frame)
        scrollbar.pack(side="right", fill="y")
        self.__outputText.config(yscrollcommand=scrollbar.set)
        scrollbar.config(command=self.__outputText.yview)

        self.__outputText.pack()

        # Creates a frame to insert the buttons.
        buttons_frame = Frame(self.__root, bg=self.window_bg, pady=20)
        buttons_frame.pack()

        # Creates a "border" for the button.
        button1_frame = Frame(buttons_frame, bg="black", padx=2, pady=2)
        button1_frame.pack(side="left")

        # Creates a button to translate the text.
        self.__button1 = Button(
            button1_frame,
            width=self.__button_width,
            height=self.__button_height,
            relief=self.__button_relief,
            bg=self.__button_bg,
            fg=self.__button_fg,
            font=self.__button_font,
            text="Translate",
            command=self.translate
        )
        self.__button1.pack()

        # If the user's OS is Windows, a button will be created
        # to reproduce the sound of the Morse code.
        if "win" in sys.platform:
            Label(buttons_frame, bg=self.window_bg, padx=5).pack(side="left")

            # Creates a "border" for the button.
            button2_frame = Frame(buttons_frame, bg="black", padx=2, pady=2)
            button2_frame.pack(side="left")

            #Creates a button to reproduce Morse code sound.
            self.__button2 = Button(
                button2_frame,
                width=self.__button_width,
                height=self.__button_height,
                relief=self.__button_relief,
                bg=self.__button_bg,
                fg=self.__button_fg,
                font=self.__button_font,
                text="Play",
                command=self.play
            )
            self.__button2.pack()

        self.__root.mainloop()
Example #54
0
class Application(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.ranking = []
        ## Define os três frames existentes na janela principal
        ## A janela principal foi dividida em 3 frames (esquerda, central e direita)
        self.leftframe = Frame(self)
        self.leftframe.grid(row=0, column=0, stick=Tk.NS + Tk.E)
        self.centerframe = Frame(self)
        self.centerframe.grid(row=0, column=1, stick=Tk.NS)
        self.rightframe = Frame(self)
        self.rightframe.grid(row=0, column=2, stick=Tk.NS + Tk.W)
        # Inicializei as instancias aqui porque senão self.botaoSelecionaEntrada\
        # não existe quando da criação dos botoes do frame esquerdo
        # container 1 - contem os objetos para leitura de arquivo
        # container 2 - contem os objetos para entrada de dados manual
        # container 3 - contem os objetos para escolha aleatoria dos rankings
        self.container1 = LabelFrame(self.centerframe,
                                     text="Escolha o arquivo",
                                     padx=5,
                                     pady=5)
        self.container2 = LabelFrame(self.centerframe,
                                     text="Entrada de dados",
                                     padx=5,
                                     pady=5)
        self.container3 = LabelFrame(self.centerframe,
                                     text="Escolha aleatória",
                                     padx=5,
                                     pady=5)

        ###
        #### Monta frame esquerdo
        #### Frame dos botões
        ###
        lblframe = LabelFrame(self.leftframe,
                              text="Selecione entrada",
                              padx=5,
                              pady=5)
        lblframe.grid(row=0, column=0)
        button1 = Button(lblframe,
                         text="Arquivo",
                         width=20,
                         command=lambda: self.botaoSelecionaEntrada(1))
        button1.grid(row=0, column=0)
        button2 = Button(lblframe,
                         text="Manual",
                         width=20,
                         command=lambda: self.botaoSelecionaEntrada(2))
        button2.grid(row=1, column=0)
        button3 = Button(lblframe,
                         text="Aleatório",
                         width=20,
                         command=lambda: self.botaoSelecionaEntrada(3))
        button3.grid(row=2, column=0)
        lblframe = LabelFrame(self.leftframe,
                              text="Calculadora",
                              padx=5,
                              pady=5)
        lblframe.grid(row=3, column=0, pady=20)
        button1 = Button(lblframe,
                         text="Calculadora",
                         width=20,
                         command=lambda: self.Calculadora())
        button1.grid(row=0, column=0)
        button2 = Button(lblframe,
                         text="Reset",
                         width=20,
                         command=lambda: self.resetDisplayResults())
        button2.grid(row=1, column=0)

        ###
        ### Monta Frame central
        ###
        ### O Frame central contém 3 "containers" que serão ligados e desligados em tempo
        ### de execução através dos botões existentes no frame esquerdo
        ###
        ##Entrada através de arquivo
        ##
        self.mySelectionF = Tk.StringVar()
        labelvalue = self.mySelectionF
        self.container1.grid(row=0, column=0)
        buttonFile = Tk.Button(self.container1,
                               text='Ler arquivo',
                               width=10,
                               command=self.askopenfilename)
        buttonFile.grid(row=0, column=0, sticky='N')
        self.displayRanking1()
        ### Desliga objeto do frame da tela
        self.container1.isgridded = True
        #self.container1.grid_forget()

        #
        # Entrada manual
        #
        #### DESISTI DE FAZER ASSIM SE DER TEMPO VOLTO A FAZER SENAO
        #### FAÇO DEPOIS DA ENTRAGA DA AD
        ####
        #self.mySelection = Tk.StringVar()
        #labelvalue = self.mySelection
        #self.container2 = LabelFrame(self.centerframe, text="Entrada de dados", padx=5, pady=5) ## Foi criado la em cima
        #self.container2.grid(row=0, column=0)
        # label com nome do ranking
        #self.label = Label(self.container2, text=labelvalue)
        #self.label.grid(row=0,column=1)
        # campo de entrada
        #entryA = Entry(self.container2,width=6)               #criamos o campo de texto
        #entryA.grid(column=0,row=1,sticky='EW'+'S')
        # Botao
        #button4 = Tk.Button(self.container2, text = '->', width = 10)
        #button4.grid( row=2,column=0,sticky='EW'+'N')
        #Combobox
        #self.comboboxM = ttk.Combobox(self.container2, width= 15, state="readonly", textvariable = self.mySelection)
        #self.comboboxM["values"] = ("Ranking 1", "Ranking 2")
        #self.comboboxM.grid(row=0, column=0)
        #self.comboboxM.bind("<<ComboboxSelected>>", self.callbackFunc)
        #ListBox
        #value=["one", "two", "three", "four", "five", "six", "seven","eight","nine","ten","eleven","twelve"] ### Somente para teste
        #value = []
        #self.listbox = Listbox(self.container2,selectmode=Tk.SINGLE)
        #scrollbar = Tk.Scrollbar(self.container2, orient=Tk.VERTICAL)
        #self.listbox.config( yscrollcommand=scrollbar.set)
        #scrollbar.configure(command=self.listbox.yview)
        #scrollbar.config(command=self.listbox.yview)
        #self.listbox.insert(Tk.END, None)
        #for item in value:
        #    self.listbox.insert(Tk.END, item)
        #self.listbox.grid(row=1, column=1,stick=Tk.W)
        #scrollbar.grid(row=1,column=2,stick=Tk.NS+Tk.W)

        ### Aqui resolvi fazer assim, senão não ia dar tempo para fazer do jeito que eu queria
        ### Caminho mais fácil, senão nao consigo fazer os testes se é que vou conseguir
        self.container2.grid(row=0, column=0)
        self.v1 = Tk.IntVar(value=1)
        #self.v1 = Tk.StringVar(value="1")
        self.v1.set(1)
        self.v2 = Tk.IntVar(value=1)
        #self.v2 = Tk.StringVar(value="1")
        self.v2.set(1)

        self.displayEntradaManual()
        #self.label = Label(self.container2, text="Escolha o tipo de entrada")
        #self.label.grid(row=0,column=0, columnspan=2)
        #self.rb1 = Tk.Radiobutton(self.container2, text="Ranking", variable=self.v1, value=1,state=Tk.ACTIVE,indicatoron=1)
        #self.rb1.grid(row=1,column=0)
        #self.rb2 = Tk.Radiobutton(self.container2, text="Score", variable=self.v1, value=2,state=Tk.ACTIVE,indicatoron=1)
        #self.rb2.grid(row=1,column=1)
        #self.label = Label(self.container2, text="Ranking / Score 1")
        #self.label.grid(row=2,column=0)
        #self.entryM1 = Entry(self.container2,width=30)               #criamos o campo de texto
        #self.entryM1.grid(row=3,column=0,sticky='EW'+'S',columnspan=2)

        #self.rb3 = Tk.Radiobutton(self.container2, text="Ranking", variable=self.v2, value=1,state=Tk.ACTIVE,indicatoron=1)
        #self.rb3.grid(row=4,column=0)
        #self.rb4 = Tk.Radiobutton(self.container2, text="Score", variable=self.v2, value=2,state=Tk.ACTIVE,indicatoron=1)
        #self.rb4.grid(row=4,column=1)
        #self.label = Label(self.container2, text="Ranking / Score 2")
        #self.label.grid(row=5,column=0)
        #self.entryM2 = Entry(self.container2,width=30)               #criamos o campo de texto
        #self.entryM2.grid(row=6,column=0,sticky='EW'+'S',columnspan=2)
        self.container2.isgridded = False
        self.container2.grid_forget()

        ##entrada aleatoria
        #self.container3 = LabelFrame(self.centerframe, text="Entrada de dados", padx=5, pady=5)
        self.mySelectionA = Tk.StringVar()
        self.container3.grid(row=0, column=0)
        self.container3A = LabelFrame(self.container3,
                                      text="Define tamanho",
                                      padx=5,
                                      pady=5)
        self.container3A.grid(row=0, column=0)
        # label com nome do ranking
        self.label = Label(self.container3A,
                           text='Selecione o tamanho dos rankings')
        self.label.grid(row=0, column=0, sticky="S")
        self.entryB = Entry(self.container3A,
                            width=6)  #criamos o campo de texto
        self.entryB.grid(row=1, column=0, sticky='EW' + 'S')
        button5 = Tk.Button(self.container3A,
                            text='Gerar',
                            width=10,
                            command=self.gerarRankingAleatorio)
        button5.grid(row=2, column=0, sticky='EW' + 'N')

        self.displayRanking()
        #self.container3B = LabelFrame(self.container3,text="Visualiza RANKINGs", padx=5, pady=5)
        #self.container3B.grid(row=0, column=1)
        self.container3.isgridded = False
        self.container3.grid_forget()
        ####self.container3B = LabelFrame(self.container3, text="Visualiza RANKINGs", padx=5, pady=5)
        ####self.container3B.grid(row=0, column=1)
        ####self.comboboxA = ttk.Combobox(self.container3B, width= 15, state="readonly", textvariable = self.mySelectionA)
        ####self.comboboxA["values"] = ("Ranking 1", "Ranking 2")
        ####self.comboboxA.grid(row=0, column=1)
        ####self.comboboxA.bind("<<ComboboxSelected>>", self.callbackRandom)
        #value=["one", "two", "three", "four", "five", "six", "seven","eight","nine","ten","eleven","twelve"] ### Somente para teste
        ####value = []
        ####self.listbox = Listbox(self.container3B,selectmode=Tk.SINGLE)
        ####scrollbar = Tk.Scrollbar(self.container3B, orient=Tk.VERTICAL)
        ####self.listbox.config( yscrollcommand=scrollbar.set)
        ####scrollbar.configure(command=self.listbox.yview)
        ####scrollbar.config(command=self.listbox.yview)
        ####self.listbox.insert(Tk.END, None)
        ####for item in value:
        ####    self.listbox.insert(Tk.END, item)
        ####self.listbox.grid(row=1, column=1,stick=Tk.W)
        ####scrollbar.grid(row=1,column=2,stick=Tk.NS+Tk.W)
        ####self.container3.isgridded = False
        ####self.container3.grid_forget()

        ###
        #### Monta frame direito
        ###
        self.lblframe = LabelFrame(self.rightframe,
                                   text="RESULTADOS",
                                   padx=5,
                                   pady=5)
        self.lblframe.grid(row=0, column=0)
        self.label = Label(self.lblframe, text="Kemeny = ")
        self.label.grid(row=0, column=0, sticky=Tk.W)
        result = str(0)
        self.labelkemeny = Label(self.lblframe, text=result)
        self.labelkemeny.grid(row=0, column=1)
        self.label = Label(self.lblframe, text="Footrule = ")
        self.label.grid(row=1, column=0, sticky=Tk.W)
        self.labelfootrule = Label(self.lblframe, text=result)
        self.labelfootrule.grid(row=1, column=1)
        self.label = Label(self.lblframe, text="*** Inversões ***")
        self.label.grid(row=2, column=0)
        self.label = Label(self.lblframe, text="Inversões Ranking 1 = ")
        self.label.grid(row=3, column=0, sticky=Tk.W)
        self.label = Label(self.lblframe, text="Inversões Ranking 2 = ")
        self.label.grid(row=4, column=0, sticky=Tk.W)
        self.labelinv1 = Label(self.lblframe, text=result)
        self.labelinv1.grid(row=3, column=1)
        self.labelinv2 = Label(self.lblframe, text=result)
        self.labelinv2.grid(row=4, column=1)
        self.bye = Button(self.rightframe, text="Bye Bye", command=self.quit)
        self.bye.grid(row=5, column=0)
        self.pack()

    # Monta radiobutton no frame central container 2
    def displayEntradaManual(self):
        """@ Show RadioButton on container2 in Application Class
           @example self.displayEntradaManual()
        """
        self.label = Label(self.container2, text="Escolha o tipo de entrada")
        self.label.grid(row=0, column=0, columnspan=2)
        self.rb1 = Tk.Radiobutton(self.container2,
                                  text="Ranking",
                                  variable=self.v1,
                                  value=1,
                                  state=Tk.ACTIVE,
                                  indicatoron=1)
        self.rb1.grid(row=1, column=0)
        self.rb2 = Tk.Radiobutton(self.container2,
                                  text="Score",
                                  variable=self.v1,
                                  value=2,
                                  state=Tk.ACTIVE,
                                  indicatoron=1)
        self.rb2.grid(row=1, column=1)
        self.label = Label(self.container2, text="Ranking / Score 1")
        self.label.grid(row=2, column=0)
        self.entryM1 = Entry(self.container2,
                             width=30)  #criamos o campo de texto
        self.entryM1.grid(row=3, column=0, sticky='EW' + 'S', columnspan=2)

        self.rb3 = Tk.Radiobutton(self.container2,
                                  text="Ranking",
                                  variable=self.v2,
                                  value=1,
                                  state=Tk.ACTIVE,
                                  indicatoron=1)
        self.rb3.grid(row=4, column=0)
        self.rb4 = Tk.Radiobutton(self.container2,
                                  text="Score",
                                  variable=self.v2,
                                  value=2,
                                  state=Tk.ACTIVE,
                                  indicatoron=1)
        self.rb4.grid(row=4, column=1)
        self.label = Label(self.container2, text="Ranking / Score 2")
        self.label.grid(row=5, column=0)
        self.entryM2 = Entry(self.container2,
                             width=30)  #criamos o campo de texto
        self.entryM2.grid(row=6, column=0, sticky='EW' + 'S', columnspan=2)
        self.label = Label(self.container2,
                           text="Formato da entrada(ranking): 5 4 3 2 1")
        self.label.grid(row=7, column=0, sticky='W')
        self.label = Label(
            self.container2,
            text="Formato da entrada(score): 0.65 0.32 0.62 0.23 0.34")
        self.label.grid(row=8, column=0, sticky='W')
        self.container2.isgridded = False
        self.container2.grid_forget()

    # Reset nos valores do frame direito
    def resetDisplayResults(self):
        """@ Reset values kemeny, footrule and Inversions and clean labels
           @example self.resetDisplayResults()
        """
        del self.ranking[:]
        result = str(0)
        self.labelkemeny = Label(self.lblframe, text=result)
        self.labelkemeny.grid(row=0, column=1)
        self.labelfootrule = Label(self.lblframe, text=result)
        self.labelfootrule.grid(row=1, column=1)
        self.labelinv1 = Label(self.lblframe, text=result)
        self.labelinv1.grid(row=3, column=1)
        self.labelinv2 = Label(self.lblframe, text=result)
        self.labelinv2.grid(row=4, column=1)
        if self.buttonClick == 1:
            self.displayRanking1()
        if self.buttonClick == 2:
            self.entryM1.delete(0, 'end')  #limpamos o campo de texto
            self.entryM1.grid(row=3, column=0, sticky='EW' + 'S', columnspan=2)
            self.entryM2.delete(0, 'end')  #limpamos o campo de texto
            self.entryM2.grid(row=6, column=0, sticky='EW' + 'S', columnspan=2)
        if self.buttonClick == 3:
            self.displayRanking()
        messagebox.showinfo("Mensagem",
                            "Kemeny, footrule e inversões zeradas!")

    # Metodo que retorna um evento de selecao
    def displayRanking(self):
        """@ Show combobox on screen
           @example self.displayRanking()
        """
        self.container3B = LabelFrame(self.container3,
                                      text="Visualiza RANKINGs",
                                      padx=5,
                                      pady=5)
        self.container3B.grid(row=0, column=1)
        self.comboboxA = ttk.Combobox(self.container3B,
                                      width=15,
                                      state="readonly",
                                      textvariable=self.mySelectionA)
        self.comboboxA["values"] = ("Ranking 1", "Ranking 2")
        self.comboboxA.grid(row=0, column=1)
        self.comboboxA.bind("<<ComboboxSelected>>", self.callbackRandom)
        #value=["one", "two", "three", "four", "five", "six", "seven","eight","nine","ten","eleven","twelve"] ### Somente para teste
        self.displayRankingListbox()
        #####value = []
        #####self.listbox = Listbox(self.container3B,selectmode=Tk.SINGLE)
        #####scrollbar = Tk.Scrollbar(self, orient=Tk.VERTICAL)
        #####self.listbox.config( yscrollcommand=scrollbar.set)
        #####scrollbar.configure(command=self.listbox.yview)
        #####scrollbar.config(command=self.listbox.yview)
        #####self.listbox.insert(Tk.END, None)
        #####for item in value:
        #####    self.listbox.insert(Tk.END, item)
        #####self.listbox.grid(row=1, column=1,stick=Tk.W)
        #####scrollbar.grid(row=1,column=2,stick=Tk.NS+Tk.W)
        #self.container3B = LabelFrame(self.container3B,text="Visualiza RANKINGs", padx=5, pady=5)
        #self.container3B.grid(row=0, column=1)
    def displayRankingListbox(self, value=[]):
        """@note show Ranking on display
           @param[in] a list
           @example self.displayRankingListbox([1 2 3 4 5])
        """
        self.value = value
        self.listbox = Listbox(self.container3B, selectmode=Tk.SINGLE)
        scrollbar = Tk.Scrollbar(self.container3B, orient=Tk.VERTICAL)
        self.listbox.config(yscrollcommand=scrollbar.set)
        scrollbar.configure(command=self.listbox.yview)
        scrollbar.config(command=self.listbox.yview)
        self.listbox.insert(Tk.END, None)
        for item in value:
            self.listbox.insert(Tk.END, item)
        self.listbox.grid(row=1, column=1, stick=Tk.W)
        scrollbar.grid(row=1, column=2, stick=Tk.NS + Tk.W)

    ## Segui o Caminho mais fácil
    ## Dupliquei displayRanking e alterei o container apenas
    ## Não é o correto, mas não está errado, se sobrar tempo faço da forma correta
    def displayRanking1(self):
        """@ Show combobox on screen
           @example self.displayRanking1()
        """
        self.container1B = LabelFrame(self.container1,
                                      text="Visualiza RANKINGs",
                                      padx=5,
                                      pady=5)
        self.container1B.grid(row=0, column=1)
        self.comboboxF = ttk.Combobox(self.container1B,
                                      width=15,
                                      state="readonly",
                                      textvariable=self.mySelectionF)
        self.comboboxF["values"] = ("Ranking 1", "Ranking 2")
        self.comboboxF.grid(row=0, column=1)
        self.comboboxF.bind("<<ComboboxSelected>>", self.callbackRandom)
        #value=["one", "two", "three", "four", "five", "six", "seven","eight","nine","ten","eleven","twelve"] ### Somente para teste
        self.displayRankingListbox1()
        '''
        value = []
        self.listbox = Listbox(self.container3B,selectmode=Tk.SINGLE)
        scrollbar = Tk.Scrollbar(self, orient=Tk.VERTICAL)
        self.listbox.config( yscrollcommand=scrollbar.set)
        scrollbar.configure(command=self.listbox.yview)
        scrollbar.config(command=self.listbox.yview)
        self.listbox.insert(Tk.END, None)
        for item in value:
            self.listbox.insert(Tk.END, item)
        self.listbox.grid(row=1, column=1,stick=Tk.W)
        scrollbar.grid(row=1,column=2,stick=Tk.NS+Tk.W) '''
        #self.container3B = LabelFrame(self.container3B,text="Visualiza RANKINGs", padx=5, pady=5)
        #self.container3B.grid(row=0, column=1)
    def displayRankingListbox1(self, value=[]):
        """@note show Ranking on display
           @param[in] a list
           @example self.displayRankingListbox([1 2 3 4 5])
        """
        self.value = value
        self.listbox = Listbox(self.container1B, selectmode=Tk.SINGLE)
        scrollbar = Tk.Scrollbar(self.container1B, orient=Tk.VERTICAL)
        self.listbox.config(yscrollcommand=scrollbar.set)
        scrollbar.configure(command=self.listbox.yview)
        scrollbar.config(command=self.listbox.yview)
        self.listbox.insert(Tk.END, None)
        for item in value:
            self.listbox.insert(Tk.END, item)
        self.listbox.grid(row=1, column=1, stick=Tk.W)
        scrollbar.grid(row=1, column=2, stick=Tk.NS + Tk.W)

    #
    # Gera dois rankings Aleatórios a partir de um inteiro
    # os rankings sao colocados em um vetor self.ranking
    def gerarRankingAleatorio(self):
        """@note Build a random Ranking and show on display
           @example self.gerarRankingAleatorio()
        """
        self.resetDisplayResults()
        try:
            value = int(self.entryB.get())
        except ValueError:
            messagebox.showinfo("ERRO!",
                                "Informar o tamanho do ranking a ser gerado!")
            return
        #choice = self.mySelectionA.get()  ### Não precisei a selecao acontece em displayrankinglistbox
        #index = self.comboboxA.current()  ### nao precisei a selecao acontece em displayrankinglistbox
        if value < 1:
            messagebox.showinfo("Title", "Valor inválido ( " + value + " )")
        else:
            del self.ranking[:]
            for _ in range(2):
                self.ranking.append(Ranking(value))
            messagebox.showinfo("Title", "Rankings 1 e 2 gerados")
            self.comboboxA.current(0)
            self.displayRankingListbox(getattr(self.ranking[0], 'ranking'))
            #self.resetDisplayResults()

    #def callbackFunc(self, event):
    #    select = self.mySelection.get()
    #    self.labelvalue = select
    #    self.label = Label(self.container2, text=self.labelvalue)
    #    self.label.grid(row=0,column=1)
    #    print(select)

    def callbackRandom(self, event):
        """@note auxiliary method to gerarRankingAleatorio
           @example self.callbackRandom()
        """
        #select = self.mySelection.get()
        try:
            #_ = self.ranking[0]
            #_ = getattr(self.ranking[0],"ranking")
            index = self.comboboxA.current()
            array = getattr(self.ranking[index], 'ranking')
            self.listbox.delete(0, Tk.END)
            self.listbox.insert(Tk.END, None)
            for item in array:
                self.listbox.insert(Tk.END, item)
            self.listbox.grid(row=1, column=1, stick=Tk.W)
        except IndexError:
            messagebox.showinfo("ERRO!", "Não existem Rankings gerados!")
            return

    def askopenfilename(self):
        """@note Open ranking file
           @example self.askopenfilename()
        """
        filepath = askopenfilename()
        if filepath:
            #self.container1.filepaths.append(filepath)
            with open(filepath, "r+") as f:
                del self.ranking[:]
                for line in f:
                    value = line.replace("\n", "").replace(
                        "\r", "")  # do something with the line
                    try:
                        value = literal_eval(value)
                    except SyntaxError:
                        messagebox.showinfo("ERRO!", "Arquivo incompatível!")
                        return
                    else:
                        if type(value) is int:
                            del self.ranking[:]
                            for _ in range(2):
                                self.ranking.append(Ranking(value))
                            messagebox.showinfo("Title",
                                                "Rankings 1 e 2 gerados")
                        elif type(value) is list:
                            self.ranking.append(Ranking(value))
                        elif type(value) is tuple:
                            self.ranking.append(Ranking(value))
            #for line in inputfile.readline():
            ##    line = line.replace("\n", "").replace("\r", "")
            #   print(line)

            #   #value = literal_eval(line)
            #   #print(type(value))
            self.comboboxF.current(0)
            self.displayRankingListbox1(getattr(self.ranking[0], 'ranking'))
            f.close()

    def botaoSelecionaEntrada(self, value):
        """@note Build a rank from tuple.
           @param[in] integer
           @example self.botaoSelecionaEntrada(1)
        """
        self.buttonClick = value
        print("Called" + str(self.value))
        self.container1.isgridded = False
        self.container1.grid_forget()
        self.container2.isgridded = False
        self.container2.grid_forget()
        self.container3.isgridded = False
        self.container3.grid_forget()
        if self.buttonClick == 1:
            self.container1.isgridded = True
            self.container1.grid(row=0, column=0)
        if self.buttonClick == 2:
            # Ativa radiobutton do ranking / score (nao esta ativando)
            self.v1.set(1)
            self.v2.set(1)
            # Liga container 2
            self.displayEntradaManual()
            self.container2.isgridded = True
            self.container2.grid(row=0, column=0)
        if self.buttonClick == 3:
            self.container3.isgridded = True
            self.container3.grid(row=0, column=0)

    def checkType(self, lista):
        """@note Verify there are only digits from list
           @param[in] list
           @return Boolean
           @example self.checkType([1, 3, 4, 2])
        """
        for x in lista:
            if type(x) is str:
                return False
        return True

    def Calculadora(self):
        """@note Method to activate auxiliaries methods to show results
           @example self.Calculadora()
        """
        try:
            if self.buttonClick == 1:
                #value1 = self.entryM1.get().split()
                #value2 = self.entryM2.get().split()
                #print("Valor 1", value1, "Valor 2",value2)
                #del self.ranking[:]
                # Adiciona a entrada 1 ao vetor self.ranking
                #if int(self.v1.get()) == 1:
                #    self.ranking.append(Ranking(value1))
                #else:
                #    self.ranking.append(Ranking(tuple(value1)))
                # Adiciona a entrada 2 ao vetor self.ranking
                #if int(self.v2.get()) == 1:
                #    self.ranking.append(Ranking(value2))
                #else:
                #    self.ranking.append(Ranking(tuple(value2)))
                try:
                    #_ = self.ranking[0]
                    _ = getattr(self.ranking[0], "ranking")
                except IndexError:
                    messagebox.showinfo("ERRO!",
                                        "Não existem Rankings gerados!")
                    return
                self.showKemeny()
                self.showFootrule()
                self.showInvert()
                print(getattr(self.ranking[0], 'ranking'))
                print(getattr(self.ranking[1], 'ranking'))
            if self.buttonClick == 2:
                value1 = self.entryM1.get().split()
                value2 = self.entryM2.get().split()
                print("Valor 1", value1, "Valor 2", value2)
                if self.checkType(value1) and self.checkType(value2) or\
                not (len(value1)) or any(d is None for d in value1) or value1 is None or\
                not (len(value2)) or any(d is None for d in value2) or value2 is None or\
                len(value1) != len(set(value1)) or len(value2) != len(set(value2)) or\
                len(set(value1)) != len(set(value2)):
                    messagebox.showinfo(
                        "ERRO!",
                        "Erro na entrada de dados - Ranking inválido!")
                else:
                    del self.ranking[:]
                    # Adiciona a entrada 1 ao vetor self.ranking
                    if int(self.v1.get()) == 1:
                        self.ranking.append(Ranking(tuple(value1)))
                    else:
                        self.ranking.append(Ranking(value1))
                    # Adiciona a entrada 2 ao vetor self.ranking
                    if int(self.v2.get()) == 1:
                        self.ranking.append(Ranking(tuple(value2)))
                    else:
                        self.ranking.append(Ranking(value2))
                    self.showKemeny()
                    self.showFootrule()
                    self.showInvert()
                    #print(getattr(self.ranking[0],'ranking'))
                    #print(getattr(self.ranking[1],'ranking'))
            if self.buttonClick == 3:
                try:
                    _ = getattr(self.ranking[0], "ranking")
                except (IndexError, AttributeError):
                    messagebox.showinfo("Title",
                                        "Não existem Rankings gerados!")
                else:
                    #    print(len(getattr(self.ranking,"ranking")))
                    self.showKemeny()
                    self.showFootrule()
                    self.showInvert()
        except AttributeError:
            messagebox.showinfo("ERRO!",
                                "Não existem valores a ser calculados!")
            return

    def showKemeny(self):
        """@note Calculate Kemeny distance from Ranking Class than show on screen
           @example self.showKemeny()
        """
        value1 = Ranking(getattr(self.ranking[0], 'ranking'))
        value2 = Ranking(getattr(self.ranking[1], 'ranking'))
        print(value1, value2)
        result = value1.kDist(value2)
        self.labelkemeny = Label(self.lblframe, text=result)
        self.labelkemeny.grid(row=0, column=1)

    def showFootrule(self):
        """@note Calculate Footrule distance from Ranking Class than show on screen
           @example self.showFootrule()
        """
        value1 = Ranking(getattr(self.ranking[0], 'ranking'))
        value2 = Ranking(getattr(self.ranking[1], 'ranking'))
        print(value1, value2)
        result = value1.fDist(value2)
        self.labelfootrule = Label(self.lblframe, text=result)
        self.labelfootrule.grid(row=1, column=1)

    def showInvert(self):
        """@note Calculate inversions from Ranking Class than show on screen
           @example self.showInvert()
        """
        value1 = Ranking(getattr(self.ranking[0], 'ranking'))
        value2 = Ranking(getattr(self.ranking[1], 'ranking'))
        print(value1, value2)
        result = value1.invCount()
        self.labelinv1 = Label(self.lblframe, text=result)
        self.labelinv1.grid(row=3, column=1)
        result = value2.invCount()
        self.labelinv2 = Label(self.lblframe, text=result)
        self.labelinv2.grid(row=4, column=1)
Example #55
0
    Toplevel,
    W,
    filedialog,
    messagebox,
)

from PIL import Image, ImageTk

root = Tk()
root.title("Dropdown Menus")

options = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]

variable = StringVar()
variable.set(options[0])


def show():
    Label(root, text=variable.get()).pack()


# Drop Down Boxes

drop = OptionMenu(root, variable, *options)
drop.pack()

button = Button(root, text="Show selection", command=show)
button.pack()

root.mainloop()
Example #56
0
class App(object):
    """
Main class
    """

    __button_width = 15
    __button_height = 1
    __button_bg = "snow4"
    __button_fg = "white"
    __button_font = ("Autumn", 27)
    __button_relief = "flat"

    __inputText_height = 5

    __label_fg = "#F5F5F5"
    __label_font = ("Impact", 20)

    __outputText_height = 7

    __text_width = 50
    __text_bg = "white"
    __text_fg = "black"
    __text_font = ("Arial", 14)

    frequency = 2000

    window_title = "Morse Code Translation App"
    window_geometry = [600, 500]
    window_bg = "SteelBlue3"

    def __init__(self):

        # Create an instance of Tk and configure the window.
        self.__root = Tk()
        self.__root.geometry("{}x{}".format(*self.window_geometry))
        self.__root["bg"] = self.window_bg
        self.__root.title(self.window_title)
        self.__root.resizable(False, False)
        self.__root.focus_force()
        self.__root.bind("<Return>", self.translate)

        self.__playing = False
        self.__waitVar = IntVar()

        # Call method to build program interface.
        self.build()

    def build(self):
        """
        Method for building program interface.
        """

        # Creates a title for the entry of the text to be translated.
        Label(
            self.__root,
            bg=self.window_bg,
            font=self.__label_font,
            fg=self.__label_fg,
            text="Text:",
            pady=10
        ).pack()

        # Creates a frame to place the input field.
        input_frame = Frame(self.__root, bg=self.window_bg)
        input_frame.pack()

        # Creates a field for the user to enter the text.
        self.__inputText = Text(
            input_frame,
            width=self.__text_width,
            height=self.__inputText_height,
            bg=self.__text_bg,
            fg=self.__text_fg,
            font=self.__text_font,
            wrap="word"
        )
        self.__inputText.insert(0.0, " Enter text here...")

        # Creates a scroll bar for the input field.
        scrollbar = Scrollbar(input_frame)
        scrollbar.pack(side="right", fill="y")
        self.__inputText.config(yscrollcommand=scrollbar.set)
        scrollbar.config(command=self.__inputText.yview)

        self.__inputText.pack()

        # Creates field title where the translated text will be placed.
        Label(
            self.__root,
            bg=self.window_bg,
            font=self.__label_font,
            fg=self.__label_fg,
            text="Morse Code:",
            pady=10
        ).pack()

        # Creates frame to place the output field.
        output_frame = Frame(self.__root, bg=self.window_bg)
        output_frame.pack()

        # Field to place the translated text.
        self.__outputText = Text(
            output_frame,
            width=self.__text_width,
            height=self.__outputText_height,
            bg=self.__text_bg,
            fg=self.__text_fg,
            font=self.__text_font,
            wrap="word"
        )
        self.__outputText.insert(0.0, " The morse code will appear here.")

        # Creates a scroll bar for the output field.
        scrollbar = Scrollbar(output_frame)
        scrollbar.pack(side="right", fill="y")
        self.__outputText.config(yscrollcommand=scrollbar.set)
        scrollbar.config(command=self.__outputText.yview)

        self.__outputText.pack()

        # Creates a frame to insert the buttons.
        buttons_frame = Frame(self.__root, bg=self.window_bg, pady=20)
        buttons_frame.pack()

        # Creates a "border" for the button.
        button1_frame = Frame(buttons_frame, bg="black", padx=2, pady=2)
        button1_frame.pack(side="left")

        # Creates a button to translate the text.
        self.__button1 = Button(
            button1_frame,
            width=self.__button_width,
            height=self.__button_height,
            relief=self.__button_relief,
            bg=self.__button_bg,
            fg=self.__button_fg,
            font=self.__button_font,
            text="Translate",
            command=self.translate
        )
        self.__button1.pack()

        # If the user's OS is Windows, a button will be created
        # to reproduce the sound of the Morse code.
        if "win" in sys.platform:
            Label(buttons_frame, bg=self.window_bg, padx=5).pack(side="left")

            # Creates a "border" for the button.
            button2_frame = Frame(buttons_frame, bg="black", padx=2, pady=2)
            button2_frame.pack(side="left")

            #Creates a button to reproduce Morse code sound.
            self.__button2 = Button(
                button2_frame,
                width=self.__button_width,
                height=self.__button_height,
                relief=self.__button_relief,
                bg=self.__button_bg,
                fg=self.__button_fg,
                font=self.__button_font,
                text="Play",
                command=self.play
            )
            self.__button2.pack()

        self.__root.mainloop()

    def play(self):
        """
        Method to reproduce the sound of the Morse code.
        """

        #For playback.
        if self.__playing:
            self.__playing = False
            return

        # Gets the text of the output and checks if it is a Morse code.
        text = self.__outputText.get(0.0, "end")
        if not text or text.isspace() or not MorseCodeTranslator.isMorse(text): return

        # Informs that the morse code sound is being played.
        self.__playing = True
        self.__button2.config(text="Stop")

        # Divide text into words.
        for char in text.split(" "):

            # Gets each letter of the word.
            for l in char:

                if not self.__playing:
                    break

                # Checks whether the character is an error.
                if l == MorseCodeTranslator.errorChar:
                    continue

                # It beeps for 0.4 seconds each time it is a dot.
                if l == ".":
                    Beep(self.frequency, 400)

                # Plays a beep for 0.8 seconds if it is a dash.
                elif l == "-":
                    Beep(self.frequency, 800)

                #Wait for 2 seconds if it is the beginning of a new word.
                elif l == "/":
                    self.wait(2000)

            if not self.__playing:
                break

            # Waits 1 second.
            self.wait(1000)

        # Informs you that playback has finished.
        self.__playing = False
        self.__button2.config(text="Play")

    def translate(self, event=None):
        """
        Button method for translating text.
        """

        #Gets user input.
        text = self.__inputText.get(0.0, "end")
        if not text: return

        # Delete the text from the output field and insert the translated user's input.
        self.__outputText.delete(0.0, "end")
        self.__outputText.insert(0.0, MorseCodeTranslator.translate(text))

    def wait(self, ms):
        """
        Method to wait a while on Ms.
        """

        self.__waitVar.set(0)
        self.__root.after(ms, self.__waitVar.set, 1)
        self.__root.wait_variable(self.__waitVar)
        self.__waitVar.set(0)
Example #57
0
    objs.append(choice(R))
cercle = []
for obj in objs:
    cercle.append(
        can1.create_oval(Cx * obj[0] - r,
                         Cy * obj[1] - r,
                         Cx * obj[0] + r,
                         Cy * obj[1] + r,
                         width=1,
                         fill='red'))
duree = Label(fen1)
can1.create_rectangle(3, 3, width, height, width=2, outline='black')
for sx, sy in sortie:
    can1.create_rectangle(Cx * (sx + 1) - 4,
                          Cy * (sy - 1),
                          Cx * (sx + 1) - 1,
                          Cy * (sy + 1),
                          fill='light green')
can1.grid(row=0, column=0, rowspan=6, padx=10, pady=5)
bou1 = Button(fen1, text='Start', width=12, command=move)
bou2 = Button(fen1, text='Leave', width=12, command=fen1.destroy)
bou3 = Button(fen1, text='Pause/Resume', width=12, command=pause)
bou4 = Button(fen1, text='Initialize', width=12, command=initialiser)
bou5 = Button(fen1, text='1 step', width=12, command=slow)
bou1.grid(row=1, column=1, padx=5, pady=5)
bou2.grid(row=5, column=1, padx=5, pady=5)
bou3.grid(row=4, column=1, padx=5, pady=5)
bou4.grid(row=2, column=1, padx=5, pady=5)
bou5.grid(row=3, column=1, padx=5, pady=5)
duree.grid(row=0, column=1, padx=5, pady=5)
fen1.mainloop()
Example #58
0
class Morpho:

	def __init__(self, master):
		self.master = master
		master.title("Morhpological Operations")
		photo = PhotoImage(file="")
		self.message = "Choose A Test"
		self.label_text = StringVar()
		self.label_text.set(self.message)
		self.label = Label(master, textvariable=self.label_text)
		#vcmd = master.register(self.validate) # we have to wrap the command
		#self.entry = Entry(master, validate="key", validatecommand=(vcmd, '%P'))
		self.RFCall = Button(master, text="(NOTHING)", command=self.guess_number)
		self.reset_button = Button(master, text="RESET", command=self.reset, fg="red")
		self.quit = Button(master, text="QUIT", command=self.master.destroy, bg="red")
		self.img = Label(master, image = photo )
		self.img.image = photo
		self.var = IntVar()
		self.choice = Radiobutton(master, text="Image 1", variable=self.var, value=1, command=self.sel)
		self.choice1 = Radiobutton(master, text="Image 2", variable=self.var, value=2, command=self.sel)
		self.label.grid(row=0, column=0, columnspan=2, sticky=W+E)
		#self.entry.grid(row=1, column=0, columnspan=2, sticky=W+E)
		self.RFCall.grid(row=2, column=0)
		self.reset_button.grid(row=2, column=1)
		self.choice.grid(row=3,column=0)
		self.choice1.grid(row=3,column=1)
		self.quit.grid(row=4, column=0, columnspan=2, sticky=W+E, pady=5)
		self.img.grid(row=5, columnspan=2)

	def sel(self):
		print("selecting photo", str(self.var.get()) )
		if(self.var.get() == 1):
			photo = PhotoImage(file="QR.png")
			self.img.configure(image=photo)
			self.img.image = photo
		elif(self.var.get() == 2):
			photo = PhotoImage(file="img.gif")
			self.img.configure(image=photo)
			self.img.image = photo

	def validate(self, new_text):
		print("validating", new_text)
		if not new_text:
			self.guess = None
			return True
		try:
			guess = int(new_text)
			if 1 <= guess <= 100:
				self.guess = guess
				return True
			else:
				self.message = "INVALID NUMBER"
				self.label_text.set(self.message)
				return False
		except ValueError:
			self.message = "INVALID CHARACTER"
			self.label_text.set(self.message)
		return False

	def guess_number(self):
		print("guessing")
		self.label_text.set(self.message)
		
	def reset(self):
		#self.entry.delete(0, END)
		photo = PhotoImage(file="")
		self.img.configure(image=photo)
		self.img.image = photo
		self.message = "TRY AGAIN"
		self.label_text.set(self.message)
Example #59
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 = 2000
        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="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")

    #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 #60
0
class View():
    def __init__(self, master):

        self.width = 600
        self.height = 600

        self.root = master
        self.root.geometry("600x600")

        self.left_frame = Frame(self.root, width=600)
        self.left_frame.pack_propagate(0)
        self.left_frame.pack(fill='both', side='left', expand='True')

        self.retrieval_frame = Frame(self.root, bg='snow3')
        self.retrieval_frame.pack_propagate(0)
        self.retrieval_frame.pack(fill='both', side='right', expand='True')

        self.bg_frame = Frame(self.left_frame,
                              bg='snow3',
                              height=600,
                              width=600)
        self.bg_frame.pack_propagate(0)
        self.bg_frame.pack(fill='both', side='top', expand='True')

        self.command_frame = Frame(self.left_frame, bg='snow3')
        self.command_frame.pack_propagate(0)
        self.command_frame.pack(fill='both', side='bottom', expand='True')
        #        self.command_frame.grid(row=1, column=0,padx=0, pady=0)

        self.bg = Canvas(self.bg_frame,
                         width=self.width,
                         height=self.height,
                         bg='gray')
        self.bg.place(relx=0.5, rely=0.5, anchor='center')

        self.mani = Canvas(self.retrieval_frame,
                           width=1024,
                           height=1024,
                           bg='gray')
        self.mani.grid(row=0, column=0, padx=0, pady=42)

        self.SetCommand()

    def run(self):
        self.root.mainloop()

    def helloCallBack(self):
        category = self.set_category.get()
        messagebox.showinfo("Hello Python", category)

    def SetCommand(self):

        tmp = Label(self.command_frame, text="neutral", width=10, bg='snow3')
        tmp.grid(row=1, column=0, padx=10, pady=10)

        tmp = Label(self.command_frame,
                    text="a photo of a",
                    width=10,
                    bg='snow3')
        tmp.grid(row=1, column=1, padx=10, pady=10)

        self.neutral = Text(self.command_frame, height=2, width=30)
        self.neutral.grid(row=1, column=2, padx=10, pady=10)

        tmp = Label(self.command_frame, text="target", width=10, bg='snow3')
        tmp.grid(row=2, column=0, padx=10, pady=10)

        tmp = Label(self.command_frame,
                    text="a photo of a",
                    width=10,
                    bg='snow3')
        tmp.grid(row=2, column=1, padx=10, pady=10)

        self.target = Text(self.command_frame, height=2, width=30)
        self.target.grid(row=2, column=2, padx=10, pady=10)

        tmp = Label(self.command_frame, text="strength", width=10, bg='snow3')
        tmp.grid(row=3, column=0, padx=10, pady=10)

        self.alpha = Scale(self.command_frame,
                           from_=-15,
                           to=25,
                           orient=HORIZONTAL,
                           bg='snow3',
                           length=250,
                           resolution=0.01)
        self.alpha.grid(row=3, column=2, padx=10, pady=10)

        tmp = Label(self.command_frame,
                    text="disentangle",
                    width=10,
                    bg='snow3')
        tmp.grid(row=4, column=0, padx=10, pady=10)

        self.beta = Scale(self.command_frame,
                          from_=0.08,
                          to=0.4,
                          orient=HORIZONTAL,
                          bg='snow3',
                          length=250,
                          resolution=0.001)
        self.beta.grid(row=4, column=2, padx=10, pady=10)

        self.reset = Button(self.command_frame, text='Reset')
        self.reset.grid(row=5, column=1, padx=10, pady=10)

        self.set_init = Button(self.command_frame, text='Accept')
        self.set_init.grid(row=5, column=2, padx=10, pady=10)