Example #1
0
class KRCCModule:
  __metaclass__ = ABCMeta

  def __init__(self):
    self._terminate = BooleanVar(False)
    self._id = StringVar(False)

  @property
  def terminate(self):
    return self._terminate.get()

  @terminate.setter
  def terminate(self, value):
    self._terminate.set(value)

  @property
  def id(self):
    return self._id.get()

  @id.setter
  def id(self, value):
    self._id.set(value)

  @abstractproperty
  def name(self):
    pass

  @abstractmethod
  def run(self):
    pass
Example #2
0
class Example(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.initUI()

    def initUI(self):
        self.parent.title("Listbox")
        self.pack(fill=BOTH, expand=1)

        acts = ["Scarlett Johansson", "Rachel Weiss", "Natalie Portman", "Jessica Alba", "Angelina jolie", "Emma Stone", "Sandra Bullock", "Julia Roberts",
        "Jennifer Lawrence", "Mila Kunis", "Jennifer Aniston", "Charlize Theron", "Cameron Diaz", "Nicole Kidman", "Meryl Streep", "Reese Witherspoon"]

        lb = Listbox(self, selectmode="multiple")
        for i in acts:
            lb.insert(END, i)

        lb.bind("<<ListboxSelect>>", self.onSelect)

        lb.pack(pady=15)

        self.var = StringVar()
        self.label = Label(self, text=0, textvariable=self.var)
        self.label.pack()

    def onSelect(self, val):
        sender = val.widget
        idx = sender.curselection()
        value = sender.get(idx)
        self.var.set(value)
Example #3
0
class Mjolnir3(KRCCModule):
  def __init__(self, root):
    super().__init__()
    self.root = root
    self.exception = None

    self.list_string = StringVar()
    self.listbox = Listbox(root, listvariable=self.list_string,
                           font='TkFixedFont', width=300)

    self.load()

  def establish_connection_and_run(self):
    error = None
    dots = 0
    connection = None
    while not self.terminate:
      try:
        if connection is None:
          connection = krpc.connect(name=self.name)
        self.run_with_connection(connection)
        error = None
        dots = 0
      except Exception as e:
        if error != e.args[0]:
          error = e.args[0]
          print('\n')
          print(traceback.format_exc())
          sys.stdout.write('Retrying...\n')
        if dots > 80:
          dots = 0
          sys.stdout.write('\n')
        sys.stdout.write('.')
        dots += 1
        sys.stdout.flush()
        time.sleep(1)
    if connection is not None:
      connection.close()

  def run_with_connection(self, connection):
    logging.debug('KRPC connection established')
    strategy = PreLaunch(connection)
    while not self.terminate:
      strategy = strategy.update()
      self.list_string.set(tuple(strategy.display()))

  def run(self):
    try:
      self.establish_connection_and_run()
      self.listbox.destroy()
    except RuntimeError:
      # Should only happen when KeyboardInterrupt is thrown in the MainThread.
      pass

  @property
  def name(self):
    return 'Mjolnir 3'

  def load(self):
    self.listbox.pack(side=LEFT, fill=BOTH)
Example #4
0
 def body(self, master, cfg={}):
     "place user dialog widgets"
     self.config = cfg
     self.config["OK button"] = False
     self.site = StringVar()
     self.site.set(cfg.get("site", ""))
     self.login = StringVar()
     self.login.set(cfg.get("user", ""))
     self.password = StringVar()
     self.password.set(str(cfg.get("password", "")))
     site = Entry(master, width=15, textvariable=self.site)
     site.grid(column=1, row=0, sticky="e")
     Label(master, text=_("Site:")).grid(column=0, row=0, sticky="w")
     loge = Entry(master, width=15, textvariable=self.login)
     loge.grid(column=1, row=1, sticky="e")
     Label(master, text=_("Username:"******"w")
     pase = Entry(master, width=15, textvariable=self.password, show="*")
     pase.grid(column=1, row=2, sticky="e")
     Label(master, text=_("Password:"******"w")
     self.to_remember = IntVar()
     self.to_remember.set(cfg.get("remember_passwd", 1))
     chk1 = Checkbutton(master, text="Remember",
                        variable=self.to_remember)
     chk1.grid(column=0, row=3, sticky="w", columnspan=2)
     self.resizable(width=0, height=0)
     return loge
Example #5
0
class Example(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.initUI()

    def initUI(self):
        self.parent.title("Listbox")
        self.pack(fill=BOTH, expand=1)

        acts = ['Scarlett Johansson', 'Rachel Weiss',
            'Natalie Portman', 'Jessica Alba']

        lb = Listbox(self)
        for i in acts:
            lb.insert(END, i)

        lb.bind("<<ListboxSelect>>", self.onSelect)

        lb.place(x=20, y=20)

        self.var = StringVar()
        self.label = Label(self, text=0, textvariable=self.var)
        self.label.place(x=20, y=210)

    def onSelect(self, val):

        sender = val.widget
        idx = sender.curselection()
        value = sender.get(idx)

        self.var.set(value)
Example #6
0
    def __init__(self, parent, frames, forks, wheelsets, groups, components):
        """
        inicjalizacja obiektu okna - nieistotne dla idei zdania
        """
        super(ConfigurationWindow, self).__init__(parent)
        self._bike = None
        self.parent = parent
        self.frames = frames
        self.forks = forks
        self.wheelsets = wheelsets
        self.groups = groups
        self.components = components
        self.parent.title("Bicycle configurator")
        self._bike_price = StringVar(self.parent)
        self._bike_weight = StringVar(self.parent)
        self._bike_travel = StringVar(self.parent)
        self.price_label = Label(self.parent, textvariable=self._bike_price)
        self.weight_label = Label(self.parent, textvariable=self._bike_weight)
        self.travel_label = Label(self.parent, textvariable=self._bike_travel)

        self.createInterface()
        self.createBike()

        self.price_label.pack()
        self.weight_label.pack()
        self.travel_label.pack()
        
        self.pack(fill=BOTH, expand=1)
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 #8
0
    def __init__(self, _master, _mapping = None,
                 _on_get_source_references = None,
                 _on_get_destination_references = None,
                 _on_select = None):
        super(FrameMapping, self).__init__(_master)


        # Add monitored variables.
        self.is_key = BooleanVar()
        self.src_reference = StringVar()
        self.src_datatype = StringVar()
        self.curr_data = StringVar()

        self.result_cast_to = StringVar()
        self.preview = StringVar()

        self.dest_reference = StringVar()

        self.on_get_source_references = _on_get_source_references
        self.on_get_destination_references = _on_get_destination_references

        self.on_select = _on_select
        self.init_widgets()

        self.mapping = _mapping



        if _mapping is not None:
            self.mapping_to_gui()
Example #9
0
 class PredictionWidget(Frame):
     """Shows a prediction to the user."""
     def __init__(self, master):
         """Make boxes, register callbacks etc."""
         Frame.__init__(self, master)
         self.active_category = StringVar()
         self.bind("<Configure>", self.onResize)
         self.date = None
         self.predictor = Predictor()
         self.category_buttons = self.createCategoryButtons()
         self.text = Label(self, justify=CENTER, font="Arial 14")
     def createCategoryButtons(self):
         """Create the buttons used to choose category. Return them."""
         result = []
         icons = self.readIcons()
         categories = self.predictor.categories()
         for i in categories:
             if i in icons:
                 icon = icons[i]
             else:
                 icon = icons["= default ="]
             category_button = Radiobutton(self, image=icon,
                  variable=self.active_category, value=i, indicatoron=False,
                  width=icon_size, height=icon_size, command=self.update)
             category_button.image_data = icon
             result.append(category_button)
         self.active_category.set(categories[0])
         return result
     def readIcons(self):
         """Read the gui icons from disk. Return them."""
         result = {}
         categories = open(nextToThisFile("icons.txt")).read().split("\n\n")
         for i in categories:
             category_name, file_data = i.split("\n", maxsplit=1)
             image = PhotoImage(data=file_data)
             result[category_name] = image
         return result
     def onResize(self, event):
         """Rearrange the children when the geometry of self changes."""
         if event.widget == self:
             center = (event.width / 2, event.height / 2)
             radius = min(center) - icon_size / 2
             self.text.place(anchor=CENTER, x=center[0], y=center[1])
             for i, j in enumerate(self.category_buttons):
                 turn = 2 * math.pi
                 angle = turn * (1 / 4 - i / len(self.category_buttons))
                 j.place(anchor=CENTER,
                         x=center[0] + math.cos(angle) * radius,
                         y=center[1] - math.sin(angle) * radius)
     def update(self, date=None):
         """Change contents based on circumstances. Set date if given."""
         if date:
             self.date = date
         if self.date:
             predictions = self.predictor.predict(self.date)
             prediction = predictions[self.active_category.get()]
             prediction = textwrap.fill(prediction, width=20)
         else:
             prediction = ""
         self.text.configure(text=prediction)
Example #10
0
class DlgDelay(Dialog):
    def body(self, master, cfg={}):
        "place user dialog widgets"
        self.config = cfg
        self.config["OK button"] = False
        self.delay = StringVar()
        self.delay.set(cfg.get("delay", ""))
        self.edelay = Entry(master, width=15, textvariable=self.delay)
        self.edelay.grid(column=1, row=0, sticky="e")
        Label(master, text=_("Delay:")).grid(column=0, row=0, sticky="w")
        self.resizable(width=0, height=0)
        return self.edelay

    def validate(self):
        try:
            flt = float(self.delay.get())
        except ValueError:
            return self.edelay
        if flt < 0 or flt > 5:
            return self.edelay
        return None

    def apply(self):
        "On ok button pressed"
        self.config["delay"] = self.delay.get()
        self.config["OK button"] = True
Example #11
0
    def __init__(self, resizable=(True, True), geometry=(620, 220)):
        assert (isinstance(resizable, (tuple, list)))
        assert (isinstance(geometry, (tuple, list)))

        self.root = Tk()

        self.config = configparser.ConfigParser()
        self.config_file_name = "config.ini"
        self.config.read(self.config_file_name)

        self.default_case = StringVar(value=self.config["DEFAULT"].get("case", "CASE"))
        self.default_team = StringVar(value=self.config["DEFAULT"].get("team", "TEAM"))
        self.default_series = StringVar()
        self.default_last_index = StringVar()

        self.root.title("The Stampede")
        self.root.resizable(width=resizable[0], height=resizable[1])
        self.root.geometry('{}x{}'.format(geometry[0], geometry[1]))
        self.root.minsize(geometry[0], geometry[1])
        self.root.maxsize(geometry[0]+200, geometry[1])
        self.file_name = StringVar()
        self.file_name.trace("w", self.file_name_changed)
        self.stamp_button = None
        self.add_widgets()
        self.add_menus()
        self.center(self.root)
Example #12
0
    def __init__(self, master=None, conflict=None, *args):
        """Initialize the widget."""
        ttk.Frame.__init__(self, master, padding=5)
        self.columnconfigure(1, weight=1)
        self.rowconfigure(2, weight=1)

        self.conflict = conflict

        self.dispFormat = StringVar(value='pattern')
        self.dispList = StringVar()
        self.feasList = []

        self.fmts = {'Pattern': 'YN-', 'List (YN)': 'YN',
                     'List (ordered and [decimal])': 'ord_dec'}
        cBoxOpts = ('Pattern', 'List (YN)', 'List (ordered and [decimal])')
        self.feasText = ttk.Label(self, text='Feasible States')
        self.feasText.grid(row=0, column=0, columnspan=3)
        self.cBox = ttk.Combobox(self, textvariable=self.dispFormat,
                                 values=cBoxOpts, state='readonly')
        self.cBoxLb = ttk.Label(self, text='Format:')
        self.feasLBx = Listbox(self, listvariable=self.dispList)
        self.scrl = ttk.Scrollbar(self, orient=VERTICAL,
                                  command=self.feasLBx.yview)

        # ###########
        self.cBoxLb.grid(column=0, row=1, sticky=NSEW, pady=3)
        self.cBox.grid(column=1, row=1, columnspan=2, sticky=NSEW, pady=3)
        self.feasLBx.grid(column=0, row=2, columnspan=2, sticky=NSEW)
        self.scrl.grid(column=2, row=2, sticky=NSEW)

        self.cBox.bind('<<ComboboxSelected>>', self.fmtSel)
        self.feasLBx.configure(yscrollcommand=self.scrl.set)

        self.dispFormat.set('Pattern')
        self.fmtSel()
Example #13
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])
 def employee(self):
     """Function for creation of the GUI to select an employee"""
     self.background.destroy()
     employees=[]
     airports=[]
     employfile="employees.csv"
     airfile="airport.csv"
     curfile="countrycurrency.csv"
     ratefile="currencyrates.csv"
     employee_info=self.look.LookupEmployee(employfile)
     self.look.LookupAirport(airfile)
     self.look.LookupCounrtyCurrency(curfile)
     self.look.LookupCurrencyRate(ratefile)
     for key in employee_info:
         employees.append(key)
     employees.sort()
     #New GUI
     background=Tk()
     background.wm_title("Select an Employee")
     background.geometry("%dx%d+%d+%d" % (400, 150, 150, 200))
     background.configure(background='light sky blue')
     Label(background, text="Choose an employee:", bg="white").grid(padx=10,pady=30,column=0, row=5)
     self.box1name=StringVar()
     self.answer=StringVar()
     box1 = ttk.Combobox(background, values=employees, textvariable=self.box1name, state='readonly')#Allows user to select an employee
     box1.set("Choose an employee")
     box1.grid(padx=30,column=0,row=6)
     answer=Label(background, textvariable=self.answer, bg="white").grid(column=0,row=8)
     button = Button(background, text="Select", command=self.select, bg="white")#Calls select
     button.grid(padx=10,column=1,row=6)
     background.mainloop()
 def __init__(self, parent, table, *args, **kw):
     super().__init__(parent, *args, **kw)
     self.table = table
     self.goto_spin = None
     self.text_var_nb_pages = StringVar()
     self.current_page_str = StringVar()
     self.create_widgets()
Example #16
0
 class DateWidget(Frame):
     """Gets a date from the user."""
     def __init__(self, master):
         """Make boxes, register callbacks etc."""
         Frame.__init__(self, master)
         self.label = Label(self, text="När är du född?")
         self.label.pack()
         self.entry_text = StringVar()
         self.entry_text.trace("w", lambda *args: self.onEntryChanged())
         self.entry = Entry(self, width=date_entry_width,
              textvariable=self.entry_text)
         self.entry.insert(0, "ÅÅÅÅ-MM-DD")
         self.entry.pack(pady=small_pad)
         self.button = Button(self, text="Uppdatera",
              command=lambda: self.onDateChanged())
         self.button.pack()
         self.entry.focus_set()
         self.entry.select_range(0, END)
         self.entry.bind("<Return>", lambda x: self.onDateChanged())
     def setListener(self, pred_view):
         """Select whom to notify when a new date is entered."""
         self.pred_view = pred_view
     def onDateChanged(self):
         """Notifies the PredictionWidget that the date has been changed."""
         try:
             date = datetime.datetime.strptime(self.entry.get(),
                  "%Y-%m-%d").date()
             self.pred_view.update(date)
         except ValueError:
             self.entry.configure(foreground="red")
     def onEntryChanged(self):
         """Reset the text color."""
         self.entry.configure(foreground="")
Example #17
0
class GuiGeneratorSelect(Frame):
    def __init__(self, parent, generators):
        Frame.__init__(self, parent)
        self.parent = parent
        self.pack()
        
        self._generators = generators
        self._generatorName = StringVar()
        self._generatorName.set(generators[0].getName())
        self._generatorName.trace("w", self._switchSettings)
        
        self._generatorLbl = Label(self, text="Generator");
        self._generatorLbl.pack(side=LEFT)
        
        param = (self, self._generatorName) + tuple(i.getName() for i in generators)
        self._generatorOpt = OptionMenu(*param)
        self._generatorOpt.pack(side=LEFT)
        
        
        self._switchSettings()
        
    def _switchSettings(self, *args):
       print("DBG: switch generator settings")
       for i in self._generators:
           if i.getName() == self._generatorName.get(): 
               i.pack()
               self._generatorGui = i
               print("pack " + str(i.getName()))
           else:
               i.pack_forget() 
               print("unpack " + str(i.getName()))
    
    def getCurrGeneratorGui(self):
        return self._generatorGui         
    def __init__(self, master):
        """Constructor method

        :param master: A "master" wigdet
        """
        self.mainframe = Frame(master)  # Create a Frame child widget
        self.mainframe.pack()  # Make the widget visible

        self.path = ''  # Define default path for the .xmcd file
        self.texfile_path = ''  # Define path for the .tex file

        self.name = Label(self.mainframe, text="Welcome to Mathcad to LaTeX converter")  # Create a static text label
        self.name.pack(side="top")  # Make the widget visible and define location

        self.filename = StringVar()  # Create a dynamic string variable
        self.filename.set("Current selected file: none")  # Set the string value
        self.filename_label = Label(self.mainframe, textvariable=self.filename)  # Create a label with the dynamic var
        self.filename_label.pack()
        self.text_updater = Entry(self.mainframe, textvariable=self.filename)  # Create a Entry widget for auto updates

        self.status = StringVar()  # Used for displaying the status of the file operation
        self.status.set("Status: Not parsed")
        self.status_label = Label(self.mainframe, textvariable=self.status)
        self.status_label.pack()
        self.text_updater2 = Entry(self.mainframe, textvariable=self.status)

        self.parse_file = Button(self.mainframe, text="Parse and save!", command=self.parse_file)  # Button for parsing
        self.parse_file.pack(side="right")

        self.parse_file = Button(self.mainframe, text="Open LaTeX file", command=self.open_file)
        self.parse_file.pack(side="right")

        self.select_file = Button(self.mainframe, text="Select file", command=self.select_file)  # Runs a class method
        self.select_file.pack(side="right")
    def __init__(self, processing_request_model):
        self.processing_request_model = processing_request_model

        self.progress = StringVar()
        self.progress.set("0%")

        self.state = StringVar()
        self.state.set(self.NOT_STARTED)
Example #20
0
 def undo (self):
     if len(self.history_list) > 1:
         a = self.history_list.pop(len(self.history_list) - 1)
         a = self.history_list[len(self.history_list) -1]
         StringVar.set(self, a)
     else:
         a = self.history_list[0]
         StringVar.set(self, a)
Example #21
0
class OptionMenu45(OptionMenu):
    def __init__(self,parent,title,option_list,**config):
        self.result = StringVar()
        self.result.set(title)
        OptionMenu.__init__(self,parent,self.result,*option_list,**config)
  
    def get(self):
        return self.result.get()
Example #22
0
 def init_before_run(self, nb_models, coefficients):
     ''' See base class.
     '''
     current_dmu = StringVar()
     current_dmu.trace('w', self.frame.on_dmu_change)
     self.current_dmu = current_dmu
     self.increment = 100 / (len(coefficients) * nb_models)
     self.frame.progress_bar['value'] = 0
def test_CheckbuttonWithVar():
    parent = Tk()
    var = StringVar(master=parent)
    var.set(1)
    box = CheckbuttonWithVar(parent, var)
    box.deselect()
    assert var.get() == '0'
    parent.destroy()
Example #24
0
class FeasDisp(ttk.Frame):
    """Widget for displaying all of the feasible states in the conflict."""

    def __init__(self, master=None, conflict=None, *args):
        """Initialize the widget."""
        ttk.Frame.__init__(self, master, padding=5)
        self.columnconfigure(1, weight=1)
        self.rowconfigure(2, weight=1)

        self.conflict = conflict

        self.dispFormat = StringVar(value='pattern')
        self.dispList = StringVar()
        self.feasList = []

        self.fmts = {'Pattern': 'YN-', 'List (YN)': 'YN',
                     'List (ordered and [decimal])': 'ord_dec'}
        cBoxOpts = ('Pattern', 'List (YN)', 'List (ordered and [decimal])')
        self.feasText = ttk.Label(self, text='Feasible States')
        self.feasText.grid(row=0, column=0, columnspan=3)
        self.cBox = ttk.Combobox(self, textvariable=self.dispFormat,
                                 values=cBoxOpts, state='readonly')
        self.cBoxLb = ttk.Label(self, text='Format:')
        self.feasLBx = Listbox(self, listvariable=self.dispList)
        self.scrl = ttk.Scrollbar(self, orient=VERTICAL,
                                  command=self.feasLBx.yview)

        # ###########
        self.cBoxLb.grid(column=0, row=1, sticky=NSEW, pady=3)
        self.cBox.grid(column=1, row=1, columnspan=2, sticky=NSEW, pady=3)
        self.feasLBx.grid(column=0, row=2, columnspan=2, sticky=NSEW)
        self.scrl.grid(column=2, row=2, sticky=NSEW)

        self.cBox.bind('<<ComboboxSelected>>', self.fmtSel)
        self.feasLBx.configure(yscrollcommand=self.scrl.set)

        self.dispFormat.set('Pattern')
        self.fmtSel()

    def fmtSel(self, *args):
        """Action on selection of a new format."""
        self.refreshList()

    def setFeas(self, feasList):
        """Change the list of feasible states to be displayed."""
        self.feasList = feasList
        self.refreshList()

    def refreshList(self):
        """Update the list of feasible states displayed and the format."""
        fmt = self.fmts[self.dispFormat.get()]
        if fmt == "YN-":
            feas = self.conflict.feasibles.dash
        if fmt == "YN":
            feas = self.conflict.feasibles.yn
        if fmt == "ord_dec":
            feas = self.conflict.feasibles.ordDec
        self.dispList.set(tuple(feas))
Example #25
0
 def create_combo(self, j):
     """ Create the j'th power / race combo to display in frame_combos. """
     combo_textvar = StringVar()
     combo_textvar.set(self.game.powers[j] + "-" + self.game.races[j])
     button_combo = Button(self.frame_combos, textvariable = combo_textvar,
                           state = "disabled", name = "combo_" + str(j),
                           command = lambda: self.press_choose_jth_combo(j))
     button_combo.grid(row = 5 - j)
     self.combos[j] = {"button": button_combo}
Example #26
0
def fourth_window(root, info):
    store = StringVar()

    def next_window(root=root, info=info):
        info['format'] = store.get()
        fifth_window(root=root, info=info)
        info['brandname'] = brand.get()
        info['campaign'] = campaign.get()

    def back(info=info):
        third_window(root=root, info=info)

    def active_next(*args):
        send.state(['!disabled', 'active'])

    c = ttk.Frame(root)
    c.grid(column=0, row=0, sticky=(N, W, E, S))

    background_image = tkinter.PhotoImage(file='%s/Desktop/natappy/images/road.gif' % home)
    background_label = tkinter.Label(c, image=background_image)
    background_label.image = background_image
    background_label.place(x=0, y=0, relwidth=1, relheight=1)

    root.grid_columnconfigure(0, weight=3)
    root.grid_rowconfigure(0, weight=3)

    g2 = ttk.Radiobutton(c, text='Full Report', variable=store, value='Full', command=active_next)
    g2.grid(column=1, row=2, sticky=(N, W, E, S), padx=20, pady=20)

    g4 = ttk.Radiobutton(c, text='Quick Report', variable=store, value='Quick', command=active_next)
    g4.grid(column=1, row=4, sticky=(N, W, E, S), padx=20, pady=20)

    w = Label(c, text="First Page Title")
    w.grid(column=1, row=5, sticky=(S, W), padx=(20, 5), pady=(5, 0))

    brand = Entry(c, width=20)
    brand.grid(column=1, row=6, sticky=W, padx=(20, 5), pady=(5, 0))

    campaign = Entry(c, width=20)
    campaign.grid(column=2, row=6, sticky=W, padx=(5, 70), pady=(5, 0))

    send = ttk.Button(c, text='Next', command=next_window, default='active', state='disabled')
    send.grid(column=3, row=7, pady=20, sticky=E, padx=(2, 20))

    close = ttk.Button(c, text='Back', command=back, default='active')
    close.grid(column=2, row=7, pady=20, sticky=E)

    if info['format']:
        store.set(info['format'])
        active_next()

    c.grid_columnconfigure(0, weight=1)
    c.grid_rowconfigure(5, weight=1)

    root.title('4/5 Format')
    root.geometry('550x400+440+200')
Example #27
0
class OptionMenu45Whiten(OptionMenu45):
    def __init__(self,parent,title,option_list,whiten_entry=None,**config):
        self.whiten_entry = whiten_entry
        self.result = StringVar()
        self.result.set(title)
        OptionMenu45.__init__(self,parent,title,option_list,command=self.whiten,**config)

  
    def whiten(self,option):
        self.whiten_entry.config(bg="white")
Example #28
0
class Scroller(object):
    """
    Scrolls through a solution list.
    """
    def __init__(self, wdw, sols):
        """
        Stores the list of solutions in sols
        and defines the layout of the GUI.
        """
        wdw.title('solutions scroller')
        self.sols = sols
        self.cursor = 0
        self.lbl = Label(wdw, text="solution : ")
        self.lbl.grid(row=0, column=0, sticky=E) 
        self.ent = Entry(wdw)
        self.ent.grid(row=0, column=1, stick=W)
        self.ent.insert(INSERT, "0 of %d" % len(sols))
        self.myft = Font(family="Courier New", size=12, weight="normal")
        self.mlen = self.myft.measure("M")
        lines = sols[0].split('\n')
        self.width = max([len(line) for line in lines])
        self.display = StringVar()
        self.display.set(self.sols[0])
        self.mess = Message(wdw, textvariable=self.display, \
            font=self.myft, width=self.width*self.mlen, background='white')
        self.mess.grid(row=1, column=0, columnspan=2)
        self.btnext = Button(wdw, command=self.next, text='next')
        self.btnext.grid(row=2, column=1, sticky=W+E)
        self.btprev = Button(wdw, command=self.previous, text='previous')
        self.btprev.grid(row=2, column=0, sticky=W+E)

    def show(self):
        """
        Shows the solution at position self.cursor
        in the message widget and updates the entry widget.
        """
        self.display.set(self.sols[self.cursor])
        self.ent.delete(0, END)
        self.ent.insert(INSERT, '%d of %d' % (self.cursor, len(self.sols)))

    def next(self):
        """
        Increases the cursor by one if possible.
        """
        if self.cursor < len(self.sols) - 1:
            self.cursor = self.cursor + 1
        self.show()

    def previous(self):
        """
        Decreases the cursor by one if possible.
        """
        if self.cursor > 0:
            self.cursor = self.cursor - 1
        self.show()
    def __init__(self, master, conflict):
        """Initialize the widget."""
        ttk.Frame.__init__(self, master)

        self.conflict = conflict

        self.dmLookup = {dm.name: dm for dm in self.conflict.decisionMakers}
        dmNames = tuple(self.dmLookup.keys())
        self.activeDMname = StringVar(value=dmNames[0])
        self.activeDM = self.dmLookup[dmNames[0]]

        dmSelLabel = ttk.Label(self, text="Decision Maker")
        dmSelLabel.grid(column=0, row=0)

        self.dmSelector = ttk.Combobox(self, textvariable=self.activeDMname,
                                       values=dmNames, state='readonly')
        self.dmSelector.grid(column=1, row=0, sticky=NSEW)
        self.dmSelector.bind('<<ComboboxSelected>>', self.dmSel)

        self.rbeCanvas = Canvas(self)
        self.rdBtnFrame = ttk.Frame(self.rbeCanvas)
        self.scrollY = ttk.Scrollbar(self, orient=VERTICAL,
                                     command=self.rbeCanvas.yview)

        self.rbeCanvas.grid(column=0, row=1, columnspan=2, sticky=NSEW)
        self.scrollY.grid(column=2, row=1, sticky=NSEW)
        self.rbeCanvas.configure(yscrollcommand=self.scrollY.set)
        self.canvWindow = self.rbeCanvas.create_window(
            (0, 0), window=self.rdBtnFrame, anchor='nw')

        self.rowconfigure(1, weight=1)

        self.entryText = StringVar(value='')

        vcmd = self.register(self.onValidate)
        self.entryBx = ttk.Entry(self, textvariable=self.entryText,
                                 validate="key",
                                 validatecommand=(vcmd, '%S', '%P'))
        self.entryBx.grid(column=0, row=2, columnspan=2, sticky=NSEW)
        self.entryBx.bind('<Return>', self.generateAdd)

        self.warnText = StringVar(value='')

        self.addBtn = ttk.Button(self, text='Remove as Misperceived Condition',
                                 command=self.generateAdd)
        self.mutExBtn = ttk.Button(self,
                                   text='Perceived as Mutually Exclusive',
                                   command=self.generateMutEx)
        self.warnLab = ttk.Label(self, textvariable=self.warnText)
        self.warnLab.grid(column=0, row=3, sticky=NSEW)
        self.addBtn.grid(column=0, row=4, columnspan=2, sticky=NSEW)
        self.mutExBtn.grid(column=0, row=5, columnspan=2, sticky=NSEW)

        self.reloadOpts()
Example #30
0
 def create_combo(self, j):
     # create the j'th race / power combo to display in frame_combos.
     # TODO: how to not call button function upon creation. labmda?
     # 
     combo_textvar = StringVar()
     combo_textvar.set(game.powers[j] + "-" + game.races[j])
     button_combo = Button(self.frame_combos, textvariable = combo_textvar,
                           state = "disabled", name = "combo_" + str(j),
                          command = lambda: self.choose_combo(j))
     button_combo.grid(row = self.num_of_combos - j)
     self.combos[j] = {"button": button_combo}
Example #31
0
from tkinter import StringVar, Tk, Label, Checkbutton, IntVar

def update_label():
    if var.get() == 1:
        label_text.set("On")
    else:
        label_text.set("Off")

window = Tk()

label_text = StringVar()
label = Label(window, textvariable=label_text)
label_text.set("Off")

var = IntVar()
check= Checkbutton(window,  text="On", variable=var,
                   onvalue=1, offvalue=0, command=update_label)

label.pack()
check.pack(side="left")

window.mainloop()
Example #32
0
    def initialize(self):
        # menu left
        self.clearVars()
        self.frame_w = Frame(self, width=100, bg="black")
        self.frame_w2 = Frame(self.frame_w,
                              width=100,
                              height=150,
                              bg='#dfdfdf')

        self.left_title = Label(self.frame_w2, text='', bg='#dfdfdf')
        self.left_title.pack()
        self.s_title = Label(self.frame_w2, text='# @_#E', bg='#dfdfdf')
        self.s_title.pack(side=BOTTOM)

        self.but_file = Button(self.frame_w2,
                               text='Dump file',
                               command=self.getPath)
        self.but_fold = Button(self.frame_w2,
                               text='Dump folder',
                               command=self.getPathDir)
        self.but_sdir = Button(self.frame_w2,
                               state=DISABLED,
                               text='Save to...',
                               command=self.setDirectory)
        self.but_conv = Button(self.frame_w2,
                               state=DISABLED,
                               text='Go',
                               command=self.convertFile)
        self.but_exit = Button(self.frame_w2,
                               text='Exit',
                               command=lambda: exit())
        self.but_file.pack(fill=BOTH)
        self.but_fold.pack(fill=BOTH)
        self.but_sdir.pack(fill=BOTH)
        self.but_conv.pack(fill=BOTH)
        self.but_exit.pack(fill=BOTH, side=BOTTOM)
        famicom_img = PhotoImage(file='images/img.png')
        famicom_label = Label(self.frame_w2, image=famicom_img)
        famicom_label.image = famicom_img
        famicom_label.pack(fill=BOTH, expand=True)
        self.frame_w2.pack(side=TOP, fill=BOTH, expand=True)

        # right area
        self.frame_e = Frame(self, bg="#dfdfdf")

        self.some_title = Label(self.frame_e,
                                text="__ by nnov 2017 __  vaporw8bit  ___",
                                bg="#dfdfdf")
        self.some_title.pack()
        self.canvas_area = Canvas(self,
                                  width=500,
                                  height=400,
                                  background="#ffffff")
        self.canvas_area.grid(row=1, column=1)

        back_img = PhotoImage(file='images/back.png')
        back_label = Label(self.canvas_area, image=back_img)
        back_label.image = back_img
        back_label.pack(fill=BOTH, expand=True)

        # status
        self.status_frame = Frame(self)
        self.labelVariable = StringVar()
        self.status = Label(self.status_frame,
                            textvariable=self.labelVariable,
                            anchor="w",
                            fg="white",
                            bg="purple")
        self.status.pack(fill=BOTH, expand=True)
        self.labelVariable.set('Please select a CHR file.')

        self.frame_w.grid(row=0, column=0, rowspan=2, sticky="nsew")
        self.frame_e.grid(row=0, column=1, sticky="ew")
        self.canvas_area.grid(row=1, column=1, sticky="nsew")
        self.status_frame.grid(row=2, column=0, columnspan=2, sticky="ew")

        self.grid_rowconfigure(1, weight=1)
        self.grid_columnconfigure(1, weight=1)

        self.resizable(False, False)
Example #33
0
 def __get_directory(element: StringVar) -> None:
     folder = filedialog.askdirectory()
     if folder != '':
         element.set(folder)
Example #34
0
    def ui_process(self):
        """
        Ui主程序
        :param
        :return:
        """
        root = Tk()
        self.root = root
        # 设置窗口位置
        root.title("豆瓣电影小助手(可筛选、下载自定义电影)----吾爱破解论坛  www.52pojie.cn")
        self.center_window(root, 1000, 565)
        root.resizable(0, 0)  # 框体大小可调性,分别表示x,y方向的可变性

        # 从排行榜 电影搜索布局开始
        # 容器控件
        labelframe = LabelFrame(root, width=660, height=300, text="搜索电影")
        labelframe.place(x=5, y=5)
        self.labelframe = labelframe

        # 电影类型
        L_typeId = Label(labelframe, text='电影类型')
        L_typeId.place(x=0, y=10)
        self.L_typeId = L_typeId

        #下拉列表框
        comvalue = StringVar()
        C_type = ttk.Combobox(labelframe,
                              width=5,
                              textvariable=comvalue,
                              state='readonly')
        # 将影片类型输入到下拉列表框中
        jsonMovieData = loads(movieData)  #json数据
        movieList = []
        for subMovieData in jsonMovieData:  #对每一种类的电影题材进行操作
            movieList.append(subMovieData['title'])
        C_type["values"] = movieList  #初始化
        C_type.current(9)  # 选择第一个
        C_type.place(x=65, y=8)
        self.C_type = C_type

        # 欲获取的电影数量
        L_count = Label(labelframe, text='获取数量=')
        L_count.place(x=150, y=10)
        self.L_count = L_count

        # 文本框
        T_count = Entry(labelframe, width=5)
        T_count.delete(0, END)
        T_count.insert(0, '500')
        T_count.place(x=220, y=7)
        self.T_count = T_count

        # 评分
        L_rating = Label(labelframe, text='影片评分>')
        L_rating.place(x=280, y=10)
        self.L_rating = L_rating

        # 文本框
        T_rating = Entry(labelframe, width=5)
        T_rating.delete(0, END)
        T_rating.insert(0, '8.0')
        T_rating.place(x=350, y=7)
        self.T_rating = T_rating

        # 评价人数
        L_vote = Label(labelframe, text='评价人数>')
        L_vote.place(x=410, y=10)
        self.L_vote = L_vote

        # 文本框
        T_vote = Entry(labelframe, width=7)
        T_vote.delete(0, END)
        T_vote.insert(0, '100000')
        T_vote.place(x=480, y=7)
        self.T_vote = T_vote

        # 查询按钮
        #lambda表示绑定的函数需要带参数,请勿删除lambda,否则会出现异常
        #thread_it表示新开启一个线程执行这个函数,防止GUI界面假死无响应
        B_0 = Button(labelframe, text="从排行榜搜索")
        B_0.place(x=560, y=10)
        self.B_0 = B_0

        # 框架布局,承载多个控件
        frame_root = Frame(labelframe, width=400)
        frame_l = Frame(frame_root)
        frame_r = Frame(frame_root)
        self.frame_root = frame_root
        self.frame_l = frame_l
        self.frame_r = frame_r

        # 表格
        columns = ("影片名字", "影片评分", "同类排名", "评价人数")
        treeview = ttk.Treeview(frame_l,
                                height=10,
                                show="headings",
                                columns=columns)

        treeview.column("影片名字", width=210, anchor='center')  # 表示列,不显示
        treeview.column("影片评分", width=210, anchor='center')
        treeview.column("同类排名", width=100, anchor='center')
        treeview.column("评价人数", width=100, anchor='center')

        treeview.heading("影片名字", text="影片名字")  # 显示表头
        treeview.heading("影片评分", text="影片评分")
        treeview.heading("同类排名", text="同类排名")
        treeview.heading("评价人数", text="评价人数")

        #垂直滚动条
        vbar = ttk.Scrollbar(frame_r, command=treeview.yview)
        treeview.configure(yscrollcommand=vbar.set)

        treeview.pack()
        self.treeview = treeview
        vbar.pack(side=RIGHT, fill=Y)
        self.vbar = vbar

        # 框架的位置布局
        frame_l.grid(row=0, column=0, sticky=NSEW)
        frame_r.grid(row=0, column=1, sticky=NS)
        frame_root.place(x=5, y=70)

        # 从排行榜 电影搜索布局结束

        # 输入关键字 电影搜索布局开始

        # 影片名称
        L_vote_keyword = Label(labelframe, text='影片名称')
        L_vote_keyword.place(x=0, y=40)
        #L_vote_keyword.grid(row=0,column=0)
        self.L_vote_keyword = L_vote_keyword

        # 文本框
        T_vote_keyword = Entry(labelframe, width=53)
        T_vote_keyword.delete(0, END)
        T_vote_keyword.insert(0, '我不是药神')
        T_vote_keyword.place(x=66, y=37)
        self.T_vote_keyword = T_vote_keyword

        # 查询按钮
        #lambda表示绑定的函数需要带参数,请勿删除lambda,否则会出现异常
        #thread_it表示新开启一个线程执行这个函数,防止GUI界面假死无响应
        B_0_keyword = Button(labelframe, text="从关键字搜索")
        B_0_keyword.place(x=560, y=40)
        self.B_0_keyword = B_0_keyword

        # 输入关键字 电影搜索布局结束

        # 电影详情布局开始
        # 容器控件
        labelframe_movie_detail = LabelFrame(root, text="影片详情")
        labelframe_movie_detail.place(x=670, y=5)
        self.labelframe_movie_detail = labelframe_movie_detail

        # 框架布局,承载多个控件
        frame_left_movie_detail = Frame(labelframe_movie_detail,
                                        width=160,
                                        height=280)
        frame_left_movie_detail.grid(row=0, column=0)
        self.frame_left_movie_detail = frame_left_movie_detail

        frame_right_movie_detail = Frame(labelframe_movie_detail,
                                         width=160,
                                         height=280)
        frame_right_movie_detail.grid(row=0, column=1)
        self.frame_right_movie_detail = frame_right_movie_detail

        #影片图片
        label_img = Label(frame_left_movie_detail, text="", anchor=N)
        label_img.place(x=0, y=0)  #布局
        self.label_img = label_img

        # IMDB评分
        ft_rating_imdb = font.Font(weight=font.BOLD)
        label_movie_rating_imdb = Label(frame_left_movie_detail,
                                        text="IMDB评分",
                                        fg='#7F00FF',
                                        font=ft_rating_imdb,
                                        anchor=NW)
        label_movie_rating_imdb.place(x=0, y=250)
        self.label_movie_rating_imdb = label_movie_rating_imdb

        # 查询按钮
        B_0_imdb = Button(frame_left_movie_detail, text="初始化")
        B_0_imdb.place(x=115, y=250)
        self.B_0_imdb = B_0_imdb

        #影片名字
        ft = font.Font(size=15, weight=font.BOLD)
        label_movie_name = Label(frame_right_movie_detail,
                                 text="影片名字",
                                 fg='#FF0000',
                                 font=ft,
                                 anchor=NW)
        label_movie_name.place(x=0, y=0)
        self.label_movie_name = label_movie_name

        #影片评分
        ft_rating = font.Font(weight=font.BOLD)
        label_movie_rating = Label(frame_right_movie_detail,
                                   text="影片评价",
                                   fg='#7F00FF',
                                   font=ft_rating,
                                   anchor=NW)
        label_movie_rating.place(x=0, y=30)
        self.label_movie_rating = label_movie_rating

        #影片年代
        ft_time = font.Font(weight=font.BOLD)
        label_movie_time = Label(frame_right_movie_detail,
                                 text="影片日期",
                                 fg='#666600',
                                 font=ft_time,
                                 anchor=NW)
        label_movie_time.place(x=0, y=60)
        self.label_movie_time = label_movie_time

        #影片类型
        ft_type = font.Font(weight=font.BOLD)
        label_movie_type = Label(frame_right_movie_detail,
                                 text="影片类型",
                                 fg='#330033',
                                 font=ft_type,
                                 anchor=NW)
        label_movie_type.place(x=0, y=90)
        self.label_movie_type = label_movie_type

        #影片演员
        label_movie_actor = Label(frame_right_movie_detail,
                                  text="影片演员",
                                  wraplength=135,
                                  justify='left',
                                  anchor=NW)
        label_movie_actor.place(x=0, y=120)
        self.label_movie_actor = label_movie_actor

        # 电影详情布局结束

        # 在线播放布局开始

        labelframe_movie_play_online = LabelFrame(root,
                                                  width=324,
                                                  height=230,
                                                  text="在线观看")
        labelframe_movie_play_online.place(x=5, y=305)
        self.labelframe_movie_play_online = labelframe_movie_play_online

        # 框架布局,承载多个控件
        frame_root_play_online = Frame(labelframe_movie_play_online, width=324)
        frame_l_play_online = Frame(frame_root_play_online)
        frame_r_play_online = Frame(frame_root_play_online)
        self.frame_root_play_online = frame_root_play_online
        self.frame_l_play_online = frame_l_play_online
        self.frame_r_play_online = frame_r_play_online

        # 表格
        columns_play_online = ("来源名称", "是否免费", "播放地址")
        treeview_play_online = ttk.Treeview(frame_l_play_online,
                                            height=10,
                                            show="headings",
                                            columns=columns_play_online)
        treeview_play_online.column("来源名称", width=90, anchor='center')
        treeview_play_online.column("是否免费", width=80, anchor='center')
        treeview_play_online.column("播放地址", width=120, anchor='center')
        treeview_play_online.heading("来源名称", text="来源名称")
        treeview_play_online.heading("是否免费", text="是否免费")
        treeview_play_online.heading("播放地址", text="播放地址")

        #垂直滚动条
        vbar_play_online = ttk.Scrollbar(frame_r_play_online,
                                         command=treeview_play_online.yview)
        treeview_play_online.configure(yscrollcommand=vbar_play_online.set)

        treeview_play_online.pack()
        self.treeview_play_online = treeview_play_online
        vbar_play_online.pack(side=RIGHT, fill=Y)
        self.vbar_play_online = vbar_play_online

        # 框架的位置布局
        frame_l_play_online.grid(row=0, column=0, sticky=NSEW)
        frame_r_play_online.grid(row=0, column=1, sticky=NS)
        frame_root_play_online.place(x=5, y=0)

        # 在线播放布局结束

        # 保存到云盘布局开始

        labelframe_movie_save_cloud_disk = LabelFrame(root,
                                                      width=324,
                                                      height=230,
                                                      text="云盘搜索")
        labelframe_movie_save_cloud_disk.place(x=340, y=305)
        self.labelframe_movie_save_cloud_disk = labelframe_movie_save_cloud_disk

        # 框架布局,承载多个控件
        frame_root_save_cloud_disk = Frame(labelframe_movie_save_cloud_disk,
                                           width=324)
        frame_l_save_cloud_disk = Frame(frame_root_save_cloud_disk)
        frame_r_save_cloud_disk = Frame(frame_root_save_cloud_disk)
        self.frame_root_save_cloud_disk = frame_root_save_cloud_disk
        self.frame_l_save_cloud_disk = frame_l_save_cloud_disk
        self.frame_r_save_cloud_disk = frame_r_save_cloud_disk

        # 表格
        columns_save_cloud_disk = ("来源名称", "是否有效", "播放地址")
        treeview_save_cloud_disk = ttk.Treeview(
            frame_l_save_cloud_disk,
            height=10,
            show="headings",
            columns=columns_save_cloud_disk)
        treeview_save_cloud_disk.column("来源名称", width=90, anchor='center')
        treeview_save_cloud_disk.column("是否有效", width=80, anchor='center')
        treeview_save_cloud_disk.column("播放地址", width=120, anchor='center')
        treeview_save_cloud_disk.heading("来源名称", text="来源名称")
        treeview_save_cloud_disk.heading("是否有效", text="是否有效")
        treeview_save_cloud_disk.heading("播放地址", text="播放地址")

        #垂直滚动条
        vbar_save_cloud_disk = ttk.Scrollbar(
            frame_r_save_cloud_disk, command=treeview_save_cloud_disk.yview)
        treeview_save_cloud_disk.configure(
            yscrollcommand=vbar_save_cloud_disk.set)

        treeview_save_cloud_disk.pack()
        self.treeview_save_cloud_disk = treeview_save_cloud_disk
        vbar_save_cloud_disk.pack(side=RIGHT, fill=Y)
        self.vbar_save_cloud_disk = vbar_save_cloud_disk

        # 框架的位置布局
        frame_l_save_cloud_disk.grid(row=0, column=0, sticky=NSEW)
        frame_r_save_cloud_disk.grid(row=0, column=1, sticky=NS)
        frame_root_save_cloud_disk.place(x=5, y=0)

        # 保存到云盘布局结束

        # BT下载布局开始

        labelframe_movie_bt_download = LabelFrame(root,
                                                  width=324,
                                                  height=230,
                                                  text="影视下载")
        labelframe_movie_bt_download.place(x=670, y=305)
        self.labelframe_movie_bt_download = labelframe_movie_bt_download

        # 框架布局,承载多个控件
        frame_root_bt_download = Frame(labelframe_movie_bt_download, width=324)
        frame_l_bt_download = Frame(frame_root_bt_download)
        frame_r_bt_download = Frame(frame_root_bt_download)
        self.frame_root_bt_download = frame_root_bt_download
        self.frame_l_bt_download = frame_l_bt_download
        self.frame_r_bt_download = frame_r_bt_download

        # 表格
        columns_bt_download = ("来源名称", "是否有效", "播放地址")
        treeview_bt_download = ttk.Treeview(frame_l_bt_download,
                                            height=10,
                                            show="headings",
                                            columns=columns_bt_download)
        treeview_bt_download.column("来源名称", width=90, anchor='center')
        treeview_bt_download.column("是否有效", width=80, anchor='center')
        treeview_bt_download.column("播放地址", width=120, anchor='center')
        treeview_bt_download.heading("来源名称", text="来源名称")
        treeview_bt_download.heading("是否有效", text="是否有效")
        treeview_bt_download.heading("播放地址", text="播放地址")

        #垂直滚动条
        vbar_bt_download = ttk.Scrollbar(frame_r_bt_download,
                                         command=treeview_bt_download.yview)
        treeview_bt_download.configure(yscrollcommand=vbar_bt_download.set)

        treeview_bt_download.pack()
        self.treeview_bt_download = treeview_bt_download
        vbar_bt_download.pack(side=RIGHT, fill=Y)
        self.vbar_bt_download = vbar_bt_download

        # 框架的位置布局
        frame_l_bt_download.grid(row=0, column=0, sticky=NSEW)
        frame_r_bt_download.grid(row=0, column=1, sticky=NS)
        frame_root_bt_download.place(x=5, y=0)

        # BT下载布局结束

        #项目的一些信息
        ft = font.Font(size=14, weight=font.BOLD)
        project_statement = Label(
            root,
            text="豆瓣电影小助手(可筛选、下载自定义电影)----吾爱破解论坛  www.52pojie.cn",
            fg='#FF0000',
            font=ft,
            anchor=NW)
        project_statement.place(x=5, y=540)
        self.project_statement = project_statement

        #绑定事件
        treeview.bind('<<TreeviewSelect>>', self.show_movie_data)  # 表格绑定选择事件
        treeview.bind('<Double-1>',
                      self.open_in_browser_douban_url)  # 表格绑定鼠标左键事件
        treeview_play_online.bind('<Double-1>',
                                  self.open_in_browser)  # 表格绑定左键双击事件
        treeview_save_cloud_disk.bind(
            '<Double-1>', self.open_in_browser_cloud_disk)  # 表格绑定左键双击事件
        treeview_bt_download.bind(
            '<Double-1>', self.open_in_browser_bt_download)  # 表格绑定左键双击事件
        B_0.configure(
            command=lambda: thread_it(self.searh_movie_in_rating))  #按钮绑定单击事件
        B_0_keyword.configure(
            command=lambda: thread_it(self.searh_movie_in_keyword))  #按钮绑定单击事件
        B_0_imdb.configure(
            command=lambda: thread_it(self.show_IDMB_rating))  # 按钮绑定单击事件
        T_vote_keyword.bind('<Return>',
                            handlerAdaptor(
                                self.keyboard_T_vote_keyword))  # 文本框绑定选择事件
        project_statement.bind('<ButtonPress-1>',
                               self.project_statement_show)  # 标签绑定鼠标单击事件
        project_statement.bind('<Enter>',
                               self.project_statement_get_focus)  # 标签绑定获得焦点事件
        project_statement.bind('<Leave>',
                               self.project_statement_lose_focus)  # 标签绑定失去焦点事件

        root.mainloop()
Example #35
0
class GuiApplication:
    def __init__(self):
        self.window = Tk()
        self.window.title(MAIN_TITLE)

        # this is so dumb
        if system() == 'Windows':
            with open('temp_icon.ico', 'wb') as temp_icon:
                temp_icon.write(base64.b64decode(ICON_WIN))
                self.window.iconbitmap('temp_icon.ico')
            os.remove('temp_icon.ico')

        self.window.wm_title(MAIN_TITLE)
        #self.window.resizable(False, False)

        # stupid shit only happens on mac???
        if system() == "Darwin":
            self.window.tk_setPalette(background="#e8e8e8")

        self.initialize_gui()

    def initialize_gui(self, initial_values=None):
        self.selections = {}
        self.combobox_selections = {}
        self.checkbox_text = {}

        self.main_frame = Frame(self.window)

        self.gridcontainer = Frame(self.main_frame)
        self.frames = {
            'rom-settings':
            ttk.LabelFrame(self.gridcontainer, text="ROM Settings"),
            'gameplay':
            ttk.LabelFrame(self.gridcontainer, text="Gameplay Settings"),
            'aesthetics':
            ttk.LabelFrame(self.gridcontainer, text="Aesthetic Settings"),
        }

        self.frames['rom-settings'].pack(side=TOP, fill=X, padx=2, pady=2)
        self.frames['gameplay'].pack(side=LEFT,
                                     fill=BOTH,
                                     expand=True,
                                     anchor="w",
                                     padx=2,
                                     pady=2)
        self.frames['aesthetics'].pack(side=RIGHT,
                                       fill=BOTH,
                                       expand=True,
                                       anchor="w",
                                       padx=2,
                                       pady=2)

        #self.gridcontainer.add(self.frames['rom-settings'], text='ROM Options')
        #self.gridcontainer.add(self.frames['gameplay'], text='Gameplay Rules')
        #self.gridcontainer.add(self.frames['aesthetic'], text='Aesthetic Rules')

        self.add_rom_settings()
        self.add_settings_from_file()

        self.add_main_settings()

        self.gridcontainer.pack(expand=True,
                                fill=BOTH,
                                anchor="center",
                                padx=5,
                                pady=5)
        self.main_frame.pack(expand=True, fill=BOTH)

        self.window.update_idletasks()
        self.window.mainloop()

    def select_rom_input(self):
        input_rom = filedialog.askopenfilename(title="Select Input ROM",
                                               filetypes=[("ROM Files",
                                                           (".z64", ".n64")),
                                                          ("All Files", "*")])
        self.selections['input_rom'].set(input_rom)

        #if input_rom != "":
        #if self.selections['output_rom'].get() == "":
        #path_parts = input_rom.split(".")
        #guessed_output_file = f'{".".join(path_parts[:-1])}.out.{path_parts[-1]}'
        #self.selections['output_rom'].set(guessed_output_file)

    def select_rom_output(self):
        output_suggestion = 'SM64_Randomizer.z64'
        current_input = self.selections['input_rom'].get()
        if current_input:
            path = Path(current_input)
            file = path.stem
            ext = path.suffix
            output_suggestion = f'{file}.out{ext}'

        output_int = 1
        while os.path.exists(output_suggestion):
            file = ".".join(output_suggestion.split(".")[:-1])
            ext = output_suggestion.split(".")[-1]

            output_suggestion = f'{file}.{output_int}.{ext}'

        output_rom = filedialog.asksaveasfilename(
            title="Select Output Path",
            filetypes=[("ROM Files", (".z64"))],
            #initialdir=self.selections["output_rom"],
            initialfile=output_suggestion)

        if output_rom != "":
            self.selections['output_rom'].set(output_rom)

    def toggle_checkbox_label(self, key):
        def trigger():
            if bool(self.selections[key].get()):
                self.checkbox_text[key].set("Enabled")
            else:
                self.checkbox_text[key].set("Disabled")

        return trigger

    def set_random_seed(self):
        self.seed_entry.set(randint(0, 1e19))

    def set_seed_as_num(self, *args):
        byte_entry = bytes(self.seed_entry.get(), 'utf8')
        self.selections['seed'].set(
            int.from_bytes(byte_entry, 'little', signed=False))

    def check_validity(self):
        rom_file = self.selections['input_rom'].get()
        self.check_error = None

        if not len(rom_file):
            self.check_error = 'Please select a ROM-File first'
            return False

        if not os.path.isfile(rom_file):
            self.check_error = 'The selected ROM is invalid'
            return False

        out_file = self.selections['output_rom'].get()
        if not len(out_file):
            self.check_error = 'Please select an output path'
            return False

        return True

    def read_from_clipboard(self):
        data = pyperclip.paste()

        try:
            json_data = json.loads(data)
        except Exception:
            messagebox.showerror(
                title=MAIN_TITLE,
                message=
                f"Sorry, the settings in your clipboard are not valid. Please try again."
            )
            return

        if json_data['version'] != __version__:
            messagebox.showerror(
                title=MAIN_TITLE,
                message=
                f"Sorry, the settings version do not match. Please ensure you're using the same version when copying the settings."
            )
            return

        json_data["input_rom"] = self.selections['input_rom'].get()
        json_data["output_rom"] = self.selections['output_rom'].get()

        for (key, tkinter_var) in self.selections.items():
            if key in json_data:
                tkinter_var.set(json_data[key])
        self.seed_entry.set(json_data["seed"])
        self.set_seed_as_num()

        self.pasteSettings.configure(text="Settings applied!")
        self.window.update()
        s = Timer(
            2, lambda: self.pasteSettings.configure(
                text="Paste Settings from Clipboard"))
        s.start()

    def copy_to_clipboard(self):
        output = {"version": __version__}

        data = {key: var.get() for (key, var) in self.selections.items()}
        output.update(data)

        # this makes no sense for other people
        del output['input_rom']
        del output['output_rom']
        output['seed'] = self.seed_entry.get()

        pyperclip.copy(json.dumps(output))

        self.copySettings.configure(text="Settings copied!")
        s = Timer(
            2, lambda: self.copySettings.configure(
                text="Copy Settings to Clipboard"))
        s.start()

    def generate_rom(self):
        try:
            if not self.check_validity():
                messagebox.showerror(title="ROM Generation Failed",
                                     message=self.check_error)
                return

            params = []
            input_rom = None

            for (key, tkinter_var) in self.selections.items():
                key_in_arg_format = f"--{key.replace('_', '-')}"

                if key == 'input_rom':
                    input_rom = tkinter_var.get()
                elif key == 'output_rom':
                    params.append('--out')
                    params.append(tkinter_var.get())
                elif isinstance(tkinter_var, BooleanVar):
                    # boolean args work by adding the param or not
                    if tkinter_var.get():
                        params.append(key_in_arg_format)
                elif isinstance(tkinter_var, StringVar):
                    params.append(key_in_arg_format)
                    params.append(quote(tkinter_var.get()))
                else:
                    raise NotImplementedError(
                        f'arg format for {type(tkinter_var)} is not implemented yet'
                    )

            args = [input_rom, *params]
            from Rom import ROM

            test_output = os.path.join(tempfile.gettempdir(),
                                       'test_output.z64')
            try:
                with ROM(input_rom, test_output) as test_rom:
                    test_rom.verify_header()
            except Exception as excp:
                messagebox.showerror(
                    title="ROM Generation failed",
                    message=
                    f'Sorry, the specified ROM is not valid. Verification failed with error: {excp}'
                )

            try:
                run_with_args(args)
            except Exception as err:
                messagebox.showerror(
                    title="ROM Generation failed",
                    message=
                    f"Unfortunately, generation failed with error:\n {err}\nPlease submit this error to the projects github: https://github.com/andre-meyer/sm64-randomizer/issues"
                )
                print(err)
                return

            rom_output = self.selections['output_rom'].get()
            (folder_containing_rom,
             filename_output) = os.path.split(rom_output)
            messagebox.showinfo(
                title="ROM Generation completed!",
                message=
                f"Your randomized ROM was created as \"{filename_output}\"! Have fun!"
            )
            #if system() == "Windows":
            #subprocess.Popen('explorer /select,"' + rom_output.replace("/", "\\") + '"', shell=True)
            #else:
            #webbrowser.open("file:///" + folder_containing_rom)
            return True
        except Exception as excp:
            messagebox.showerror(
                title="ROM Generation failed",
                message=
                f'Sorry, ROM generation failed with error:\n {excp}\nPlease submit this error to the projects github: https://github.com/andre-meyer/sm64-randomizer/issues'
            )

    def add_setting_field(self, field):
        master = self.frames[field['category']]
        optionFrame = Frame(master)
        key = field['name']

        if field['type'] == 'checkbox':
            self.selections[key] = BooleanVar(optionFrame)
            checkboxField = ttk.Checkbutton(optionFrame,
                                            text=field['label'],
                                            variable=self.selections[key])
            if 'help' in field:
                CreateToolTip(checkboxField, field['help'])

            checkboxField.pack(side=LEFT)
        elif field['type'] == 'select':
            optionLabel = ttk.Label(optionFrame, text=field['label'])
            optionLabel.pack(side=LEFT)
            if 'help' in field:
                CreateToolTip(optionLabel, field['help'])

            self.selections[key] = StringVar(optionFrame)
            self.combobox_selections[key] = StringVar(optionFrame)

            choice_dict = {
                option['label']: option['value']
                for option in field['options']
            }
            choice_dict_invert = {
                option['value']: option['label']
                for option in field['options']
            }
            self.selections[key].set(field['options'][0]['value'])

            optionsField = ttk.OptionMenu(
                optionFrame,
                self.combobox_selections[key],
                field['options'][0]['label'],
                *[option['label'] for option in field['options']],
                command=lambda *args, sel_key=key, choices=choice_dict: self.
                selections[sel_key].set(choices[self.combobox_selections[
                    sel_key].get()]))
            self.selections[key].trace(
                'w',
                lambda *args, sel_key=key, choices=choice_dict_invert: self.
                combobox_selections[sel_key].set(choice_dict_invert[
                    self.selections[sel_key].get()]))

            optionsField.pack(side=LEFT, fill=X, expand=True)

        optionFrame.pack(side=TOP, padx=5, pady=(5, 1), fill=X)

    def add_settings_from_file(self):
        with open(
                os.path.join(application_path, 'Data',
                             'configurableParams.json'), 'r') as json_file:
            fields = json.loads(json_file.read())

            for field in fields:
                self.add_setting_field(field)

    """
  def add_gameplay_settings(self):
    self.add_setting_fields(gameplay_settings, self.frames['gameplay'])

  def add_aesthetic_settings(self):
    self.add_setting_fields(aesthetic_settings, self.frames['aesthetic'])
  """

    def add_main_settings(self):
        buttonsFrame = Frame(self.main_frame, padx=5, pady=5, height=60)
        buttonsFrame.pack_propagate(0)

        generateButton = ttk.Button(buttonsFrame,
                                    text="Generate ROM",
                                    command=self.generate_rom,
                                    width=10)
        generateButton.pack(side=LEFT, fill=BOTH, expand=True)
        self.copySettings = ttk.Button(buttonsFrame,
                                       text="Copy Settings to Clipboard",
                                       command=self.copy_to_clipboard,
                                       width=20)
        self.copySettings.pack(side=LEFT, fill=BOTH, expand=True)
        self.pasteSettings = ttk.Button(buttonsFrame,
                                        text="Paste Settings from Clipboard",
                                        command=self.read_from_clipboard,
                                        width=30)
        self.pasteSettings.pack(side=LEFT, fill=BOTH, expand=True)

        buttonsFrame.pack(fill=X, anchor="center", side=BOTTOM)

    def add_rom_settings(self):
        inputFrame = Frame(self.frames['rom-settings'])
        self.seed_entry = StringVar()
        self.seed_entry.trace('w', self.set_seed_as_num)

        self.selections['seed'] = StringVar()
        self.set_random_seed()
        seedFrame = Frame(inputFrame)

        seedLabel = Label(seedFrame, text="Seed", width=10)
        seedLabel.pack(side=LEFT)
        seedEntry = Entry(seedFrame, textvariable=self.seed_entry)
        seedEntry.pack(side=LEFT, fill=BOTH, expand=True)
        seedRandom = ttk.Button(seedFrame,
                                text='New',
                                command=self.set_random_seed,
                                width=15)
        seedRandom.pack(side=RIGHT)

        seedFrame.pack(side=TOP, fill=X, expand=True)

        self.selections['input_rom'] = StringVar()

        baseRomLabel = Label(inputFrame, text="Input ROM", width=10)
        baseRomLabel.pack(side=LEFT, padx=(0, 0))
        baseRomEntry = Entry(inputFrame,
                             textvariable=self.selections['input_rom'])
        baseRomEntry.pack(side=LEFT, fill=BOTH, expand=True)
        romSelectButton = ttk.Button(inputFrame,
                                     text='Select ROM',
                                     command=self.select_rom_input,
                                     width=15)
        romSelectButton.pack(side=RIGHT)

        inputFrame.pack(side=TOP, fill=X, expand=True)

        outputFrame = Frame(self.frames['rom-settings'])
        self.selections['output_rom'] = StringVar()

        outputPathLabel = Label(outputFrame, text="Output ROM", width=10)
        outputPathLabel.pack(side=LEFT, padx=(0, 0))
        outputRomEntry = Entry(outputFrame,
                               textvariable=self.selections['output_rom'])
        outputRomEntry.pack(side=LEFT, fill=BOTH, expand=True)
        outputSelectButton = ttk.Button(outputFrame,
                                        text='Select Output',
                                        command=self.select_rom_output,
                                        width=15)
        outputSelectButton.pack(side=RIGHT)

        outputFrame.pack(side=TOP, fill=X, expand=True)
Example #36
0
class SearchEngine:
    """Handles searching a text widget for Find, Replace, and Grep."""
    def __init__(self, root):
        '''Initialize Variables that save search state.

        The dialogs bind these to the UI elements present in the dialogs.
        '''
        self.root = root  # need for report_error()
        self.patvar = StringVar(root, '')  # search pattern
        self.revar = BooleanVar(root, False)  # regular expression?
        self.casevar = BooleanVar(root, False)  # match case?
        self.wordvar = BooleanVar(root, False)  # match whole word?
        self.wrapvar = BooleanVar(root, True)  # wrap around buffer?
        self.backvar = BooleanVar(root, False)  # search backwards?

    # Access methods

    def getpat(self):
        return self.patvar.get()

    def setpat(self, pat):
        self.patvar.set(pat)

    def isre(self):
        return self.revar.get()

    def iscase(self):
        return self.casevar.get()

    def isword(self):
        return self.wordvar.get()

    def iswrap(self):
        return self.wrapvar.get()

    def isback(self):
        return self.backvar.get()

    # Higher level access methods

    def setcookedpat(self, pat):
        "Set pattern after escaping if re."
        # called only in SearchDialog.py: 66
        if self.isre():
            pat = re.escape(pat)
        self.setpat(pat)

    def getcookedpat(self):
        pat = self.getpat()
        if not self.isre():  # if True, see setcookedpat
            pat = re.escape(pat)
        if self.isword():
            pat = r"\b%s\b" % pat
        return pat

    def getprog(self):
        "Return compiled cooked search pattern."
        pat = self.getpat()
        if not pat:
            self.report_error(pat, "Empty regular expression")
            return None
        pat = self.getcookedpat()
        flags = 0
        if not self.iscase():
            flags = flags | re.IGNORECASE
        try:
            prog = re.compile(pat, flags)
        except re.error as what:
            args = what.args
            msg = args[0]
            col = args[1] if len(args) >= 2 else -1
            self.report_error(pat, msg, col)
            return None
        return prog

    def report_error(self, pat, msg, col=-1):
        # Derived class could override this with something fancier
        msg = "Error: " + str(msg)
        if pat:
            msg = msg + "\nPattern: " + str(pat)
        if col >= 0:
            msg = msg + "\nOffset: " + str(col)
        tkMessageBox.showerror("Regular expression error",
                               msg,
                               master=self.root)

    def search_text(self, text, prog=None, ok=0):
        '''Return (lineno, matchobj) or None for forward/backward search.

        This function calls the right function with the right arguments.
        It directly return the result of that call.

        Text is a text widget. Prog is a precompiled pattern.
        The ok parameter is a bit complicated as it has two effects.

        If there is a selection, the search begin at either end,
        depending on the direction setting and ok, with ok meaning that
        the search starts with the selection. Otherwise, search begins
        at the insert mark.

        To aid progress, the search functions do not return an empty
        match at the starting position unless ok is True.
        '''

        if not prog:
            prog = self.getprog()
            if not prog:
                return None  # Compilation failed -- stop
        wrap = self.wrapvar.get()
        first, last = get_selection(text)
        if self.isback():
            if ok:
                start = last
            else:
                start = first
            line, col = get_line_col(start)
            res = self.search_backward(text, prog, line, col, wrap, ok)
        else:
            if ok:
                start = first
            else:
                start = last
            line, col = get_line_col(start)
            res = self.search_forward(text, prog, line, col, wrap, ok)
        return res

    def search_forward(self, text, prog, line, col, wrap, ok=0):
        wrapped = 0
        startline = line
        chars = text.get("%d.0" % line, "%d.0" % (line + 1))
        while chars:
            m = prog.search(chars[:-1], col)
            if m:
                if ok or m.end() > col:
                    return line, m
            line = line + 1
            if wrapped and line > startline:
                break
            col = 0
            ok = 1
            chars = text.get("%d.0" % line, "%d.0" % (line + 1))
            if not chars and wrap:
                wrapped = 1
                wrap = 0
                line = 1
                chars = text.get("1.0", "2.0")
        return None

    def search_backward(self, text, prog, line, col, wrap, ok=0):
        wrapped = 0
        startline = line
        chars = text.get("%d.0" % line, "%d.0" % (line + 1))
        while 1:
            m = search_reverse(prog, chars[:-1], col)
            if m:
                if ok or m.start() < col:
                    return line, m
            line = line - 1
            if wrapped and line < startline:
                break
            ok = 1
            if line <= 0:
                if not wrap:
                    break
                wrapped = 1
                wrap = 0
                pos = text.index("end-1c")
                line, col = map(int, pos.split("."))
            chars = text.get("%d.0" % line, "%d.0" % (line + 1))
            col = len(chars) - 1
        return None
Example #37
0
class GUI(Tk):

    __operators: list = ['/', '*', '+', '-']

    def __init__(self):
        ''' View initializer '''
        super().__init__()
        # Main window properties
        self.title("PyCalc (v1.1)")
        self.resizable(False, False)
        self.styler = ttk.Style()
        self._layout = [
            '*', '/', 'C', 'AC', '9', '8', '7', '-', '6', '5', '4', '+', '3',
            '2', '1', '+/-', '.', '0', 'Copy', '='
        ]
        self._adv_layout = [
            '(', ')', '^', 'C', '*', 'sin', 'cos', 'tan', '/', 'asin', 'acos',
            'atan', '+', 'x!', 'log', 'ln', '-', '\u03C0', 'e', '='
        ]

        # Inheriting from Storage for program logic
        self.logic = Storage()
        # Set General layout
        self.content = ttk.Notebook(master=self,
                                    padding=(0, 0, 0, 0),
                                    style='Outliner.TFrame')
        self.mainframe = ttk.Frame(self.content, relief='flat')
        self.mainframe2 = ttk.Frame(self.content)
        self.content.add(self.mainframe, text='Basic')
        self.content.add(self.mainframe2, text='Advanced')
        self.content.grid()
        self.label_text = StringVar()

    def default_style_settings(self):
        self.styler.configure("TLabel", font='Times 20')
        self.styler.configure("TButton",
                              relief='flat',
                              width='5',
                              padding='10',
                              background='bisque')
        self.styler.configure("EqualButton.TButton",
                              relief='falt',
                              background='SeaGreen2',
                              foreground='green4')
        self.styler.configure("EqualButton2.TButton",
                              relief='flat',
                              background='firebrick1',
                              foreground='green4')
        self.styler.configure("Outliner.TFrame", background='snow2')

    def create_basic_display(self):
        ''' Create the display '''
        display_frame = ttk.Frame(self.mainframe, relief='flat')
        display_frame['borderwidth'] = 10
        display_label = ttk.Label(display_frame, textvariable=self.label_text)
        # grid above widgets
        display_frame.grid(row=0, column=0, columnspan=4, pady=5, padx=5)
        display_label.grid(row=0, column=0, columnspan=4)

    def create_basic_buttons(self):
        ''' Create buttons under keypad '''
        keypad = ttk.Frame(self.mainframe)
        button_objects = {
            button: ttk.Button(
                master=keypad,
                text=button,
                command=lambda button=button: self._button_invoke(button))
            for button in self._layout
        }
        button_objects['AC']['command'] = lambda: self._button_invoke('A')
        button_objects['+/-']['command'] = lambda: self._button_invoke('i')
        button_objects['=']['style'] = 'EqualButton.TButton'

        keypad.grid()
        row, column = 0, 0
        for button in button_objects.values():
            button.grid(row=(row // 4) + 1, column=column % 4)
            row += 1
            column += 1

    def create_advanced_display(self):
        display_frame = ttk.Frame(self.mainframe2, relief='flat')
        display_frame['borderwidth'] = 10
        display_label = ttk.Label(display_frame, textvariable=self.label_text)
        # grid above widgets
        display_frame.grid(row=0, column=0, columnspan=4, pady=5, padx=5)
        display_label.grid(row=0, column=0, columnspan=4)

    def create_advanced_buttons(self):
        keypad = ttk.Frame(self.mainframe2)
        button_objects = {
            button: ttk.Button(
                master=keypad,
                text=button,
                command=lambda button=button: self._button_invoke(button))
            for button in self._adv_layout
        }
        button_objects['=']['style'] = 'EqualButton2.TButton'

        keypad.grid()
        row, column = 0, 0
        for button in button_objects.values():
            button.grid(row=(row // 4) + 1, column=column % 4)
            row += 1
            column += 1

    def _button_invoke(self, bt):
        if bt == '=':
            ''' If button pressed is '=' '''
            to_display = 'Ans: ' + self._get_answer(
                self.logic.show_storage_as_list())
            if (len(to_display) > 17):
                FONT = 'Times ' + str(20 * 17 // len(to_display))
                ttk.Style().configure("TLabel", font=FONT)
            else:
                ttk.Style().configure("TLabel", font='Times 20')
            self.label_text.set(to_display)
        elif bt == 'Copy':
            self._copy_to_clipboard(self.logic.show_storage_as_list())
        else:
            self.logic.into_storage(bt)
            to_display = self.logic.show_storage()
            if (len(to_display) > 17):
                FONT = 'Times ' + str(20 * 17 // len(to_display))
                ttk.Style().configure("TLabel", font=FONT)
            else:
                ttk.Style().configure("TLabel", font='Times 20')
            self.label_text.set(to_display)

    def keyboard_event_binding(self):
        self.bind("<Key>", self._callback)

    def _callback(self, e):
        if e.char.lower() in self._layout:
            self._button_invoke(e.char)
        elif e.char.lower() == 'c':
            self._button_invoke('Copy')
        elif e.char.lower() == 'a':
            self._button_invoke('A')
        elif e.char.lower() == 'i':
            self._button_invoke('i')
        elif e.char == '\r':
            self._button_invoke('=')
        elif e.char.lower() in ('\x08', 'b'):
            self._button_invoke('C')
        elif e.char.lower() == 'q':
            self.destroy()
        elif e.char == '(':
            self._button_invoke('(')
        elif e.char == ')':
            self._button_invoke(')')

    def _get_answer(self, inputs_as_list):
        calculate_instance = Calculate(inputs_as_list)
        return calculate_instance.calculate()

    def _copy_to_clipboard(self, inputs_as_list):
        to_clipboard("".join(inputs_as_list))
Example #38
0
    messagebox.showinfo(message=msg)


if __name__ == "__main__":
    _root = Tk()
    _root.title('Scrape app')

    _mainframe = ttk.Frame(_root, padding='5 5 5 5')
    _mainframe.grid(row=0, column=0, sticky=(E, W, N, S))

    _url_frame = ttk.LabelFrame(_mainframe, text='URL', padding='5 5 5 5')
    _url_frame.grid(row=0, column=0, sticky=(E, W))
    _url_frame.columnconfigure(0, weight=1)
    _url_frame.rowconfigure(0, weight=1)

    _url = StringVar()
    _url.set('http://localhost:8000')
    _url_entry = ttk.Entry(_url_frame, width=40, textvariable=_url)
    _url_entry.grid(row=0, column=0, sticky=(E, W, S, N), padx=5)

    _fetch_btn = ttk.Button(_url_frame, text='Fetch info', command=fetch_url)
    _fetch_btn.grid(row=0, column=1, sticky=W, padx=5)

    _img_frame = ttk.LabelFrame(_mainframe, text='Content', padding='9 0 0 0')
    _img_frame.grid(row=1, column=0, sticky=(N, S, E, W))

    _images = StringVar()
    _img_listbox = Listbox(_img_frame,
                           listvariable=_images,
                           height=6,
                           width=25)
Example #39
0
    def __init__(self, *args, **kwargs):
        #tk.Frame.__init__(self, parent, *args, **kwargs)
        #self.parent = parent
        #windows = self.window
        window = self.window
        window.title('my window')
        window.geometry('600x550')
        window.columnconfigure([0, 1, 2, 3], minsize=100)
        window.rowconfigure([3, 4, 5, 6, 7, 8], minsize=30)
        window.columnconfigure(0, weight=0)
        window.columnconfigure(1, weight=1)
        window.columnconfigure(2, weight=1)
        window.columnconfigure(4, weight=0)
        self.logger.info('start')

        tk.Label(window,
                 text='Magento TO UIS 轉檔程式',
                 anchor='w',
                 font=('微軟中黑體', 16)).grid(row=0, column=0, columnspan=4)
        tk.Label(window, text='選擇預定到貨日', anchor='w').grid(row=3,
                                                          column=0,
                                                          sticky='W')
        tk.Label(window, text='選擇轉入的Magento檔案', anchor='w').grid(row=4,
                                                                 column=0,
                                                                 sticky='W')
        tk.Label(window, text='轉出檔案存放目錄', anchor='w').grid(row=5,
                                                           column=0,
                                                           sticky='W')
        tk.Label(window, text='組態檔', anchor='w').grid(row=8,
                                                      column=0,
                                                      sticky='W')

        # 選擇日期的欄位
        initdate = StringVar()
        initdate.set(datetime.datetime.now().strftime("%Y%m%d"))
        dp = datepicker.Datepicker(window,
                                   dateformat="%Y%m%d",
                                   datevar=initdate,
                                   entrywidth='100')
        dp.grid(row=3, column=1, sticky='w')

        # 選擇檔案的欄位
        fileedit = tk.Entry(window, width='200')
        fileedit.grid(row=4, column=1, sticky='W', columnspan=2)
        fileedit.bind('<Button-1>', self.popcsvdialog)

        # 選擇存放匯出檔案的地方
        diredit = tk.Entry(window, width='200')
        diredit.grid(row=5, column=1, sticky='W', columnspan=2)
        diredit.bind('<Button-1>', self.popdirdialog)

        # 取消按鈕
        cancelbtn = tk.Button(window, text='離開', command=window.destroy)
        cancelbtn.grid(row=6, column=1, sticky='E')

        # 確定轉換的按鈕
        convbtn = tk.Button(window, text="執行轉檔", command=self.execonv)
        convbtn.grid(row=6, column=2, sticky='E')

        # logwindow
        logtext = tk.scrolledtext.ScrolledText(window)
        logtext.config(state='disable')
        logtext.grid(row=7, column=0, columnspan=4)

        # 選擇檔案的欄位
        iniedit = tk.Entry(window, width='200')
        iniedit.grid(row=8, column=1, sticky='W', columnspan=2)
        iniedit.bind('<Button-1>', self.popinidialog)
Example #40
0
def launch_GUI():
    root = Tk()
    root.configure(background='white')
    root.geometry("1183x502")
    root.title("eigenfaces demo")

    ala = font.Font(family="Symbol", size=13)

    label_1 = Label(root, text="Training set:", font=ala, bg='white')
    status_1_message = StringVar()
    status_1 = Entry(root,
                     relief=RIDGE,
                     font=ala,
                     textvariable=status_1_message,
                     width=90)
    status_1.insert(0, default_path_1)
    status_1.config(state='readonly')

    label_2 = Label(root, text="Testing image:", font=ala, bg='white')
    status_2_message = StringVar()
    status_2 = Entry(root,
                     relief=RIDGE,
                     font=ala,
                     textvariable=status_2_message,
                     width=90)
    status_2.insert(0, default_path_2)
    status_2.config(state='readonly')

    search_button_1 = Button(root,
                             text="Browse",
                             command=lambda ar=status_1: browse(ar, False))
    search_button_2 = Button(root,
                             text="Browse",
                             command=lambda ar=status_2: browse(ar, True))

    label_3 = Label(root,
                    text="Part of Training Set for Eigenfaces:",
                    font=ala,
                    bg='white')
    rate_field = Entry(root, relief=RIDGE, font=ala, width=3)
    rate_field.insert(0, "1")

    label_4 = Label(root, text="Answer:", font=ala, bg='white')
    verdict_message = StringVar()
    verdict_field = Entry(root,
                          relief=RIDGE,
                          font=ala,
                          textvariable=verdict_message,
                          width=90)
    verdict_field.config(state='readonly')

    go_button = Button(
        root,
        text="Start",
        command=lambda ar=rate_field, ar0=verdict_field, ar1=status_1_message,
        ar2=status_2_message: go_event(ar, ar0, ar1, ar2))

    test_button = Button(root,
                         text="Show Test",
                         command=lambda arg="test": go_vis(arg))
    mean_button = Button(root,
                         text="Show Mean",
                         command=lambda arg="mean": go_vis(arg))
    eigen_button = Button(root,
                          text="Show Eigenfaces",
                          command=lambda arg="eigen": go_vis(arg))
    build_button = Button(root,
                          text="Build Face",
                          command=lambda arg="build": go_vis(arg))

    label_1.grid(row=0, column=0, sticky="NESW", pady=4, padx=4)
    status_1.grid(row=1, column=0, sticky="NESW", pady=4, padx=4)
    search_button_1.grid(row=1, column=1, sticky="NESW", pady=4, padx=4)

    label_2.grid(row=2, column=0, sticky="NESW", pady=4, padx=4)
    status_2.grid(row=3, column=0, sticky="NESW", pady=4, padx=4)
    search_button_2.grid(row=3, column=1, sticky="NESW", pady=4, padx=4)

    label_3.grid(row=4, column=0, sticky="NESW", pady=4, padx=4)
    rate_field.grid(row=4, column=1, pady=4, padx=4)

    label_4.grid(row=5, column=0, sticky="NESW", pady=4, padx=4)
    go_button.grid(row=6, column=1, sticky="NESW", pady=4, padx=4)
    verdict_field.grid(row=6, column=0, sticky="NESW", pady=4, padx=4)

    test_button.grid(row=7, column=1, sticky="NESW", pady=4, padx=4)
    mean_button.grid(row=8, column=1, sticky="NESW", pady=4, padx=4)
    eigen_button.grid(row=10, column=1, sticky="NESW", pady=4, padx=4)
    build_button.grid(row=11, column=1, sticky="NESW", pady=4, padx=4)

    root.mainloop()
Example #41
0
def main():

    bot = Tk()
    bot.title('telegram bot')
    bot.geometry("500x200")

    # string var
    st = StringVar()
    img = StringVar()
    btex = StringVar()
    burl = StringVar()
    tim = StringVar()
    st.set('please submit details..')

    image = Label(bot, text='image location')
    image.grid(row=0, column=0, padx=5, pady=5)
    image_loc = Entry(bot, textvariable=img)
    image_loc.grid(row=0, column=1, padx=5, pady=5)

    button = Label(bot, text='button text')
    button.grid(row=1, column=0, padx=5, pady=5)
    button_text = Entry(bot, textvariable=btex)
    button_text.grid(row=1, column=1, padx=5, pady=5)

    button_u = Label(bot, text='button url')
    button_u.grid(row=2, column=0, padx=5, pady=5)
    button_url = Entry(bot, textvariable=burl)
    button_url.grid(row=2, column=1, padx=5, pady=5)

    time = Label(bot, text='time')
    time.grid(row=3, column=0, padx=5, pady=5)
    time_mint = Entry(bot, textvariable=tim)
    time_mint.grid(row=3, column=1, padx=5, pady=5)

    submit_add = Button(
        bot,
        text="Submit add",
        width=10,
        command=lambda: start_add_fun(st, img, burl, btex, tim, status))
    submit_add.grid(row=5, column=1, padx=10, pady=10)

    status = Label(bot, textvariable=st, bg='blue', fg='white')
    status.grid(row=0, column=4, padx=0, pady=5)

    delete_add = Button(
        bot,
        text="Delete add",
        width=10,
        command=lambda: delete_add_fun(st, img, burl, btex, tim, status))
    delete_add.grid(row=1, column=4, padx=10, pady=10)

    lab = Label(bot, text='Status:-')
    lab.grid(row=0, column=3, padx=20, pady=5)

    txt = Label(bot, text='text')
    txt.grid(row=0, column=4, padx=0, pady=5)

    text = Text(
        bot,
        width=10,
        command=lambda: delete_add_fun(st, img, burl, btex, tim, status))
    text.grid(row=1, column=4, padx=10, pady=10)
    bot.mainloop()
Example #42
0
    def create_widgets(self):
        self.create_fonts()
        self.create_variables()

        # Global is_playing as it is used as a boolean and StringVar
        global is_playing
        is_playing = StringVar()
        is_playing.set("▶")

        # Create Ticker Label for Ticker
        self.ticker_id = tk.Label(self,
                                  textvariable=self.ticker_value,
                                  fg=config.color_white,
                                  bg=config.background_color,
                                  font=self.font_large).grid(row=0,
                                                             column=0,
                                                             columnspan=4,
                                                             padx=33,
                                                             sticky="nsew")

        # Create a label to show the last price
        self.last_price_label = tk.Label(self,
                                         textvariable=self.last_price_value,
                                         bg=config.background_color,
                                         fg=config.color_white,
                                         font=self.font_large).grid(
                                             row=1,
                                             column=0,
                                             columnspan=4,
                                             sticky="nsew")

        # Create a button to start the reply
        self.play_button = tk.Button(self,
                                     textvariable=is_playing,
                                     bg=config.button_color_light,
                                     fg=config.color_grey,
                                     borderwidth=0)

        self.play_button["command"] = self.play_replay
        self.play_button.grid(row=2, column=0, columnspan=2, sticky="nsew")

        # Create a button for progressing to next bar
        self.next_button = tk.Button(self,
                                     text="▮▶",
                                     bg=config.button_color_light,
                                     fg=config.color_grey,
                                     borderwidth=0)
        self.next_button["command"] = self.next_bar
        self.next_button.grid(row=2, column=2, columnspan=2, sticky="nsew")

        # Create a button for long orders
        self.long_button = tk.Button(self,
                                     text="BUY",
                                     font=self.font,
                                     bg=config.button_color,
                                     fg=config.color_green,
                                     borderwidth=0)
        self.long_button["command"] = self.order_buy
        self.long_button.grid(row=3, column=0, columnspan=2, sticky="nsew")

        # Create a button for short orders
        self.short_button = tk.Button(self,
                                      text="SELL",
                                      font=self.font,
                                      bg=config.button_color,
                                      fg=config.color_red,
                                      borderwidth=0)
        self.short_button["command"] = self.order_sell
        self.short_button.grid(row=3, column=2, columnspan=2, sticky="nsew")

        # Create radio buttons to toggle between limit orders and market orders
        self.limit_radiobutton = tk.Radiobutton(
            self,
            bg=config.background_color,
            fg=config.color_dark_grey,
            selectcolor=config.background_color,
            text="LIMIT",
            variable=self.order_type,
            value="limit")
        self.limit_radiobutton.grid(row=4,
                                    column=0,
                                    columnspan=2,
                                    sticky="nsew")

        self.market_radiobutton = tk.Radiobutton(
            self,
            bg=config.background_color,
            fg=config.color_dark_grey,
            selectcolor=config.background_color,
            text="MARKET",
            variable=self.order_type,
            value="market",
        ).grid(row=4, column=2, columnspan=2, sticky="nsew")

        # Create entry box for limit orders
        self.limit_price = tk.Entry(self,
                                    borderwidth=0,
                                    bg=config.button_color_light,
                                    fg=config.color_grey)
        self.limit_price.insert(0, " ")
        self.limit_price.grid(row=5,
                              column=0,
                              columnspan=3,
                              sticky="nsew",
                              padx=5)

        self.limit_copy_button = tk.Button(self,
                                           text="LAST",
                                           borderwidth=0,
                                           bg=config.button_color,
                                           fg=config.color_grey,
                                           font=self.font_small)
        self.limit_copy_button["command"] = self.copy_last
        self.limit_copy_button.grid(row=5,
                                    column=3,
                                    columnspan=1,
                                    sticky="nsew")

        self.current_position_label = tk.Label(self,
                                               text="Current Position",
                                               anchor="w",
                                               bg=config.background_color,
                                               fg=config.color_grey,
                                               font=self.font_small).grid(
                                                   row=6,
                                                   column=0,
                                                   columnspan=4,
                                                   sticky="nsew")

        self.current_position_value_label = tk.Label(
            self,
            textvariable=self.current_position_value,
            anchor="w",
            bg=config.button_color_light,
            fg=config.color_dark_grey).grid(row=7,
                                            column=0,
                                            columnspan=3,
                                            sticky="nsew")

        self.current_position_pnl_label = tk.Label(
            self,
            textvariable=self.current_position_pnl,
            anchor="e",
            bg=config.button_color_light,
            fg=config.color_dark_grey).grid(row=7,
                                            column=3,
                                            columnspan=1,
                                            sticky="nsew")

        self.account_value_label = tk.Label(self,
                                            text="Account value",
                                            anchor="w",
                                            bg=config.background_color,
                                            fg=config.color_grey,
                                            font=self.font_small).grid(
                                                row=8,
                                                column=0,
                                                columnspan=4,
                                                sticky="nsew")

        self.account_value_value_label = tk.Label(
            self,
            textvariable=self.account_value_text,
            bg=config.button_color_light,
            fg=config.color_white,
            anchor="w").grid(row=9, column=0, columnspan=3, sticky="nsew")

        self.account_value_pnl_label = tk.Label(
            self,
            textvariable=self.account_value_pnl,
            bg=config.button_color_light,
            fg=config.color_dark_grey,
            anchor="e").grid(row=9, column=3, columnspan=1, sticky="nsew")

        self.trade_history_label = tk.Label(self,
                                            text="Trades",
                                            anchor="w",
                                            bg=config.background_color,
                                            fg=config.color_grey,
                                            font=self.font_small).grid(
                                                row=10,
                                                column=0,
                                                columnspan=3,
                                                sticky="nsew")

        self.trade_history_clear = tk.Button(self,
                                             text="Clear",
                                             bg=config.button_color,
                                             fg=config.color_grey,
                                             font=self.font_small,
                                             borderwidth=0)
        self.trade_history_clear.grid(row=10,
                                      column=3,
                                      columnspan=1,
                                      sticky="nsew")
        self.trade_history_clear['command'] = self.clear_list

        self.trade_history_list = tk.Listbox(self,
                                             fg=config.color_grey,
                                             bg=config.textarea_color,
                                             borderwidth=0)
        self.trade_history_list.grid(row=11,
                                     column=0,
                                     columnspan=4,
                                     sticky="nsew")
Example #43
0
    def __init__(self, master):
        self.master = master
        self.master.title("Titanic Survival")
        self.master.geometry("300x350")
        self.master.resizable(False, False)
        self.filename = ""
        model_filename = 'models/MLPClassifier30798.sav'
        self.loadedmodel = pickle.load(open(model_filename, 'rb'))
        self.importeddf = ""
        self.predictions = ""

        self.nameleb = Label(self.master, text="Enter name")
        self.nameleb.pack()

        self.nametext = Text(self.master, height=1)
        self.nametext.pack()

        self.ageleb = Label(self.master, text="Enter age")
        self.ageleb.pack()

        self.agetext = Text(self.master, height=1, width=3)
        self.agetext.pack()

        self.nofsiblleb = Label(self.master,
                                text="Enter the number of Siblings/Spouses")
        self.nofsiblleb.pack()

        self.nofparentstext = Text(self.master, height=1, width=3)
        self.nofparentstext.pack()

        self.noffammebleb = Label(self.master,
                                  text="Enter the number of Parents/Children")
        self.noffammebleb.pack()

        self.noffammebtext = Text(self.master, height=1, width=3)
        self.noffammebtext.pack()

        self.fareleb = Label(self.master, text="Enter fare")
        self.fareleb.pack()

        self.faretext = Text(self.master, height=1, width=7)
        self.faretext.pack()

        self.sexlist = ["Male", "Female"]
        self.sexstring = StringVar(master)
        self.sexstring.set("Select a Sex")
        self.sexpopup = OptionMenu(self.master, self.sexstring, *self.sexlist)
        self.sexpopup.pack()

        self.pclasslist = ["1st", "2nd", '3rd']
        self.pclassstring = StringVar(master)
        self.pclassstring.set("Select a Ticket class")
        self.pclasspopup = OptionMenu(self.master, self.pclassstring,
                                      *self.pclasslist)
        self.pclasspopup.pack()

        self.embarkedlist = ["C", "Q", "S"]
        self.embarkedstring = StringVar(master)
        self.embarkedstring.set("Select a Port of Embarkation")
        self.embarkedpopup = OptionMenu(self.master, self.embarkedstring,
                                        *self.embarkedlist)
        self.embarkedpopup.pack()

        self.predictbutton = Button(self.master,
                                    text="PREDICT",
                                    command=self.predict)
        self.predictbutton.pack()

        self.clearbutton = Button(self.master,
                                  text="CLEAR",
                                  command=self.clear)
        self.clearbutton.pack()

        self.menu = Menu(self.master)

        self.file_menu = Menu(self.menu, tearoff=0)
        self.file_menu.add_command(label="Insert a csv",
                                   accelerator='Ctrl+O',
                                   command=self.insertfile)
        self.file_menu.add_command(label="Close file",
                                   accelerator='Ctrl+F4',
                                   command=self.closefile)
        self.file_menu.add_command(label="Save file",
                                   accelerator='Ctrl+S',
                                   command=self.savepredictions)
        self.file_menu.add_command(label="Save to existed file",
                                   accelerator='Alt+S',
                                   command=self.savetoexisted)
        self.file_menu.add_command(label="Exit",
                                   accelerator='Alt+F4',
                                   command=self.exitmenu)
        self.menu.add_cascade(label="File", menu=self.file_menu)

        self.show_menu = Menu(self.menu, tearoff=0)
        self.show_menu.add_command(label="Show Predictions",
                                   accelerator='Ctrl+ F5',
                                   command=self.showpredictions)
        self.menu.add_cascade(label="Show", menu=self.show_menu)

        self.edit_menu = Menu(self.menu, tearoff=0)
        self.edit_menu.add_command(label="Clear All",
                                   accelerator='Ctrl+Z',
                                   command=self.clear)
        self.submenuclear = Menu(self.edit_menu, tearoff=0)
        self.submenuclear.add_command(
            label="Name",
            accelerator="Ctrl+T",
            command=lambda: self.clear(self.nametext))
        self.submenuclear.add_command(label="Age",
                                      accelerator="Alt+T",
                                      command=lambda: self.clear(self.agetext))
        self.submenuclear.add_command(
            label="Siblings/Spouses",
            accelerator="Alt+N",
            command=lambda: self.clear(self.noffammebtext))
        self.submenuclear.add_command(
            label="Parents/Children",
            accelerator="Ctrl+N",
            command=lambda: self.clear(self.nofparentstext))
        self.submenuclear.add_command(
            label="Fare",
            accelerator="Alt+Z",
            command=lambda: self.clear(self.faretext))
        self.edit_menu.add_cascade(label="Clear text",
                                   menu=self.submenuclear,
                                   underline=0)
        self.submenureset = Menu(self.edit_menu, tearoff=0)
        self.submenureset.add_command(
            label="Sex",
            accelerator="Alt+M",
            command=lambda: self.clear(
                toclear=self.sexstring, textflag=False, text="Select a Sex"))
        self.submenureset.add_command(
            label="Ticket class",
            accelerator="Ctrl+M",
            command=lambda: self.clear(toclear=self.pclassstring,
                                       textflag=False,
                                       text="Select a Ticket class"))
        self.submenureset.add_command(
            label="Embarkation",
            accelerator="Ctrl+K",
            command=lambda: self.clear(toclear=self.embarkedstring,
                                       textflag=False,
                                       text="Select a Port of Embarkation"))
        self.edit_menu.add_cascade(label="Reset Options",
                                   menu=self.submenureset,
                                   underline=0)
        self.menu.add_cascade(label="Edit", menu=self.edit_menu)

        self.about_menu = Menu(self.menu, tearoff=0)
        self.about_menu.add_command(label="About",
                                    accelerator='Ctrl+I',
                                    command=aboutmenu)
        self.menu.add_cascade(label="About", menu=self.about_menu)

        self.help_menu = Menu(self.menu, tearoff=0)
        self.help_menu.add_command(label="Help",
                                   accelerator='Ctrl+F1',
                                   command=helpmenu)
        self.menu.add_cascade(label="Help", menu=self.help_menu)

        self.master.config(menu=self.menu)
        self.master.bind('<Control-F5>', lambda event: self.showpredictions())
        self.master.bind('<Control-z>', lambda event: self.clear(None))
        self.master.bind('<Alt-F4>', lambda event: self.exitmenu())
        self.master.bind('<Control-F1>', lambda event: helpmenu())
        self.master.bind('<Control-i>', lambda event: aboutmenu())
        self.master.bind('<Control-o>', lambda event: self.insertfile())
        self.master.bind('<Control-F4>', lambda evemt: self.closefile())
        self.master.bind('<Control-t>',
                         lambda event: self.clear(self.nametext))
        self.master.bind('<Alt-t>', lambda event: self.clear(self.agetext))
        self.master.bind('<Alt-z>', lambda event: self.clear(self.faretext))
        self.master.bind('<Alt-n>',
                         lambda event: self.clear(self.nofparentstext))
        self.master.bind('<Control-n>',
                         lambda event: self.clear(self.noffammebtext))
        self.master.bind(
            '<Control-m>',
            lambda event: self.clear(toclear=self.pclassstring,
                                     textflag=False,
                                     text="Select a Ticket class"))
        self.master.bind(
            '<Alt-m>', lambda event: self.clear(
                toclear=self.sexstring, textflag=False, text="Select a Sex"))
        self.master.bind(
            '<Control-k>',
            lambda event: self.clear(toclear=self.embarkedstring,
                                     textflag=False,
                                     text="Select a Port of Embarkation"))
Example #44
0
 def create_variables(self):
     # Set up StringVars that will be used.
     self.ticker_value = StringVar()
     self.account_value_text = StringVar()
     self.account_value_text.set(str(account_value))
     self.last_price_value = StringVar()
     self.current_position_value = StringVar()
     self.current_position_pnl = StringVar()
     self.account_value_pnl = StringVar()
     self.limit_price = StringVar()
     self.order_type = StringVar(None, 'market')
Example #45
0
# from tkinter import *
import webbrowser
import sqlite3
from tkinter import Button, Entry, IntVar, Label, OptionMenu, Radiobutton, StringVar, Tk, Toplevel

root = Tk()
root.geometry('640x600')
root.title("Exam Registration Form")
conn = sqlite3.connect('Registration.db')

firstN = StringVar()
lastN = StringVar()
gender = StringVar()
DOB = StringVar()
add1 = StringVar()
add2 = StringVar()
city = StringVar()
pincode = IntVar()
state = StringVar()
country = StringVar()
email = StringVar()
category = StringVar()
nationality = StringVar()


def isVerified():
    print("Inside Verified")
    if firstN.get() == "" or gender.get() == "" or add1.get() == "" or DOB.get(
    ) == "" or city.get() == "" or pincode.get() == 0 or state.get(
    ) == "" or email.get() == "" or category.get() == "" or nationality.get(
    ) == "" or country.get() == "Please Select":
Example #46
0
	def __init__(self, root):
		self.root = root
		self.root.title("Library System")
		self.root.geometry('1350x750+0+0')
		self.root.config(background="powder blue")

		#==============VARIABLES===========================================================================================

		MType = StringVar()
		Ref = StringVar()
		Title = StringVar()
		FirstName = StringVar()
		Surname = StringVar()
		Address1 = StringVar()
		Address2 = StringVar()
		PostCode = StringVar()
		MobileNo = StringVar()
		BookID = StringVar()
		BookTitle = StringVar()
		BookType = StringVar()
		Author = StringVar()
		DateBorrowed = StringVar()
		DateDue = StringVar()
		SellingPrice = StringVar()
		LateReturnFine = StringVar()
		DateOverDue = StringVar()
		DaysOnLoan = StringVar()
		Prescription = StringVar()

		#==============FUNCTIONS=======================================================================================
		def iExit():
			qExit = messagebox.askyesno("Inventory System", "Do you want to EXIT the system")
			if qExit  == 1:
				root.destroy()
				return

		def Reset():
			MType.set("")
			Ref.set("")
			Title.set("")
			FirstName.set("")
			Surname.set("")
			Address1.set("")
			Address2.set("")
			PostCode.set("")
			MobileNo.set("")
			BookID.set("")
			BookTitle.set("")
			BookType.set("")
			Author.set("")
			DateBorrowed.set("")
			DateDue.set("")
			SellingPrice.set("")
			LateReturnFine.set("")
			DateOverDue.set("")
			DaysOnLoan.set("")
			Prescription.set("")
			self.txtDisplay.delete("1.0", END)
			self.txtDetail.delete("1.0", END)

		def iDelete():
			Reset()
			self.txtDisplay.delete("1.0", END)

		def iDisplayData():
			self.txtDetail.insert(END, "\t" +MType.get()+ "\t" +Ref.get()+ "\t" +Title.get()+ "\t" +FirstName.get()+ "\t" +Surname.get()+ "\t" +Address1.get()+ "\t" +Address2.get()+ "\t" +PostCode.get()+ "\t" +MobileNo.get()+ "\t" +BookID.get()+ "\t" +BookTitle.get()+ "\t" +BookType.get()+ "\t" +Author.get()+ "\t" +DateBorrowed.get()+ "\t" +SellingPrice.get()+ "\t" +LateReturnFine.get() + "\t" +DateOverDue.get()+ "\t" +DaysOnLoan.get()+ "\t" +Prescription.get() + "\n")

		def iReceipt():
			self.txtDisplay.insert(END, ' Member Type:\t\t\t\t' + MType.get()+ "\n")
			self.txtDisplay.insert(END, ' Ref No:\t\t\t\t' + Ref.get() + "\n")
			self.txtDisplay.insert(END, ' Title:\t\t\t\t' + Title.get() + "\n")
			self.txtDisplay.insert(END, ' First Name:\t\t\t\t' + FirstName.get() + "\n")
			self.txtDisplay.insert(END, ' Surname:\t\t\t\t' + Surname.get() + "\n")
			self.txtDisplay.insert(END, ' Address 1:\t\t\t\t' + Address1.get() + "\n")
			self.txtDisplay.insert(END, ' Address 2:\t\t\t\t' + Address2.get() + "\n")
			self.txtDisplay.insert(END, ' PostCode:\t\t\t\t' + PostCode.get() + "\n")
			self.txtDisplay.insert(END, ' Mobile No:\t\t\t\t' + MobileNo.get() + "\n")
			self.txtDisplay.insert(END, ' Book ID:\t\t\t\t' + BookID.get() + "\n")
			self.txtDisplay.insert(END, ' BookTitle:\t\t\t\t' + BookTitle.get() + "\n")
			self.txtDisplay.insert(END, ' BookType:\t\t\t\t' + BookType.get() + "\n")
			self.txtDisplay.insert(END, ' Author:\t\t\t\t' + Author.get() + "\n")
			self.txtDisplay.insert(END, ' Date Borrowed:\t\t\t\t' + DateBorrowed.get() + "\n")
			self.txtDisplay.insert(END, ' Selling Price:\t\t\t\t' + SellingPrice.get() + "\n")
			self.txtDisplay.insert(END, ' Late Return Fine:\t\t\t\t' + LateReturnFine.get() + "\n")
			self.txtDisplay.insert(END, ' Date Over Due:\t\t\t\t' + DateOverDue.get() + "\n")
			self.txtDisplay.insert(END, ' Days On Loan:\t\t\t\t' + DaysOnLoan.get() + "\n")
			self.txtDisplay.insert(END, ' Number of Days:\t\t\t\t' + Prescription.get() + "\n")

		def SelectedBook(evt):
			value= str(Booklist.get(Booklist.curselection()))
			w = value

 		#','', ''

			if (w== 'Cinderella'):
				BookID.set("ISBN 78945213")
				BookTitle.set("Cinderella")
				Author.set("Peter Parker")
				SellingPrice.set("R99.99")
				LateReturnFine.set("R30")
				DaysOnLoan.set("14")
				iReceipt()
				d1 = date.today()
				d2 = timedelta(days= 14)
				d3 = (d1 + d2)
				DateBorrowed.set(d1)
				DateDue.set(d3)
				DateOverDue.set("No")

			elif (w== 'Game Design'):
				BookID.set("ISBN 78961313")
				BookTitle.set("Cinderella")
				Author.set("Bob Jones")
				SellingPrice.set("R89.99")
				LateReturnFine.set("R35")
				DaysOnLoan.set("14")
				iReceipt()
				d1 = date.today()
				d2 = timedelta(days= 14)
				d3 = (d1 + d2)
				DateBorrowed.set(d1)
				DateDue.set(d3)
				DateOverDue.set("No")

			elif (w== 'Ancient Rome'):
				BookID.set("ISBN 21961913")
				BookTitle.set("Ancient Rome")
				Author.set("Ken James")
				SellingPrice.set("R109.99")
				LateReturnFine.set("R45")
				DaysOnLoan.set("14")
				iReceipt()
				d1 = date.today()
				d2 = timedelta(days= 14)
				d3 = (d1 + d2)
				DateBorrowed.set(d1)
				DateDue.set(d3)
				DateOverDue.set("No")

			elif (w== 'Made In Africa'):
				BookID.set("ISBN 21961913")
				BookTitle.set("Made In Africa")
				Author.set("Sipho Zulu")
				SellingPrice.set("R79.99")
				LateReturnFine.set("R25")
				DaysOnLoan.set("14")
				iReceipt()
				d1 = date.today()
				d2 = timedelta(days= 14)
				d3 = (d1 + d2)
				DateBorrowed.set(d1)
				DateDue.set(d3)
				DateOverDue.set("No")

			elif (w== 'Sleeping Beauty'):
				BookID.set("ISBN 21961913")
				BookTitle.set("Sleeping Beauty")
				Author.set("Thomas King")
				SellingPrice.set("R69.99")
				LateReturnFine.set("R25")
				DaysOnLoan.set("14")
				iReceipt()
				d1 = date.today()
				d2 = timedelta(days= 14)
				d3 = (d1 + d2)
				DateBorrowed.set(d1)
				DateDue.set(d3)
				DateOverDue.set("No")

			elif (w== 'London'):
				BookID.set("ISBN 91364923")
				BookTitle.set("London")
				Author.set("James Cameron")
				SellingPrice.set("R99.99")
				LateReturnFine.set("R30")
				DaysOnLoan.set("14")
				iReceipt()
				d1 = date.today()
				d2 = timedelta(days= 14)
				d3 = (d1 + d2)
				DateBorrowed.set(d1)
				DateDue.set(d3)
				DateOverDue.set("No")

			elif (w== 'Nigeria'):
				BookID.set("ISBN 83346921")
				BookTitle.set("Nigeria")
				Author.set("Sam Smith")
				SellingPrice.set("R109.99")
				LateReturnFine.set("R35")
				DaysOnLoan.set("14")
				iReceipt()
				d1 = date.today()
				d2 = timedelta(days= 14)
				d3 = (d1 + d2)
				DateBorrowed.set(d1)
				DateDue.set(d3)
				DateOverDue.set("No")

			elif (w== 'Snow White'):
				BookID.set("ISBN 734429241")
				BookTitle.set("Snow White")
				Author.set("Adele")
				SellingPrice.set("R79.99")
				LateReturnFine.set("R25")
				DaysOnLoan.set("14")
				iReceipt()
				d1 = date.today()
				d2 = timedelta(days= 14)
				d3 = (d1 + d2)
				DateBorrowed.set(d1)
				DateDue.set(d3)
				DateOverDue.set("No")

			elif (w== 'Shrek 3'):
				BookID.set("ISBN 331426241")
				BookTitle.set("Shrek 3")
				Author.set("Bob Marley")
				SellingPrice.set("R89.99")
				LateReturnFine.set("R30")
				DaysOnLoan.set("14")
				iReceipt()
				d1 = date.today()
				d2 = timedelta(days= 14)
				d3 = (d1 + d2)
				DateBorrowed.set(d1)
				DateDue.set(d3)
				DateOverDue.set("No")

			elif (w== 'I Love Lagos'):
				BookID.set("ISBN 637423251")
				BookTitle.set("I Love Lagos")
				Author.set("Fella Kuti")
				SellingPrice.set("R129.99")
				LateReturnFine.set("R50")
				DaysOnLoan.set("14")
				iReceipt()
				d1 = date.today()
				d2 = timedelta(days= 14)
				d3 = (d1 + d2)
				DateBorrowed.set(d1)
				DateDue.set(d3)
				DateOverDue.set("No")

			elif (w== 'I Love Kenya'):
				BookID.set("ISBN 126823251")
				BookTitle.set("I Love Kenya")
				Author.set("K'naan")
				SellingPrice.set("R79.99")
				LateReturnFine.set("R20")
				DaysOnLoan.set("14")
				iReceipt()
				d1 = date.today()
				d2 = timedelta(days= 14)
				d3 = (d1 + d2)
				DateBorrowed.set(d1)
				DateDue.set(d3)
				DateOverDue.set("No")

			elif (w== 'I love Mzansi'):
				BookID.set("ISBN 469832168")
				BookTitle.set("I love Mzansi")
				Author.set("Fella Kuti")
				SellingPrice.set("R159.99")
				LateReturnFine.set("R100")
				DaysOnLoan.set("14")
				iReceipt()
				d1 = date.today()
				d2 = timedelta(days= 14)
				d3 = (d1 + d2)
				DateBorrowed.set(d1)
				DateDue.set(d3)
				DateOverDue.set("No")



		#=============FRAMES==========================================================================
		MainFrame =Frame(self.root)
		MainFrame.grid()

		TitleFrame = Frame(MainFrame, width=1350, padx=10,bd=20, relief=RIDGE)
		TitleFrame.grid(row=0, column=0,sticky= W)

		self.lblTitle = Label(TitleFrame, justify="center", width=37, text="\tLibrary Manangement System\t", font=('arial', 40, 'bold'), padx=12)
		self.lblTitle.grid(row=0, column=0)


		ButtonFrame = Frame(MainFrame, bd=10, width=1350, height=50, relief=RIDGE)
		ButtonFrame.grid(row=3, column=0, sticky=W)

		DetailFrame = Frame(MainFrame, bd=10, width=1350, height=100, relief=RIDGE)
		DetailFrame.grid(row=2, column=0, sticky=W)

		DataFrame = Frame(MainFrame, bd=10, width=1300, height=400,  padx=5,relief=RIDGE)
		DataFrame.grid(row=1, column=0, sticky= W)

		DataFrameLEFT = LabelFrame(DataFrame, font=('arial', 18, 'bold'), text="Library Membership Info:", bd=10, width=800, height=300, relief=RIDGE)
		DataFrameLEFT.grid(row=0, column=0)

		DataFrameRIGHT = LabelFrame(DataFrame, font=('arial', 18, 'bold'), text="Book Details:", bd=10, width=450, height=300, relief=RIDGE)
		DataFrameRIGHT.grid(row=0, column=1)
		#===================Dispaly======================================================================================
		self.txtDisplay = Text(DataFrameRIGHT, bg="cyan", height=13, width=30, padx=8, pady=20, font=('arial', 12, 'bold'))
		self.txtDisplay.grid(row=0, column=2)


		#==================LISTBOX=============================================================
		scrollbar = Scrollbar(DataFrameRIGHT)
		scrollbar.grid(row=0, column=1, sticky="ns")

		ListOfBooks = ['Cinderella','Game Design', 'Ancient Rome','Made In Africa','Sleeping Beauty','London', 'Nigeria','Snow White', 'Shrek 3', 'I Love Lagos','I Love Kenya', 'I love Mzansi', 'Cinderella','Game Design', 'ancient Rome','Made In Africa','Sleeping Beauty','London']

		Booklist = Listbox(DataFrameRIGHT, width=20, height=12,  font=('arial', 12, 'bold'))
		Booklist.bind("<<ListboxSelect>>", SelectedBook)
		Booklist.grid(row=0, column=0, padx=8)
		scrollbar.config(command=Booklist.yview)

		for items in ListOfBooks:
			Booklist.insert(END, items)

		#==================LISTBOX=============================================================
		self.lblTitle = Label(DetailFrame, text="Member Type\tReference No.\tTitle\tFirstName\tSurname\tAddress 1\tAddress 2\tPostCode\tBook Title\tDate Borrowed\tDays On Loan", font=('arial', 10, 'bold'), pady=8)
		self.lblTitle.grid(row=0, column=0)

		self.txtDetail = Text(DetailFrame, bg="cyan", height=5, width=140, pady=4, font=('arial', 12, 'bold'))
		self.txtDetail.grid(row=1, column=0)


		#===================WIDGETS======================================================================================
		self.lblMemberType = Label(DataFrameLEFT, text="Member Type:", font=('arial', 12, 'bold'), padx=2, pady=5)
		self.lblMemberType.grid(row=0, column=0)
		self.cboMemberType = ttk.Combobox(DataFrameLEFT, textvariable=MType, font=('arial', 12, 'bold'), width=23, state='readonly')
		self.cboMemberType['value'] = ('', 'Student', 'Lecturer', 'Admin Staff')
		self.cboMemberType.current(0)
		self.cboMemberType.grid(row=0, column=1, sticky= W)

		self.lblBookID = Label(DataFrameLEFT, text="Book ID:", font=('arial', 12, 'bold'), padx=2, pady=5)
		self.lblBookID.grid(row=0, column=2, sticky= W)
		self.txtBookID = Entry(DataFrameLEFT, textvariable=BookID, font=('arial', 12, 'bold'), width=25)
		self.txtBookID.grid(row=0, column=3)

		self.lblRef = Label(DataFrameLEFT, text="Reference No:", font=('arial', 12, 'bold'), padx=2, pady=5)
		self.lblRef.grid(row=1, column=0, sticky= W)
		self.txtRef = Entry(DataFrameLEFT, textvariable=Ref, font=('arial', 12, 'bold'), width=25)
		self.txtRef.grid(row=1, column=1)

		self.lblBookTitle = Label(DataFrameLEFT, text="Book Title:", font=('arial', 12, 'bold'), padx=2, pady=5)
		self.lblBookTitle.grid(row=1, column=2, sticky= W)
		self.txtBookTitle = Entry(DataFrameLEFT, textvariable=BookTitle, font=('arial', 12, 'bold'), width=25)
		self.txtBookTitle.grid(row=1, column=3)

		self.lblTitle = Label(DataFrameLEFT, text="Title:", font=('arial', 12, 'bold'), padx=2, pady=5)
		self.lblTitle.grid(row=2, column=0, sticky= W)
		self.cboTitle = ttk.Combobox(DataFrameLEFT, textvariable=Title, font=('arial', 12, 'bold'), width=23, state='readonly')
		self.cboTitle['value'] = ('', 'Mr', 'Miss', 'Mrs', 'Dr', 'Capt',)
		self.cboTitle.current(0)
		self.cboTitle.grid(row=2, column=1, sticky= W)

		self.lblAuthor = Label(DataFrameLEFT, text="Author:", font=('arial', 12, 'bold'), padx=2, pady=5)
		self.lblAuthor.grid(row=2, column=2, sticky= W)
		self.cboAuthor = Entry(DataFrameLEFT, textvariable=Author, font=('arial', 12, 'bold'), width=25)
		self.cboAuthor.grid(row=2, column=3)

		self.lblFirstName = Label(DataFrameLEFT, text="FirstName:", font=('arial', 12, 'bold'), padx=2, pady=5)
		self.lblFirstName.grid(row=3, column=0, sticky= W)
		self.txtFirstName = Entry(DataFrameLEFT, textvariable=FirstName, font=('arial', 12, 'bold'), width=25)
		self.txtFirstName.grid(row=3, column=1)

		self.lblDateBorrowed = Label(DataFrameLEFT, text="Reference No:", font=('arial', 12, 'bold'), padx=2, pady=5)
		self.lblDateBorrowed.grid(row=3, column=2, sticky= W)
		self.lblDateBorrowed = Entry(DataFrameLEFT, textvariable=DateBorrowed, font=('arial', 12, 'bold'), width=25)
		self.lblDateBorrowed.grid(row=3, column=3)

		self.lblSurName = Label(DataFrameLEFT, text="Surame:", font=('arial', 12, 'bold'), padx=2, pady=5)
		self.lblSurName.grid(row=4, column=0, sticky= W)
		self.txtSurName = Entry(DataFrameLEFT, textvariable=Surname, font=('arial', 12, 'bold'), width=25)
		self.txtSurName.grid(row=4, column=1)

		self.lblDateDue = Label(DataFrameLEFT, text="Due Date:", font=('arial', 12, 'bold'), padx=2, pady=5)
		self.lblDateDue.grid(row=4, column=2, sticky= W)
		self.txtDateDue = Entry(DataFrameLEFT, textvariable=DateDue, font=('arial', 12, 'bold'), width=25)
		self.txtDateDue.grid(row=4, column=3)

		self.lblAddress1 = Label(DataFrameLEFT, text="Address 1:", font=('arial', 12, 'bold'), padx=2, pady=5)
		self.lblAddress1.grid(row=5, column=0, sticky= W)
		self.txtAddress1 = Entry(DataFrameLEFT, textvariable=Address1, font=('arial', 12, 'bold'), width=25)
		self.txtAddress1.grid(row=5, column=1)

		self.lblDaysOnLoan = Label(DataFrameLEFT, text="Days On Loan:", font=('arial', 12, 'bold'), padx=2, pady=5)
		self.lblDaysOnLoan.grid(row=5, column=2, sticky= W)
		self.txtDaysOnLoan = Entry(DataFrameLEFT, textvariable=DaysOnLoan, font=('arial', 12, 'bold'), width=25)
		self.txtDaysOnLoan.grid(row=5, column=3)

		self.lblAddress2 = Label(DataFrameLEFT, text="Address 2:", font=('arial', 12, 'bold'), padx=2, pady=5)
		self.lblAddress2.grid(row=6, column=0, sticky= W)
		self.txtAddress2 = Entry(DataFrameLEFT, textvariable=Address2, font=('arial', 12, 'bold'), width=25)
		self.txtAddress2.grid(row=6, column=1)

		self.lblLateReturnFine = Label(DataFrameLEFT, text="Late Return Fine:", font=('arial', 12, 'bold'), padx=2, pady=5)
		self.lblLateReturnFine.grid(row=6, column=2, sticky= W)
		self.txtLateReturnFine = Entry(DataFrameLEFT, textvariable=LateReturnFine, font=('arial', 12, 'bold'), width=25)
		self.txtLateReturnFine.grid(row=6, column=3)

		self.lblPostCode = Label(DataFrameLEFT, text="Post Code:", font=('arial', 12, 'bold'), padx=2, pady=5)
		self.lblPostCode.grid(row=7, column=0, sticky= W)
		self.txtPostCode = Entry(DataFrameLEFT, textvariable=PostCode, font=('arial', 12, 'bold'), width=25)
		self.txtPostCode.grid(row=7, column=1)

		self.lblDateOverDue = Label(DataFrameLEFT, text="Date Over Due:", font=('arial', 12, 'bold'), padx=2, pady=5)
		self.lblDateOverDue.grid(row=7, column=2, sticky= W)
		self.txtDateOverDue = Entry(DataFrameLEFT, textvariable=DateOverDue, font=('arial', 12, 'bold'), width=25)
		self.txtDateOverDue.grid(row=7, column=3)

		self.lblMobileNo = Label(DataFrameLEFT, text="Mobile No:", font=('arial', 12, 'bold'), padx=2, pady=5)
		self.lblMobileNo.grid(row=8, column=0, sticky= W)
		self.txtMobileNo = Entry(DataFrameLEFT, textvariable=MobileNo, font=('arial', 12, 'bold'), width=25)
		self.txtMobileNo.grid(row=8, column=1)

		self.lblSellingPrice = Label(DataFrameLEFT, text="Selling Price:", font=('arial', 12, 'bold'), padx=2, pady=5)
		self.lblSellingPrice.grid(row=8, column=2, sticky= W)
		self.txtSellingPrice = Entry(DataFrameLEFT, textvariable=Prescription, font=('arial', 12, 'bold'), width=25)
		self.txtSellingPrice.grid(row=8, column=3)

		#==================BUTTONs===========================================================================
		self.btnDisplay = Button(ButtonFrame, bd=4, width=30,  font=('arial', 12, 'bold'), text="Display Data").grid(row=0, column=0)
		self.btnDelete = Button(ButtonFrame, command=iDelete, bd=4, width=30,  font=('arial', 12, 'bold'), text="Delete").grid(row=0, column=1)
		self.btnReset = Button(ButtonFrame,command=Reset, bd=4, width=30,  font=('arial', 12, 'bold'), text="Reset").grid(row=0, column=2)
		self.btnExit = Button(ButtonFrame, command=iExit, bd=4, width=30,  font=('arial', 12, 'bold'), text="Exit").grid(row=0, column=3)
Example #47
0
b2 = Button(window, text='添加', width=10, height=1, command=hit_b2)


def hit_b3():
    value = lb.get(lb.curselection())
    rlist.remove(value)
    var.set(rlist)  #重置目录
    #写删除后的文件
    with open('D:\python3.6.1\Zprogram3\day_done.txt', 'w') as f:
        for i in rlist:
            f.write(i + '\n')


b3 = Button(window, text='删除', width=10, height=1, command=hit_b3)

var = StringVar()
var.set(rlist)

lb = Listbox(window, listvariable=var)

#布局
l.pack()
b1.pack()
e.pack()
b2.pack()
b3.pack()
lb.pack()

window.mainloop()
Example #48
0
from tkinter import Tk, Label, Entry, Button, StringVar, IntVar

window = Tk()

name_array = [['a1', 'a2', 'a3'], ['b1', 'b2', 'b3'], ['c1', 'c2', 'c3'],
              ['d1', 'd2', 'd3']]
position_track = IntVar()

first_name = StringVar()
last_name = StringVar()
email = StringVar()


def return_value(pos):
    first_name.set(name_array[pos][0])
    last_name.set(name_array[pos][1])
    email.set(name_array[pos][2])


def update_value(pos):
    global name_array
    name_array[pos] = [first_name.get(), last_name.get(), email.get()]
    first_name.set(name_array[pos][0])
    last_name.set(name_array[pos][1])
    email.set(name_array[pos][2])


def first_value():
    global position_track
    return_value(0)
    position_track.set(0)
Example #49
0
# Resizing image to fit on button
record_speech_img = photo.subsample(6)

# Button to record and transcribe
speech_cmd_btn = Button(top_frame,
                        width=36,
                        height=36,
                        image=record_speech_img,
                        command=record_transcribe_music)
speech_cmd_btn.grid(column=3, row=2)

# Choose playback - background, melody, percussion, any combination
#--------------------------

# Define list with music mixing options
musicMixVar = StringVar(root)

musicMixDict = dict({
    'Background Only': (1, 0, 0),
    'Melody Only': (0, 1, 0),
    'Background and Percussion': (1, 0, 1),
    'Background and Melody': (1, 1, 0)
})

musicMixOptions = list(musicMixDict.keys())
musicMixVar.set(musicMixOptions[0])  # set the default option

chooseMixMenu = OptionMenu(top_frame, musicMixVar, *musicMixOptions)
chooseMixMenu.grid(column=0, row=3, columnspan=2)

# Percussion
open_image = ImageTk.PhotoImage(Image.open('open.png'))
open_button = tkinter.Button(menu_frame, image=open_image, command=open_note)
open_button.grid(row=0, column=1, padx=5, pady=5)

save_image = ImageTk.PhotoImage(Image.open('save.png'))
save_button = tkinter.Button(menu_frame, image=save_image, command=save_note)
save_button.grid(row=0, column=2, padx=5, pady=5)

close_image = ImageTk.PhotoImage(Image.open('close.png'))
close_button = tkinter.Button(menu_frame, image=close_image, command=close_note)
close_button.grid(row=0, column=3, padx=5, pady=5)

#Picked random fonts but you can use more fonts using tkinter.font.families().  Just import font
families = ['Terminal', 'Modern', 'Script', 'Courier', 'Arial', 'Calibri', 'Cambria', 'Georgia', 'MS Gothic', 'SimSun', 'Tahoma', 'Times New Roman', 'Verdana', 'Wingdings']
font_family = StringVar()
font_family.set(families[0])
font_family_drop = tkinter.OptionMenu(menu_frame, font_family, *families, command=change_font)
#Set the width so it will fit 'Times New Roman' and remain constant
font_family_drop.config(width=16)
font_family_drop.grid(row=0, column=4, padx=5, pady=5)

sizes =[8, 10, 12, 14, 16, 16, 20, 24, 32, 48, 64, 72, 96] 
font_size = IntVar()
font_size.set(sizes[2])
font_size_drop = tkinter.OptionMenu(menu_frame, font_size, *sizes, command=change_font)
#Set the width so it will remain constant,even if 8 is chosen.
font_size_drop.config(width=2)
font_size_drop.grid(row=0, column=5, padx=5, pady=5)

options = ['none', 'bold', 'italic']
Example #51
0
class BankGUI:
    def __init__(self, master):
        ## Inicializando  a aplicação e definindo um título para ela
        self.master = master
        self.master.geometry("1000x500")
        ## Definindo o servidor
        self.server = MyAccount()
        ## Construindo a interface para os comandos
        self.Bank = Bank()
        self.command_interface()

        ## Variável que mostrará o resultado das operações
        master.title("Bank")

        ## Título das aplicações
        self.label = Label(master, text="Sistema bancário")

        ## Setando o resultado das operações
        self.total = "Resutado das operações"
        self.total_label_text = StringVar()
        self.total_label_text.set(self.total)
        self.total_label = Label(master, textvariable=self.total_label_text)

        ## Definindo as configurações das entradas
        self.account_entry = Entry(master)
        self.value_entry = Entry(master)

        self.account_text = StringVar()
        self.account_text.set("conta: ")
        self.label_account = Label(master,
                                   textvariable=self.account_text,
                                   height=1)

        self.value_text = StringVar()
        self.value_text.set("  valor: ")
        self.label_value = Label(master,
                                 textvariable=self.value_text,
                                 height=1)

        ## Definindo as configurações dos botões
        self.statement_button = Button(
            master,
            text="Extrato",
            command=lambda: self.update("verify_statement"),
            height=1,
            width=10)
        self.balance_button = Button(
            master,
            text="Saldo",
            command=lambda: self.update("get_balance"),
            height=1,
            width=10)
        self.transaction_button = Button(
            master,
            text="Transação",
            command=lambda: self.update("make_transaction"),
            height=1,
            width=10)

        ## Making Layout
        self.set_layout()

    def set_layout(self):
        """Set the application layout"""
        self.label.grid(row=0, column=0, sticky=W)
        self.total_label.grid(row=4, column=0, columnspan=2, sticky=W)

        self.label_account.grid(row=3, column=1)
        self.label_value.grid(row=3, column=6)
        self.account_entry.grid(row=3, column=2, columnspan=3, sticky=W + E)
        self.value_entry.grid(row=3, column=7, columnspan=3, sticky=W + E)

        self.statement_button.grid(row=1, column=0)
        self.balance_button.grid(row=2, column=0)
        self.transaction_button.grid(row=3, column=0)

    def command_interface(self):
        self.Bank.register("make_transaction", MakeTransaction(self.server))
        self.Bank.register("verify_statement", VerifyStatement(self.server))
        self.Bank.register("get_balance", VerifyBalance(self.server))

    def update(self, command_name):
        if (command_name is "make_transaction"):
            if (self.account_entry.get() is ""
                    or self.value_entry.get() is ""):
                self.total = "Um dos campos não foi informado"
            else:
                try:
                    account = int(self.account_entry.get())
                    value = float(self.value_entry.get())
                    self.total = self.Bank.execute(command_name, account,
                                                   value)
                except:
                    self.total = "Entradas inválidas"
        else:
            self.total = self.Bank.execute(command_name)

        self.total_label_text.set(self.total)
        self.account_entry.delete(0, END)
        self.value_entry.delete(0, END)
Example #52
0
    #CREACIÓN DEL MENÚ ANALIZAR INCRUSTANDO LOS SUBMENÚS
    menubar.add_cascade(label="Reportes", menu=menu_reporte)

    #SE AGREGA LA BARRA DE MENÚ A LA RAÍZ
    root.config(menu=menubar)

    ####################################### EDITOR DE TEXTO #######################################

    # EDITOR DE TEXTO
    my_editor = Example(frame)
    my_editor.pack(side="top", fill="both", expand=True)

    #ETIQUETAS PARA LA FILA Y COLUMNA ACTUAL

    fila = StringVar()
    colum = StringVar()

    filaL = tk.Label(frame, textvariable=fila)
    filaL.place(x=100, y=550, width=100, height=25)
    filaL.pack()

    columnaL = tk.Label(frame, textvariable=colum)
    columnaL.place(x=100, y=590, width=100, height=25)
    columnaL.pack()

    ######################################### CONSOLA #############################################

    consola = tk.Text(root, bg='black', fg='white', state=tk.DISABLED)
    consola.place(x=30, y=505, width=1330, height=140)
Example #53
0
tree_data = (('red', '#FF0000', (255, 0, 0)), ('yellow', '#FFFF00', (255, 255,
                                                                     0)),
             ('blue', '#0000FF', (0, 0, 255)), ('green', '#00FF00', (0, 255,
                                                                     0)),
             ('magenta', '#FF00FF', (255, 0, 255)), ('cyan', '#00FFFF',
                                                     (0, 255, 255)))

fr0 = Frame(root)
fr0.grid(column=0, row=0, sticky='nsew')

# create Treeview widget
tree = Treeview(fr0, column=tree_columns, show='headings')
tree.grid(column=0, row=0, sticky='nsew')
tree.bind("<<TreeviewSelect>>", select_item)

# insert header
for col in tree_columns:
    tree.heading(col, text=col.title())

#insert data
for item in tree_data:
    itemID = tree.insert('', 'end', values=item)

# display selection
lvar = StringVar()
lbl = Label(fr0, textvariable=lvar, text="Ready")
lbl.grid(column=0, row=1, sticky='nsew')

root.mainloop()
    textDescription.insert(tk.END,listOfMovies[iid].getDescription())
    textDescription.config(state=tk.DISABLED)

#Main GUI	
window = tk.Tk() 

window.title("SP Movie")
window.geometry("400x600") 
window.resizable(0, 0) #Don't allow resizing in the x or y direction
window.configure(background = 'lavender')  #alternative use gray96

labelAppName=ttk.Label(window,text="SP Movie App",padding=2)
labelAppName.config(font=("Helvetica", 20))
labelAppName.grid(row=0,column=0,columnspan=4,pady=10)

txtNameFilter=StringVar()
entry1=ttk.Entry(window,textvariable=txtNameFilter)
entry1.grid(row=1,column=1,sticky=tk.W)
buttonSearch=ttk.Button(window,text='Filter Movie',command=filtermovie)
buttonSearch.grid(row=1,column=2,sticky=tk.W)

#treeview
tree1=ttk.Treeview(window)
tree1.heading("#0",text="Movie Name")

tree1.grid(row=2,column=1,columnspan=2,pady=15,sticky=tk.W)
tree1.bind('<ButtonRelease-1>', selectItem)

#movie Item Details
labelCategory=ttk.Label(window,text="Category",padding=2)
labelCategory.grid(row=3,column=0,sticky=tk.W)
Example #55
0
                          offvalue=0,
                          variable=highlight_line)
themes_menu = Menu(menu_bar, tearoff=0)
view_menu.add_cascade(label='Themes', menu=themes_menu)

color_schemes = {
    'Default': '#000000.#FFFFFF',
    'Greygarious': '#83406A.#D1D4D1',
    'Aquamarine': '#5B8340.#D1E7E0',
    'Bold Beige': '#4B4620.#FFF0E1',
    'Cobalt Blue': '#ffffBB.#3333aa',
    'Olive Green': '#D1E7E0.#5B8340',
    'Night Mode': '#FFFFFF.#000000',
}

theme_choice = StringVar()
theme_choice.set('Default')
for k in sorted(color_schemes):
    themes_menu.add_radiobutton(label=k, variable=theme_choice)
menu_bar.add_cascade(label='View', menu=view_menu)

about_menu = Menu(menu_bar, tearoff=0)
about_menu.add_command(label='About')
about_menu.add_command(label='Help')
menu_bar.add_cascade(label='About', menu=about_menu)
root.config(menu=menu_bar)

shortcut_bar = Frame(root, height=25, background='light sea green')
shortcut_bar.pack(expand='no', fill='x')
line_number_bar = Text(root,
                       width=4,
class MainApplication(Tk):
    files_map: dict = {}
    original_filenames_map: dict = {}
    scroll_bar_position = (0.0, 1.0)
    cmd_args = "/k"

    def get_all_files(self, files_path):
        for file in listdir(files_path):
            if path.isfile(path.join(files_path, file)):
                yield file

    def reset_files_boxes(self):
        self.result_files_box.delete(0, END)
        for item in self.files_map.keys():
            self.files_map[item] = item

    def show_items(self, list_of_items: list, target_box: Listbox,
                   check_original: bool):
        target_box.delete(0, END)
        index = 0
        for item in list_of_items:
            target_box.insert(END, item)
            if check_original and not self.files_map.get(item):
                self.source_files_box.itemconfig(index, {'fg': 'gray50'})
                target_box.itemconfig(index, {'fg': 'red'})
            elif check_original and self.files_map.get(item):
                self.source_files_box.itemconfig(index, {'fg': 'black'})
                target_box.itemconfig(index, {'fg': 'black'})
            index += 1
        scroll_position = ('moveto', self.scroll_bar_position[0])
        self.source_files_box.yview(*scroll_position)
        self.result_files_box.yview(*scroll_position)

    def run_test_button(self):
        if 'TestTool' in environ:
            if self.path_input_text_variable.get():
                test_tool_path = environ.get('TestTool').replace("\\", "\\\\")
                system("start \"\" cmd " + self.cmd_args + " \"cd /D " +
                       test_tool_path + "  & test.bat run \"" +
                       self.path_input_text_variable.get().replace("/", "\\") +
                       "\" \"")
        else:
            self.error_message_label.configure(
                text=
                "Error Running the test. 'TestTool' environment variable is not set."
            )

    def rename_all_files(self, new_name):
        if self.rename_radio_value.get() == 2:
            items = self.source_files_box.curselection()
            for item in items:
                selected_filename = self.original_filenames_map.get(item)
                split_name = selected_filename.split("_", 1)
                if len(split_name) >= 1:
                    self.files_map[
                        selected_filename] = new_name + "_" + split_name[1]
        else:
            for filename in self.files_map.keys():
                split_name = filename.split("_", 1)
                if len(split_name) >= 1:
                    self.files_map[filename] = new_name + "_" + split_name[1]

        self.show_items(self.files_map.values(), self.result_files_box, True)

    def reset_messages(self):
        self.error_message_label.configure(text="")
        self.output_message_label.configure(text="")

    def save_button_handler(self):
        files_to_rename = 0
        for item in self.files_map:
            if item != self.files_map[item]:
                files_to_rename += 1
        if files_to_rename > 0:
            if messagebox.askyesno(
                    'Rename Confirmation', 'Do you really want to rename ' +
                    str(files_to_rename) + ' files?'):
                files_not_renamed = 0
                current_dir = self.path_input_text_variable.get()
                renamed_files = 0
                for item in self.files_map:
                    if item != self.files_map[item]:
                        src = current_dir + "\\" + item
                        dst = current_dir + "\\" + self.files_map[item]
                        try:
                            rename(src, dst)
                            renamed_files += 1
                        except FileExistsError:
                            files_not_renamed += 1
                self.output_message_label.configure(
                    text=str(renamed_files) + " files successfully renamed!")
                self.build_files_box()
                if files_not_renamed > 0:
                    self.error_message_label.configure(
                        text="Cannot rename " + str(files_not_renamed) +
                        " file(s). File already exists!")
            else:
                self.reset_messages()
        else:
            self.error_message_label.configure(text="Nothing to rename!")

    def open_path_button(self):
        # Enter Path section
        if self.path_input_text_variable.get():
            current_directory_path = filedialog.askdirectory(
                parent=self.inputFrame,
                initialdir=self.path_input_text_variable.get(),
                title='Please select a directory')
        else:
            current_directory_path = filedialog.askdirectory(
                parent=self.inputFrame,
                initialdir="/",
                title='Please select a directory')
        if current_directory_path:
            self.path_input_text_variable.set(current_directory_path)
            self.build_files_box()

    def step_button(self, item_type, increment):
        def update_step(filename):
            selected_temp_filename = self.files_map.get(filename)
            split_name = selected_temp_filename.split("_", 2)
            if len(split_name) >= 2:
                sequence = int(split_name[1])

                if increment:
                    sequence += 1
                elif sequence > 0:
                    sequence -= 1

                if sequence < 10:
                    sequence_str = "_0" + str(sequence) + "_"
                else:
                    sequence_str = "_" + str(sequence) + "_"
            self.files_map[
                filename] = split_name[0] + sequence_str + split_name[2]

        def update_index(filename, index_to_update):
            selected_temp_filename = self.files_map.get(filename)

            if selected_temp_filename.find(index_to_update) > 0:
                start_position = selected_temp_filename.find(
                    index_to_update) + len(index_to_update)
                index_len = 3
                sequence = 0
                while index_len > 0:
                    try:
                        sequence = int(selected_temp_filename[
                            start_position:start_position + index_len])
                        break
                    except ValueError:
                        index_len -= 1

                if increment:
                    sequence += 1
                elif sequence > 0:
                    sequence -= 1

                self.files_map[filename] = selected_temp_filename.replace(
                    selected_temp_filename[selected_temp_filename.find(
                        index_to_update):start_position + index_len],
                    index_to_update + str(sequence), 1)

        if item_type == 'step':
            if self.rename_radio_value.get() == 2:
                items = self.source_files_box.curselection()
                for item in items:
                    selected_filename = self.original_filenames_map.get(item)
                    update_step(selected_filename)

            else:
                for filename in self.files_map.keys():
                    update_step(filename)
        else:
            if self.rename_radio_value.get() == 2:
                items = self.source_files_box.curselection()
                for item in items:
                    selected_filename = self.original_filenames_map.get(item)
                    update_index(selected_filename, item_type)

            else:
                for filename in self.files_map.keys():
                    update_index(filename, item_type)

        self.show_items(self.files_map.values(), self.result_files_box, True)

    def build_files_box(self):
        self.reset_messages()
        # Build a dictionary(originalFilename -> updatedFilename) from provided input
        try:
            self.files_map.clear()
            self.original_filenames_map.clear()
            index = 0
            for filename in self.get_all_files(
                    self.path_input_text_variable.get()):
                self.files_map[filename] = filename
                if index == 0:
                    split_name = filename.split("_", 1)
                    self.name_input_text_variable.set(split_name[0])

                self.original_filenames_map[index] = filename
                index += 1

            self.show_items(self.files_map.keys(), self.source_files_box,
                            False)
            self.show_items(self.files_map.values(), self.result_files_box,
                            False)

        except FileNotFoundError:
            self.error_message_label.configure(text="Invalid Path provided")
            self.source_files_box.delete(0, END)
            self.result_files_box.delete(0, END)

        except FileExistsError:
            self.error_message_label.configure(
                text="Cannot create a file when that file already exists")

    def build_input_frame(self):
        def enter_handler(event):
            self.build_files_box()

        def key_pressed_handler(event):
            new_name = self.name_input_text_variable.get()
            self.rename_all_files(new_name)

        def select_handler():
            self.reset_files_boxes()
            new_name = self.name_input_text_variable.get()
            self.rename_all_files(new_name)

        # Enter Path section
        path_label = Label(self.inputFrame, text="Enter Files Path: ")
        path_label.grid(row=0,
                        column=0,
                        pady=(10, 0),
                        padx=(10, 0),
                        sticky='w')
        self.path_input_text_variable = StringVar()
        self.path_input = Entry(self.inputFrame,
                                width=30,
                                textvariable=self.path_input_text_variable)
        self.path_input.bind('<Return>', enter_handler)
        self.path_input.grid(row=0,
                             column=1,
                             pady=(10, 0),
                             padx=(0, 0),
                             sticky='w')
        Button(self.inputFrame,
               text="browse",
               command=self.open_path_button,
               height=1).grid(row=0,
                              column=2,
                              pady=(10, 0),
                              padx=(0, 0),
                              sticky='w')

        # Enter Name section
        Label(self.inputFrame, text="Enter Name:").grid(row=0,
                                                        column=4,
                                                        pady=(10, 0),
                                                        padx=(30, 0),
                                                        sticky='e')
        self.name_input_text_variable = StringVar()
        name_input = Entry(self.inputFrame,
                           width=30,
                           textvariable=self.name_input_text_variable)
        name_input.grid(row=0,
                        column=5,
                        columnspan=2,
                        pady=(10, 0),
                        padx=(10, 0))
        name_input.bind('<KeyRelease>', key_pressed_handler)

        # Rename all Radio Buttons
        self.rename_radio_value = IntVar()
        Label(self.inputFrame, text="Rename:").grid(row=1,
                                                    column=4,
                                                    pady=(0, 0),
                                                    padx=(0, 0),
                                                    sticky='e')
        Radiobutton(self.inputFrame, text="All", variable=self.rename_radio_value,
                       value=1, command=lambda: select_handler()) \
            .grid(row=1, column=5, pady=(0, 0), padx=(10, 0), sticky='w')
        Radiobutton(self.inputFrame, text="Selected", variable=self.rename_radio_value,
                       value=2, command=lambda: select_handler()) \
            .grid(row=1, column=6, pady=(0, 0), padx=(0, 0), sticky='w')
        self.rename_radio_value.set(1)

        Button(self.inputFrame, text="Run Test", command=lambda: self.run_test_button(), height=1, width=12) \
            .grid(row=2, column=0, padx=(10, 0), pady=(0, 0))
        Button(self.inputFrame, text="Step-", command=lambda: self.step_button('step', False), height=1) \
            .grid(row=2, column=7, padx=(0, 0), pady=(0, 0))
        Button(self.inputFrame, text="Step+", command=lambda: self.step_button('step', True), height=1) \
            .grid(row=2, column=8, padx=(0, 0), pady=(0, 0))
        Button(self.inputFrame, text="cl-", command=lambda: self.step_button('_cl', False), height=1) \
            .grid(row=2, column=9, padx=(10, 0), pady=(0, 0))
        Button(self.inputFrame, text="cl+", command=lambda: self.step_button('_cl', True), height=1) \
            .grid(row=2, column=10, padx=(0, 0), pady=(0, 0))
        Button(self.inputFrame, text="en-", command=lambda: self.step_button('_en', False), height=1) \
            .grid(row=2, column=11, padx=(10, 0), pady=(0, 0))
        Button(self.inputFrame, text="en+", command=lambda: self.step_button('_en', True), height=1) \
            .grid(row=2, column=12, padx=(0, 0), pady=(0, 0))
        Button(self.inputFrame, text="i-", command=lambda: self.step_button('_i', False), height=1) \
            .grid(row=2, column=13, padx=(10, 0), pady=(0, 0))
        Button(self.inputFrame, text="i+", command=lambda: self.step_button('_i', True), height=1) \
            .grid(row=2, column=14, padx=(0, 0), pady=(0, 0))

    def build_output_frame(self):
        def on_single_click_release(event):
            if self.rename_radio_value.get() == 2:
                self.reset_files_boxes()
                new_name = self.name_input_text_variable.get()
                self.rename_all_files(new_name)

        def yscroll1(*args):
            if self.result_files_box.yview() != self.source_files_box.yview():
                self.result_files_box.yview_moveto(args[0])
            self.source_files_scrollbar.set(*args)
            self.result_files_scrollbar.set(*args)
            self.scroll_bar_position = (args[0], args[1])

        def yscroll2(*args):
            if self.source_files_box.yview() != self.result_files_box.yview():
                self.source_files_box.yview_moveto(args[0])
            self.source_files_scrollbar.set(*args)
            self.result_files_scrollbar.set(*args)
            self.scroll_bar_position = (args[0], args[1])

        def yview(*args):
            self.source_files_box.yview(*args)
            self.result_files_box.yview(*args)

        # Before box - displaying original filenames
        Label(self.outputFrame, text="Before:").grid(row=0,
                                                     column=0,
                                                     pady=(5, 0),
                                                     padx=(10, 0),
                                                     sticky='w')
        self.source_files_box = Listbox(self.outputFrame,
                                        selectmode=EXTENDED,
                                        activestyle='none')
        self.source_files_box.grid(row=1,
                                   column=0,
                                   pady=5,
                                   padx=(15, 0),
                                   sticky="nsew")
        self.source_files_box.bind('<Double-Button-1>', self.on_double_click)
        self.source_files_box.bind('<ButtonRelease-1>',
                                   on_single_click_release)
        self.source_files_scrollbar = Scrollbar(self.outputFrame,
                                                orient="vertical")
        self.source_files_scrollbar.grid(row=1, column=1, pady=5, sticky="nsw")
        self.source_files_scrollbar.config(command=yview)
        self.source_files_box.config(yscrollcommand=yscroll1)
        self.source_files_box.configure(exportselection=False)

        # '->' label between the 2 boxes
        # TODO: add a custom image instead of plain text
        Label(self.outputFrame, text="->", anchor="center").grid(row=1,
                                                                 column=2,
                                                                 padx=(10, 0),
                                                                 sticky='nsew')

        # After box - displaying updated filenames
        Label(self.outputFrame, text="After:").grid(row=0,
                                                    column=3,
                                                    pady=(5, 0),
                                                    padx=(10, 0),
                                                    sticky='w')
        self.result_files_box = Listbox(self.outputFrame,
                                        selectmode=SINGLE,
                                        selectbackground='white',
                                        selectforeground='black',
                                        activestyle='none')
        self.result_files_box.grid(row=1,
                                   column=3,
                                   pady=5,
                                   padx=(10, 0),
                                   sticky="nsew")
        self.result_files_box.bind('<Double-Button-1>', self.on_double_click)
        self.result_files_scrollbar = Scrollbar(self.outputFrame,
                                                orient="vertical")
        self.result_files_scrollbar.grid(row=1,
                                         column=4,
                                         pady=5,
                                         padx=(0, 15),
                                         sticky="nsw")
        self.result_files_scrollbar.config(command=yview)
        self.result_files_box.config(yscrollcommand=yscroll2)

    def build_messages_frame(self):
        self.output_message_label = Label(self.messagesFrame,
                                          text="",
                                          anchor="w")
        self.output_message_label.grid(row=0, column=0, padx=5, sticky='w')

        self.error_message_label = Label(self.messagesFrame,
                                         text="",
                                         anchor="w",
                                         fg="red")
        self.error_message_label.grid(row=1, column=0, padx=5, sticky='w')
        Button(self.messagesFrame, text="Refresh", command=self.build_files_box, width=8) \
            .grid(row=0, column=1, pady=(5, 0), padx=(0, 0), sticky='nsew')

        Button(self.messagesFrame, text="Save", command=self.save_button_handler, width=8) \
            .grid(row=0, column=2, pady=(5, 0), padx=(5, 15), sticky='nsew')

    def on_double_click(self, evt):
        # Note here that Tkinter passes an event object to onselect()
        w = evt.widget
        index = int(w.curselection()[0])
        value = w.get(index)
        startfile(self.path_input.get() + '/' + value)

    def __init__(self):
        super().__init__()
        self.title("SDETs rename helper")
        self.inputFrame = Frame()
        self.outputFrame = Frame()
        self.messagesFrame = Frame()
        self.minsize(900, 400)

        self.geometry("1250x700")

        self.build_input_frame()
        self.build_output_frame()
        self.build_messages_frame()

        self.path_input_text_variable.set(getcwd())
        self.build_files_box()

        if len(argv) > 2 and argv[2]:
            self.cmd_args = argv[2]

        self.inputFrame.grid(row=0, column=0, sticky='nsew')
        self.outputFrame.grid(row=1, column=0, sticky='nsew')
        self.messagesFrame.grid(row=2, column=0, sticky='nsew')

        self.inputFrame.columnconfigure(0, weight=1)
        self.inputFrame.columnconfigure(1, weight=1)
        self.inputFrame.columnconfigure(2, weight=1)
        self.inputFrame.columnconfigure(3, weight=90, minsize=120)
        self.inputFrame.columnconfigure(4, weight=1)
        self.inputFrame.columnconfigure(5, weight=1)
        self.inputFrame.columnconfigure(6, weight=1)
        self.inputFrame.columnconfigure(7, weight=1)
        self.inputFrame.columnconfigure(8, weight=1)
        self.inputFrame.columnconfigure(9, weight=1)
        self.inputFrame.columnconfigure(10, weight=1)
        self.inputFrame.columnconfigure(11, weight=1)
        self.inputFrame.columnconfigure(12, weight=1)
        self.inputFrame.columnconfigure(13, weight=1)
        self.inputFrame.columnconfigure(14, weight=1)
        self.inputFrame.rowconfigure(0, weight=1)
        self.inputFrame.rowconfigure(1, weight=1)
        self.inputFrame.rowconfigure(2, weight=1)

        self.outputFrame.columnconfigure(0, weight=50)
        self.outputFrame.columnconfigure(1, weight=1)
        self.outputFrame.columnconfigure(2, weight=1)
        self.outputFrame.columnconfigure(3, weight=50)
        self.outputFrame.columnconfigure(4, weight=1)
        self.outputFrame.rowconfigure(0, weight=1)
        self.outputFrame.rowconfigure(1, weight=50)

        self.messagesFrame.columnconfigure(0, weight=50)
        self.messagesFrame.columnconfigure(1, weight=1)
        self.messagesFrame.columnconfigure(2, weight=1)

        self.columnconfigure(0, weight=1)
        self.rowconfigure(0, weight=1)
        self.rowconfigure(1, weight=50)
        self.rowconfigure(2, weight=1)
Example #57
0
class chr_to_png(Tk):
    def __init__(self, parent):
        Tk.__init__(self, parent)
        self.parent = parent
        self.initialize()

    def initialize(self):
        # menu left
        self.clearVars()
        self.frame_w = Frame(self, width=100, bg="black")
        self.frame_w2 = Frame(self.frame_w,
                              width=100,
                              height=150,
                              bg='#dfdfdf')

        self.left_title = Label(self.frame_w2, text='', bg='#dfdfdf')
        self.left_title.pack()
        self.s_title = Label(self.frame_w2, text='# @_#E', bg='#dfdfdf')
        self.s_title.pack(side=BOTTOM)

        self.but_file = Button(self.frame_w2,
                               text='Dump file',
                               command=self.getPath)
        self.but_fold = Button(self.frame_w2,
                               text='Dump folder',
                               command=self.getPathDir)
        self.but_sdir = Button(self.frame_w2,
                               state=DISABLED,
                               text='Save to...',
                               command=self.setDirectory)
        self.but_conv = Button(self.frame_w2,
                               state=DISABLED,
                               text='Go',
                               command=self.convertFile)
        self.but_exit = Button(self.frame_w2,
                               text='Exit',
                               command=lambda: exit())
        self.but_file.pack(fill=BOTH)
        self.but_fold.pack(fill=BOTH)
        self.but_sdir.pack(fill=BOTH)
        self.but_conv.pack(fill=BOTH)
        self.but_exit.pack(fill=BOTH, side=BOTTOM)
        famicom_img = PhotoImage(file='images/img.png')
        famicom_label = Label(self.frame_w2, image=famicom_img)
        famicom_label.image = famicom_img
        famicom_label.pack(fill=BOTH, expand=True)
        self.frame_w2.pack(side=TOP, fill=BOTH, expand=True)

        # right area
        self.frame_e = Frame(self, bg="#dfdfdf")

        self.some_title = Label(self.frame_e,
                                text="__ by nnov 2017 __  vaporw8bit  ___",
                                bg="#dfdfdf")
        self.some_title.pack()
        self.canvas_area = Canvas(self,
                                  width=500,
                                  height=400,
                                  background="#ffffff")
        self.canvas_area.grid(row=1, column=1)

        back_img = PhotoImage(file='images/back.png')
        back_label = Label(self.canvas_area, image=back_img)
        back_label.image = back_img
        back_label.pack(fill=BOTH, expand=True)

        # status
        self.status_frame = Frame(self)
        self.labelVariable = StringVar()
        self.status = Label(self.status_frame,
                            textvariable=self.labelVariable,
                            anchor="w",
                            fg="white",
                            bg="purple")
        self.status.pack(fill=BOTH, expand=True)
        self.labelVariable.set('Please select a CHR file.')

        self.frame_w.grid(row=0, column=0, rowspan=2, sticky="nsew")
        self.frame_e.grid(row=0, column=1, sticky="ew")
        self.canvas_area.grid(row=1, column=1, sticky="nsew")
        self.status_frame.grid(row=2, column=0, columnspan=2, sticky="ew")

        self.grid_rowconfigure(1, weight=1)
        self.grid_columnconfigure(1, weight=1)

        self.resizable(False, False)

    def createLog(self, dump_dir, num_good, num_bad, bad_files, date_start,
                  date_end):
        with open(dump_dir + '/LOG.TXT', 'w') as execution_log:
            execution_log.write('EXECUTION COMPLETE.\n')
            execution_log.write('Started: ' + date_start + '\n')
            execution_log.write('Finished: ' + date_end + '\n')
            execution_log.write('_' * 50 + '\n')
            execution_log.write('Total files processed: ' +
                                str(num_good + num_bad) + '\n')
            execution_log.write('Successfully converted: ' + str(num_good) +
                                '\n')
            execution_log.write('Not converted (ERROR): ' + str(num_bad) +
                                '\n')
            execution_log.write('_' * 50 + '\n')
            [execution_log.write(x + '\n') for x in bad_files.split('@@')]
            execution_log.write('_' * 50 + '\n')

    def clearVars(self):
        self.save_dir = ''
        self.filename = ''

    def configOptions(self, enable_disable):
        if enable_disable:
            self.but_sdir['state'] = NORMAL
            self.but_conv['state'] = NORMAL
        else:
            self.but_sdir['state'] = DISABLED
            self.but_conv['state'] = DISABLED

    def getPath(self):
        self.filename = askopenfilename(
            filetypes=[('All files', '*'), ('CHR files',
                                            '*.chr'), ('NES files', '*.nes')])
        if self.filename:
            self.labelVariable.set(
                os.path.split(self.filename)[1] + ' selected.')
            self.save_dir = os.path.split(self.filename)[0]
            self.configOptions(True)

    def getPathDir(self):
        self.filename = askdirectory()
        if self.filename:
            self.save_dir = self.filename
            self.labelVariable.set('".../' + self.filename.split('/')[-1] +
                                   '" directory selected.')
            self.configOptions(True)

    def setDirectory(self):
        self.save_dir = askdirectory()

    def convertFile(self):
        self.configOptions(False)
        if (self.filename == ''):
            self.labelVariable.set('Please enter a valid file or directory.')
        if not (self.filename.lower().endswith('.chr')
                or self.filename.lower().endswith('.nes')):
            dump_dir = self.filename
            good_files = 0
            bad_files = 0
            list_bad_files = ''
            starting_at = time.strftime('%x - %X')
            self.labelVariable.set('Processing files.')

            for a_file in sorted([x for x in \
                os.listdir(self.filename) if (x.lower().endswith('.chr') or x.lower().endswith('.nes')) ]):
                self.filename = dump_dir + '/' + a_file
                try:
                    self.converter()
                    good_files += 1
                except:
                    bad_files += 1
                    list_bad_files += '@@' + a_file
                self.createLog(dump_dir, good_files, bad_files, list_bad_files,
                               starting_at, time.strftime('%x - %X'))
                self.labelVariable.set(
                    str(good_files + bad_files) +
                    ' files processed. See LOG.TXT for info.')
        else:
            try:
                self.converter()
                self.labelVariable.set(
                    os.path.split(self.filename)[1] +
                    ' was converted successfully.')
            except:
                self.labelVariable.set('There was an error while processing ' +
                                       os.path.split(self.filename)[1] + '.')
        self.clearVars()
        self.configOptions(True)

    def converter(self):
        PALETTE = [(0, 0, 0), (255, 0, 0), (0, 0, 255), (255, 255, 255)]
        TILES_IN_ROW = 128

        with open(self.filename, 'rb') as chr_file:
            in_hex = str(binascii.hexlify(chr_file.read()))[2:-1]

        tiles = [
            in_hex[index:index + 32] for index in range(0, len(in_hex), 32)
        ]
        SIZE_CHR = len(tiles)

        mega_pixel = list()
        IMG_HTILES = int(SIZE_CHR / TILES_IN_ROW)

        row_count = 1
        column_count = 0

        for tile in tiles:
            column_count += 1
            if column_count == 17:
                row_count + 1
                column_count = 1
            decode = [ x + 2*y for x, y in zip(\
                                  [int(x) for x in list(bin(int(tile[:16], 16))[2:].zfill(64))], \
                                  [int(x) for x in list(bin(int(tile[16:], 16))[2:].zfill(64))] ) ]
            mega_pixel.append([
                decode[index:index + 8] for index in range(0, len(decode), 8)
            ])

        reshape = [
            mega_pixel[index:index + IMG_HTILES]
            for index in range(0, SIZE_CHR, IMG_HTILES)
        ]

        reshape.append([[[0, 0, 0, 0, 0, 0, 0, 0]] * 8])

        if len(reshape[-1]) < len(reshape[-2]):
            fill = len(reshape[-2]) - len(reshape[-1])
            [
                reshape[-1].append([[0, 0, 0, 0, 0, 0, 0, 0]] * 8)
                for i in range(0, fill)
            ]

        result = [ entry for sublist in \
                    [ numpy.hstack(reshape[row]) for row in \
                      range(0, len(reshape)) ] for entry in sublist ]

        png_file = open(
            self.save_dir + '/' + os.path.split(self.filename)[1] + '.png',
            'wb')
        file_writer = png.Writer(len(result[0]), len(result), palette=PALETTE)
        file_writer.write(png_file, result)
        png_file.close()
    def build_input_frame(self):
        def enter_handler(event):
            self.build_files_box()

        def key_pressed_handler(event):
            new_name = self.name_input_text_variable.get()
            self.rename_all_files(new_name)

        def select_handler():
            self.reset_files_boxes()
            new_name = self.name_input_text_variable.get()
            self.rename_all_files(new_name)

        # Enter Path section
        path_label = Label(self.inputFrame, text="Enter Files Path: ")
        path_label.grid(row=0,
                        column=0,
                        pady=(10, 0),
                        padx=(10, 0),
                        sticky='w')
        self.path_input_text_variable = StringVar()
        self.path_input = Entry(self.inputFrame,
                                width=30,
                                textvariable=self.path_input_text_variable)
        self.path_input.bind('<Return>', enter_handler)
        self.path_input.grid(row=0,
                             column=1,
                             pady=(10, 0),
                             padx=(0, 0),
                             sticky='w')
        Button(self.inputFrame,
               text="browse",
               command=self.open_path_button,
               height=1).grid(row=0,
                              column=2,
                              pady=(10, 0),
                              padx=(0, 0),
                              sticky='w')

        # Enter Name section
        Label(self.inputFrame, text="Enter Name:").grid(row=0,
                                                        column=4,
                                                        pady=(10, 0),
                                                        padx=(30, 0),
                                                        sticky='e')
        self.name_input_text_variable = StringVar()
        name_input = Entry(self.inputFrame,
                           width=30,
                           textvariable=self.name_input_text_variable)
        name_input.grid(row=0,
                        column=5,
                        columnspan=2,
                        pady=(10, 0),
                        padx=(10, 0))
        name_input.bind('<KeyRelease>', key_pressed_handler)

        # Rename all Radio Buttons
        self.rename_radio_value = IntVar()
        Label(self.inputFrame, text="Rename:").grid(row=1,
                                                    column=4,
                                                    pady=(0, 0),
                                                    padx=(0, 0),
                                                    sticky='e')
        Radiobutton(self.inputFrame, text="All", variable=self.rename_radio_value,
                       value=1, command=lambda: select_handler()) \
            .grid(row=1, column=5, pady=(0, 0), padx=(10, 0), sticky='w')
        Radiobutton(self.inputFrame, text="Selected", variable=self.rename_radio_value,
                       value=2, command=lambda: select_handler()) \
            .grid(row=1, column=6, pady=(0, 0), padx=(0, 0), sticky='w')
        self.rename_radio_value.set(1)

        Button(self.inputFrame, text="Run Test", command=lambda: self.run_test_button(), height=1, width=12) \
            .grid(row=2, column=0, padx=(10, 0), pady=(0, 0))
        Button(self.inputFrame, text="Step-", command=lambda: self.step_button('step', False), height=1) \
            .grid(row=2, column=7, padx=(0, 0), pady=(0, 0))
        Button(self.inputFrame, text="Step+", command=lambda: self.step_button('step', True), height=1) \
            .grid(row=2, column=8, padx=(0, 0), pady=(0, 0))
        Button(self.inputFrame, text="cl-", command=lambda: self.step_button('_cl', False), height=1) \
            .grid(row=2, column=9, padx=(10, 0), pady=(0, 0))
        Button(self.inputFrame, text="cl+", command=lambda: self.step_button('_cl', True), height=1) \
            .grid(row=2, column=10, padx=(0, 0), pady=(0, 0))
        Button(self.inputFrame, text="en-", command=lambda: self.step_button('_en', False), height=1) \
            .grid(row=2, column=11, padx=(10, 0), pady=(0, 0))
        Button(self.inputFrame, text="en+", command=lambda: self.step_button('_en', True), height=1) \
            .grid(row=2, column=12, padx=(0, 0), pady=(0, 0))
        Button(self.inputFrame, text="i-", command=lambda: self.step_button('_i', False), height=1) \
            .grid(row=2, column=13, padx=(10, 0), pady=(0, 0))
        Button(self.inputFrame, text="i+", command=lambda: self.step_button('_i', True), height=1) \
            .grid(row=2, column=14, padx=(0, 0), pady=(0, 0))
Example #59
0
class Titanicsurvival():
    """ titanic survival class"""
    def __init__(self, master):
        self.master = master
        self.master.title("Titanic Survival")
        self.master.geometry("300x350")
        self.master.resizable(False, False)
        self.filename = ""
        model_filename = 'models/MLPClassifier30798.sav'
        self.loadedmodel = pickle.load(open(model_filename, 'rb'))
        self.importeddf = ""
        self.predictions = ""

        self.nameleb = Label(self.master, text="Enter name")
        self.nameleb.pack()

        self.nametext = Text(self.master, height=1)
        self.nametext.pack()

        self.ageleb = Label(self.master, text="Enter age")
        self.ageleb.pack()

        self.agetext = Text(self.master, height=1, width=3)
        self.agetext.pack()

        self.nofsiblleb = Label(self.master,
                                text="Enter the number of Siblings/Spouses")
        self.nofsiblleb.pack()

        self.nofparentstext = Text(self.master, height=1, width=3)
        self.nofparentstext.pack()

        self.noffammebleb = Label(self.master,
                                  text="Enter the number of Parents/Children")
        self.noffammebleb.pack()

        self.noffammebtext = Text(self.master, height=1, width=3)
        self.noffammebtext.pack()

        self.fareleb = Label(self.master, text="Enter fare")
        self.fareleb.pack()

        self.faretext = Text(self.master, height=1, width=7)
        self.faretext.pack()

        self.sexlist = ["Male", "Female"]
        self.sexstring = StringVar(master)
        self.sexstring.set("Select a Sex")
        self.sexpopup = OptionMenu(self.master, self.sexstring, *self.sexlist)
        self.sexpopup.pack()

        self.pclasslist = ["1st", "2nd", '3rd']
        self.pclassstring = StringVar(master)
        self.pclassstring.set("Select a Ticket class")
        self.pclasspopup = OptionMenu(self.master, self.pclassstring,
                                      *self.pclasslist)
        self.pclasspopup.pack()

        self.embarkedlist = ["C", "Q", "S"]
        self.embarkedstring = StringVar(master)
        self.embarkedstring.set("Select a Port of Embarkation")
        self.embarkedpopup = OptionMenu(self.master, self.embarkedstring,
                                        *self.embarkedlist)
        self.embarkedpopup.pack()

        self.predictbutton = Button(self.master,
                                    text="PREDICT",
                                    command=self.predict)
        self.predictbutton.pack()

        self.clearbutton = Button(self.master,
                                  text="CLEAR",
                                  command=self.clear)
        self.clearbutton.pack()

        self.menu = Menu(self.master)

        self.file_menu = Menu(self.menu, tearoff=0)
        self.file_menu.add_command(label="Insert a csv",
                                   accelerator='Ctrl+O',
                                   command=self.insertfile)
        self.file_menu.add_command(label="Close file",
                                   accelerator='Ctrl+F4',
                                   command=self.closefile)
        self.file_menu.add_command(label="Save file",
                                   accelerator='Ctrl+S',
                                   command=self.savepredictions)
        self.file_menu.add_command(label="Save to existed file",
                                   accelerator='Alt+S',
                                   command=self.savetoexisted)
        self.file_menu.add_command(label="Exit",
                                   accelerator='Alt+F4',
                                   command=self.exitmenu)
        self.menu.add_cascade(label="File", menu=self.file_menu)

        self.show_menu = Menu(self.menu, tearoff=0)
        self.show_menu.add_command(label="Show Predictions",
                                   accelerator='Ctrl+ F5',
                                   command=self.showpredictions)
        self.menu.add_cascade(label="Show", menu=self.show_menu)

        self.edit_menu = Menu(self.menu, tearoff=0)
        self.edit_menu.add_command(label="Clear All",
                                   accelerator='Ctrl+Z',
                                   command=self.clear)
        self.submenuclear = Menu(self.edit_menu, tearoff=0)
        self.submenuclear.add_command(
            label="Name",
            accelerator="Ctrl+T",
            command=lambda: self.clear(self.nametext))
        self.submenuclear.add_command(label="Age",
                                      accelerator="Alt+T",
                                      command=lambda: self.clear(self.agetext))
        self.submenuclear.add_command(
            label="Siblings/Spouses",
            accelerator="Alt+N",
            command=lambda: self.clear(self.noffammebtext))
        self.submenuclear.add_command(
            label="Parents/Children",
            accelerator="Ctrl+N",
            command=lambda: self.clear(self.nofparentstext))
        self.submenuclear.add_command(
            label="Fare",
            accelerator="Alt+Z",
            command=lambda: self.clear(self.faretext))
        self.edit_menu.add_cascade(label="Clear text",
                                   menu=self.submenuclear,
                                   underline=0)
        self.submenureset = Menu(self.edit_menu, tearoff=0)
        self.submenureset.add_command(
            label="Sex",
            accelerator="Alt+M",
            command=lambda: self.clear(
                toclear=self.sexstring, textflag=False, text="Select a Sex"))
        self.submenureset.add_command(
            label="Ticket class",
            accelerator="Ctrl+M",
            command=lambda: self.clear(toclear=self.pclassstring,
                                       textflag=False,
                                       text="Select a Ticket class"))
        self.submenureset.add_command(
            label="Embarkation",
            accelerator="Ctrl+K",
            command=lambda: self.clear(toclear=self.embarkedstring,
                                       textflag=False,
                                       text="Select a Port of Embarkation"))
        self.edit_menu.add_cascade(label="Reset Options",
                                   menu=self.submenureset,
                                   underline=0)
        self.menu.add_cascade(label="Edit", menu=self.edit_menu)

        self.about_menu = Menu(self.menu, tearoff=0)
        self.about_menu.add_command(label="About",
                                    accelerator='Ctrl+I',
                                    command=aboutmenu)
        self.menu.add_cascade(label="About", menu=self.about_menu)

        self.help_menu = Menu(self.menu, tearoff=0)
        self.help_menu.add_command(label="Help",
                                   accelerator='Ctrl+F1',
                                   command=helpmenu)
        self.menu.add_cascade(label="Help", menu=self.help_menu)

        self.master.config(menu=self.menu)
        self.master.bind('<Control-F5>', lambda event: self.showpredictions())
        self.master.bind('<Control-z>', lambda event: self.clear(None))
        self.master.bind('<Alt-F4>', lambda event: self.exitmenu())
        self.master.bind('<Control-F1>', lambda event: helpmenu())
        self.master.bind('<Control-i>', lambda event: aboutmenu())
        self.master.bind('<Control-o>', lambda event: self.insertfile())
        self.master.bind('<Control-F4>', lambda evemt: self.closefile())
        self.master.bind('<Control-t>',
                         lambda event: self.clear(self.nametext))
        self.master.bind('<Alt-t>', lambda event: self.clear(self.agetext))
        self.master.bind('<Alt-z>', lambda event: self.clear(self.faretext))
        self.master.bind('<Alt-n>',
                         lambda event: self.clear(self.nofparentstext))
        self.master.bind('<Control-n>',
                         lambda event: self.clear(self.noffammebtext))
        self.master.bind(
            '<Control-m>',
            lambda event: self.clear(toclear=self.pclassstring,
                                     textflag=False,
                                     text="Select a Ticket class"))
        self.master.bind(
            '<Alt-m>', lambda event: self.clear(
                toclear=self.sexstring, textflag=False, text="Select a Sex"))
        self.master.bind(
            '<Control-k>',
            lambda event: self.clear(toclear=self.embarkedstring,
                                     textflag=False,
                                     text="Select a Port of Embarkation"))

    def checktosave(self, filename):
        if filename is None or filename == "":
            msg.showerror("ERROR", "NO FILE SAVED")
        else:
            np.savetxt(str(filename) + ".csv", self.predictions)
            msg.showinfo("SUCCESS", "CSV FILE SAVED SUCCESSFULLY")

    def savetoexisted(self):
        """ save predictions to existed files"""
        if self.predictions == "":
            msg.showerror("ERROR", "NO PREDICTIONS TO SAVE")
        else:
            pass

    def savepredictions(self):
        """ saves the predictions to a csv file"""
        if self.predictions == "":
            msg.showerror("ERROR", "NO PREDICTIONS TO SAVE")
        else:
            filenamesave = filedialog.asksaveasfilename(
                initialdir="/",
                title="Select file",
                filetypes=(("csv files", "*.csv"), ("all files", "*.*")))
            self.checktosave(filenamesave)

    def showpredictions(self):
        """ show predictions function """
        if self.predictions == "":
            msg.showerror("ERROR", "NO PREDICTIONS")
        else:
            msg.showinfo("PREDICTIONS", str(self.predictions))

    def check_columns(self):
        """ checks the columns name from the importrd .csv file """
        if all([
                item in self.df.columns for item in [
                    'PassengerId', 'Pclass', 'Name', 'Sex', 'Age', 'SibSp',
                    'Parch', 'Ticket', 'Fare', 'Cabin', 'Embarked'
                ]
        ]):
            self.statechange("disable")
            msg.showinfo("SUCCESS", "CSV FILE ADDED SUCCESSFULLY")
            self.importeddf = pd.read_csv(self.filename)
        else:
            self.filename = ""
            msg.showerror("ERROR", "NO PROPER CSV ")

    def exitmenu(self):
        """ exit menu function """
        if msg.askokcancel("Quit?", "Really quit?"):
            self.master.destroy()

    def fixinsertedfile(self):
        """ 
        Creates a numpy array in order to make the predictions.
        Returns:
            X: numpy array ready to make the predictions
        
        """
        self.importeddf['Age'] = self.importeddf['Age'].fillna(
            self.importeddf['Age'].mean())
        self.importeddf['Fare'] = self.importeddf['Fare'].fillna(
            self.importeddf['Fare'].mean())
        agelabels = ['child', 'adult', 'old']
        self.importeddf['age_group'] = pd.cut(self.importeddf['Age'],
                                              bins=3,
                                              labels=agelabels)
        self.importeddf['age_group'] = self.importeddf['age_group'].fillna(
            'adult')
        labelsfare = ['cheap', 'normal', 'expensive']
        self.importeddf['Fare_group'] = pd.cut(self.importeddf['Fare'],
                                               bins=3,
                                               labels=labelsfare)
        self.importeddf['Fare_group'] = self.importeddf['Fare_group'].fillna(
            'cheap')
        self.importeddf.drop(columns=[
            'PassengerId', 'Name', 'Cabin', 'Embarked', 'Ticket', 'Fare', 'Age'
        ],
                             inplace=True)
        X = self.importeddf.iloc[:, :].values
        ct = ColumnTransformer(transformers=[('encoder', OneHotEncoder(),
                                              [1, 4, -1])],
                               remainder='passthrough')
        X = np.array(ct.fit_transform(X))
        sc = StandardScaler()
        X[:, 2:] = sc.fit_transform(X[:, 2:])
        return X

    def statechange(self, state):
        """ changes the state of buttons, texts etc.. """
        self.agetext.config(state=state)
        self.nametext.config(state=state)
        self.faretext.config(state=state)
        self.sexpopup.config(state=state)
        self.pclasspopup.config(state=state)
        self.embarkedpopup.config(state=state)
        self.noffammebtext.config(state=state)
        self.nofparentstext.config(state=state)

    def file_input_validation(self):
        """ user input validation"""
        if ".csv" in self.filename:
            self.df = pd.read_csv(self.filename)
            self.check_columns()
        else:
            self.filename = ""
            msg.showerror("ERROR", "NO CSV IMPORTED")

    def insertfile(self):
        """ insert csv function """
        if ".csv" in self.filename:
            msg.showerror("ERROR", "A CSV FILE IS ALREADY OPEN")
        else:
            self.filename = filedialog.askopenfilename(
                initialdir="/",
                title="Select csv file",
                filetypes=(("csv files", "*.csv"), ("all files", "*.*")))
            self.file_input_validation()

    def closefile(self):
        """ closes the csv file """
        if not ".csv" in self.filename:
            msg.showerror("ERROR", "NO CSV TO CLOSE")
        else:
            self.statechange("normal")
            self.filename = ""
            self.predictions = ""
            msg.showinfo("SUSSESS", "YOUR CSV FILE HAS SUCCESFULLY CLOSED")

    def checksetoptions(self, userinput):
        """ checks the user's options """
        if self.embarkedstring.get(
        ) != "Select a Port of Embarkation" and self.sexstring.get(
        ) != "Select a Sex" and self.pclassstring.get(
        ) != "Select a Ticket class":
            userinput.append([
                str(self.embarkedstring.get()),
                str(self.sexstring.get()),
                str(self.pclassstring.get())
            ])
        else:
            msg.showerror("VALUE ERROR", "SELECT A VALID OPTION")
            self.clearprediction("set")

    def checknumbers(self, userinput):
        """ checks if the user has inserted valid number inputs """
        if self.embarkedstring.get(
        ) != "Select a Port of Embarkation" and self.sexstring.get(
        ) != "Select a Sex" and self.pclassstring.get(
        ) != "Select a Ticket class":
            pass
        else:
            msg.showerror("VALUE ERROR", "ENTER VALID NUMBERS")
            self.clearprediction("number")

    def predict(self):
        """ predict button function """

        if self.filename != "" and self.predictions != "":
            msg.showerror("ERROR", "PREDICTIONS HAVE ALREADY BE DONE")
        elif self.filename != "":
            X = self.fixinsertedfile()
            self.predictions = self.loadedmodel.predict(X).tolist()
            answer = askyesno(title='Save predictions',
                              message='Do you want to save the predictions?')
            if answer:
                self.savepredictions()
            else:
                msg.showinfo("NO", "NO PREDICTIONS SAVED")
        else:
            userinput = []
            self.checksetoptions(userinput)
            self.checknumbers(userinput)

    def clear(self, toclear=None, textflag=True, text=""):
        """ reset button function """
        if toclear is None:
            self.pclassstring.set("Select a Ticket class")
            self.sexstring.set("Select a Sex")
            self.embarkedstring.set("Select a Port of Embarkation")
            self.noffammebtext.delete(1.0, END)
            self.agetext.delete(1.0, END)
            self.nametext.delete(1.0, END)
            self.faretext.delete(1.0, END)
            self.nofparentstext.delete(1.0, END)
        elif textflag:
            toclear.delete(1.0, END)
        else:
            toclear.set(str(text))

    def clearprediction(self, option):
        """ clear based on options """
        if option == "set":
            self.pclassstring.set("Select a Ticket class")
            self.sexstring.set("Select a Sex")
            self.embarkedstring.set("Select a Port of Embarkation")
        else:
            self.noffammebtext.delete(1.0, END)
            self.agetext.delete(1.0, END)
            self.nametext.delete(1.0, END)
            self.faretext.delete(1.0, END)
            self.nofparentstext.delete(1.0, END)
Example #60
0
class Application(tk.Frame):
    def __init__(self, master=None, bg=config.background_color):
        super().__init__(master)
        self.master = master
        self.master.configure(background="#1E1E1E")
        self.pack()
        self.create_widgets()
        self.limit_check()

    def create_fonts(self):
        self.font = tkFont.Font(family=config.font,
                                weight=config.font_weight,
                                size=config.font_size)
        self.font_large = tkFont.Font(family=config.font,
                                      weight=config.font_weight,
                                      size=round(config.font_size * 1.5))
        self.font_small = tkFont.Font(family=config.font,
                                      weight=config.font_weight,
                                      size=round(config.font_size * .66))

    def create_variables(self):
        # Set up StringVars that will be used.
        self.ticker_value = StringVar()
        self.account_value_text = StringVar()
        self.account_value_text.set(str(account_value))
        self.last_price_value = StringVar()
        self.current_position_value = StringVar()
        self.current_position_pnl = StringVar()
        self.account_value_pnl = StringVar()
        self.limit_price = StringVar()
        self.order_type = StringVar(None, 'market')

    # Create tkinter widgets.
    def create_widgets(self):
        self.create_fonts()
        self.create_variables()

        # Global is_playing as it is used as a boolean and StringVar
        global is_playing
        is_playing = StringVar()
        is_playing.set("▶")

        # Create Ticker Label for Ticker
        self.ticker_id = tk.Label(self,
                                  textvariable=self.ticker_value,
                                  fg=config.color_white,
                                  bg=config.background_color,
                                  font=self.font_large).grid(row=0,
                                                             column=0,
                                                             columnspan=4,
                                                             padx=33,
                                                             sticky="nsew")

        # Create a label to show the last price
        self.last_price_label = tk.Label(self,
                                         textvariable=self.last_price_value,
                                         bg=config.background_color,
                                         fg=config.color_white,
                                         font=self.font_large).grid(
                                             row=1,
                                             column=0,
                                             columnspan=4,
                                             sticky="nsew")

        # Create a button to start the reply
        self.play_button = tk.Button(self,
                                     textvariable=is_playing,
                                     bg=config.button_color_light,
                                     fg=config.color_grey,
                                     borderwidth=0)

        self.play_button["command"] = self.play_replay
        self.play_button.grid(row=2, column=0, columnspan=2, sticky="nsew")

        # Create a button for progressing to next bar
        self.next_button = tk.Button(self,
                                     text="▮▶",
                                     bg=config.button_color_light,
                                     fg=config.color_grey,
                                     borderwidth=0)
        self.next_button["command"] = self.next_bar
        self.next_button.grid(row=2, column=2, columnspan=2, sticky="nsew")

        # Create a button for long orders
        self.long_button = tk.Button(self,
                                     text="BUY",
                                     font=self.font,
                                     bg=config.button_color,
                                     fg=config.color_green,
                                     borderwidth=0)
        self.long_button["command"] = self.order_buy
        self.long_button.grid(row=3, column=0, columnspan=2, sticky="nsew")

        # Create a button for short orders
        self.short_button = tk.Button(self,
                                      text="SELL",
                                      font=self.font,
                                      bg=config.button_color,
                                      fg=config.color_red,
                                      borderwidth=0)
        self.short_button["command"] = self.order_sell
        self.short_button.grid(row=3, column=2, columnspan=2, sticky="nsew")

        # Create radio buttons to toggle between limit orders and market orders
        self.limit_radiobutton = tk.Radiobutton(
            self,
            bg=config.background_color,
            fg=config.color_dark_grey,
            selectcolor=config.background_color,
            text="LIMIT",
            variable=self.order_type,
            value="limit")
        self.limit_radiobutton.grid(row=4,
                                    column=0,
                                    columnspan=2,
                                    sticky="nsew")

        self.market_radiobutton = tk.Radiobutton(
            self,
            bg=config.background_color,
            fg=config.color_dark_grey,
            selectcolor=config.background_color,
            text="MARKET",
            variable=self.order_type,
            value="market",
        ).grid(row=4, column=2, columnspan=2, sticky="nsew")

        # Create entry box for limit orders
        self.limit_price = tk.Entry(self,
                                    borderwidth=0,
                                    bg=config.button_color_light,
                                    fg=config.color_grey)
        self.limit_price.insert(0, " ")
        self.limit_price.grid(row=5,
                              column=0,
                              columnspan=3,
                              sticky="nsew",
                              padx=5)

        self.limit_copy_button = tk.Button(self,
                                           text="LAST",
                                           borderwidth=0,
                                           bg=config.button_color,
                                           fg=config.color_grey,
                                           font=self.font_small)
        self.limit_copy_button["command"] = self.copy_last
        self.limit_copy_button.grid(row=5,
                                    column=3,
                                    columnspan=1,
                                    sticky="nsew")

        self.current_position_label = tk.Label(self,
                                               text="Current Position",
                                               anchor="w",
                                               bg=config.background_color,
                                               fg=config.color_grey,
                                               font=self.font_small).grid(
                                                   row=6,
                                                   column=0,
                                                   columnspan=4,
                                                   sticky="nsew")

        self.current_position_value_label = tk.Label(
            self,
            textvariable=self.current_position_value,
            anchor="w",
            bg=config.button_color_light,
            fg=config.color_dark_grey).grid(row=7,
                                            column=0,
                                            columnspan=3,
                                            sticky="nsew")

        self.current_position_pnl_label = tk.Label(
            self,
            textvariable=self.current_position_pnl,
            anchor="e",
            bg=config.button_color_light,
            fg=config.color_dark_grey).grid(row=7,
                                            column=3,
                                            columnspan=1,
                                            sticky="nsew")

        self.account_value_label = tk.Label(self,
                                            text="Account value",
                                            anchor="w",
                                            bg=config.background_color,
                                            fg=config.color_grey,
                                            font=self.font_small).grid(
                                                row=8,
                                                column=0,
                                                columnspan=4,
                                                sticky="nsew")

        self.account_value_value_label = tk.Label(
            self,
            textvariable=self.account_value_text,
            bg=config.button_color_light,
            fg=config.color_white,
            anchor="w").grid(row=9, column=0, columnspan=3, sticky="nsew")

        self.account_value_pnl_label = tk.Label(
            self,
            textvariable=self.account_value_pnl,
            bg=config.button_color_light,
            fg=config.color_dark_grey,
            anchor="e").grid(row=9, column=3, columnspan=1, sticky="nsew")

        self.trade_history_label = tk.Label(self,
                                            text="Trades",
                                            anchor="w",
                                            bg=config.background_color,
                                            fg=config.color_grey,
                                            font=self.font_small).grid(
                                                row=10,
                                                column=0,
                                                columnspan=3,
                                                sticky="nsew")

        self.trade_history_clear = tk.Button(self,
                                             text="Clear",
                                             bg=config.button_color,
                                             fg=config.color_grey,
                                             font=self.font_small,
                                             borderwidth=0)
        self.trade_history_clear.grid(row=10,
                                      column=3,
                                      columnspan=1,
                                      sticky="nsew")
        self.trade_history_clear['command'] = self.clear_list

        self.trade_history_list = tk.Listbox(self,
                                             fg=config.color_grey,
                                             bg=config.textarea_color,
                                             borderwidth=0)
        self.trade_history_list.grid(row=11,
                                     column=0,
                                     columnspan=4,
                                     sticky="nsew")

    # Write Timestamp to csv file
    write([time.strftime("%Y-%m-%d %H:%M")])

    # Start of Functions
    def message_box(self):
        messagebox.showinfo(
            'Error', 'Sorry! Limit orders are not currently implemented.\n'
            'You can check progress here:\n'
            'https://github.com/Robswc/tradingview-trainer/issues/5')
        self.order_type.set('market')

    # Generic function to show error
    def show_error(self, cause, exception, message):
        messagebox.showerror(str(cause), str(str(exception) + '\n' + message))
        driver.get("https://github.com/Robswc/tradingview-trainer/wiki/Errors")

    def clear_list(self):
        clear_csv()
        self.update_labels()

    def get_ticker(self):
        #ticker = driver.find_element_by_xpath(
        #    '/html/body/div[1]/div[1]/div[3]/div[1]/div/table/tr[1]/td[2]/div/div[3]/div[1]/span[2]/div/div[1]/div'
        #).text
        try:
            ticker = driver.find_element_by_xpath(
                '/html/body/div[1]/div[1]/div[3]/div[1]/div/table/tr[1]/td[2]/div/div[2]/div[1]/div[1]/div[1]/div[1]'
            ).text
            ticker = str(ticker).split(' ')

            print(ticker[0])
            return str(ticker[0])
        except:
            return 'None'

    def get_price_data(self, request):
        try:
            if request == 'o':
                return float(
                    driver.find_element_by_xpath(
                        '/html/body/div[1]/div[1]/div[3]/div[1]/div/table/tr[1]/td[2]/div/div[3]/div[1]/div[2]/div/div[1]/div[2]'
                    ).text)

            if request == 'h':
                return float(
                    driver.find_element_by_xpath(
                        '/html/body/div[1]/div[1]/div[3]/div[1]/div/table/tr[1]/td[2]/div/div[3]/div[1]/div[2]/div/div[2]/div[2]'
                    ).text)

            if request == 'l':
                return float(
                    driver.find_element_by_xpath(
                        '/html/body/div[1]/div[1]/div[3]/div[1]/div/table/tr[1]/td[2]/div/div[3]/div[1]/div[2]/div/div[3]/div[2]'
                    ).text)

            if request == 'c':
                return float(
                    driver.find_element_by_xpath(
                        '/html/body/div[1]/div[1]/div[3]/div[1]/div/table/tr[1]/td[2]/div/div[3]/div[1]/div[2]/div/div[4]/div[2]'
                    ).text)
        except:
            return 0

    def get_limit_price(self):
        self.limit_price.get()

    def get_position_pnl(self):
        if get_position()['quantity'] < 0:
            pnl_percent = ((get_position()['entry'] - self.get_last_price()) /
                           get_position()['entry']) * 100
        if get_position()['quantity'] > 0:
            pnl_percent = ((self.get_last_price() - get_position()['entry']) /
                           self.get_last_price()) * 100

        try:
            return round(pnl_percent, 2)
        except:
            return 0

    # Doesn't seem to work :(
    def add_marker(self):
        pass
        # actions = ActionChains(driver)
        # element = driver.find_element_by_xpath('/html/body/div[1]/div[1]/div[3]/div[1]/div/table/tr[1]')
        # element.click()
        # actions.click(element).key_down(Keys.ALT, 'v').perform()

    def update_labels(self):

        # update all labels via tk StringVar()
        self.last_price_value.set(str(self.get_last_price()))
        self.current_position_pnl.set(str(self.get_position_pnl()) + '%')
        self.account_value_pnl.set(
            str(
                round(
                    percent_change(get_account_value(),
                                   float(config.initial_amount)), 2)) + '%')
        self.current_position_value.set(
            str(get_position()['quantity']) + " @ " +
            str(get_position()['entry']))
        self.account_value_text.set(
            locale.currency(get_account_value(), grouping=True))
        self.ticker_value.set(self.get_ticker())

        # Update trade history box
        self.trade_history_list.delete(0, 'end')
        for trade in read_all():
            self.trade_history_list.insert(0, trade)

    # get last price via xpath
    def get_last_price(self):
        try:
            last_price = driver.find_element_by_xpath(
                '/html/body/div[1]/div[1]/div[3]/div[1]/div/table/tr[1]/td[2]/div/div[2]/div[1]/div[2]/div/div[4]/div[2]'
            ).text
            return float(last_price)
        except:
            try:
                last_price = driver.find_element_by_xpath(
                    config.custom_xpath_last_price).text
                return float(last_price)
            except Exception as error:
                pass

#              self.show_error('last_value', str(error), 'Please report error here: ')

# function to pass buy order to order engine.

    def order_buy(self):
        oe = OrderEngine
        if self.order_type.get() == 'market':
            oe.market(OrderEngine, round(get_account_value(), 2),
                      self.get_last_price())
        if self.order_type.get() == 'limit':
            print('LIMIT BIMIT ORDER HEHEH')
            oe.limit(OrderEngine, round(get_account_value(), 2),
                     float(self.limit_price.get()), self.get_last_price())
        self.update_labels()

    # function to pass sell order to order engine.
    def order_sell(self):
        oe = OrderEngine
        if self.order_type.get() == 'market':
            print(type(get_account_value()), type(self.get_last_price()))
            oe.market(OrderEngine,
                      round(get_account_value(), 2) * -1,
                      float(self.get_last_price()))
        if self.order_type.get() == 'limit':
            oe.limit(OrderEngine,
                     get_account_value() * -1, float(self.limit_price.get()),
                     self.get_last_price())
        self.update_labels()

    # Check with the order engine to see if there is a limit order.
    def limit_check(self):
        oe = OrderEngine
        oe.on_tick(OrderEngine, self.get_price_data('o'),
                   self.get_price_data('h'), self.get_price_data('l'),
                   self.get_price_data('c'))
        global is_playing
        print(str(is_playing.get()))

        if str(is_playing.get()) == "▮▮":
            print(str(is_playing.get()))
            self.after(500, self.limit_check)

    # Function to auto-fill last price into limit price.
    def copy_last(self):
        self.limit_price.delete(0, "end")
        self.limit_price.insert(0, self.last_price_value.get())

    # Click next bar w/selenium, use functions to grab values.
    def next_bar(self):
        print(self.limit_price.get())
        global is_playing
        try:
            driver.find_element_by_xpath(
                '/html/body/div[7]/div/div[2]/div[3]/div').click()
        except:
            try:
                driver.find_element_by_xpath(
                    config.custom_xpath_replay).click()
            except:
                self.show_error('next_bar', 'xpath error',
                                'Please report error here: ')

        is_playing.set("▶")
        self.limit_check()
        self.update_labels()
        print('>>')

    # Function to click the play-replay with selenium, check for limit orders.
    def play_replay(self):
        global is_playing
        self.update_labels()
        try:
            driver.find_element_by_xpath(
                '/html/body/div[9]/div/div[2]/div[2]/div').click()
        except Exception:
            driver.find_element_by_xpath(
                config.custom_xpath_play_replay).click()
        print(str(is_playing.get()))
        if str(is_playing.get()) == "▶":
            is_playing.set("▮▮")
            print(str(is_playing))
            self.limit_check()
        else:
            is_playing.set("▶")
            print(str(is_playing))