当前位置: 首页>>代码示例>>Python>>正文


Python Entry.get方法代码示例

本文整理汇总了Python中tkinter.ttk.Entry.get方法的典型用法代码示例。如果您正苦于以下问题:Python Entry.get方法的具体用法?Python Entry.get怎么用?Python Entry.get使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在tkinter.ttk.Entry的用法示例。


在下文中一共展示了Entry.get方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: DateWidget

# 需要导入模块: from tkinter.ttk import Entry [as 别名]
# 或者: from tkinter.ttk.Entry import get [as 别名]
 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="")
开发者ID:JoelSjogren,项目名称:horoskop,代码行数:35,代码来源:main.py

示例2: apagar_caracter_invalido

# 需要导入模块: from tkinter.ttk import Entry [as 别名]
# 或者: from tkinter.ttk.Entry import get [as 别名]
 def apagar_caracter_invalido(evento_char, ref_entry: ttk.Entry, caracteres_inválidos: str):
     """ Método estático para apagar os caracteres inseridos em um Entry no momento da digitação(evento Release).
     Pode ser usado sem instanciação.
     :param evento_char: event.char do evento.
     :param ref_entry: Referência do componente Entry.
     :param caracteres_inválidos: string de caracteres que deseja-se que sejam apagados.
     :return: none. """
     if evento_char in caracteres_inválidos:
         ref_entry.delete(len(ref_entry.get()) - 1, 'end')
开发者ID:paulocsilvajr,项目名称:python-code,代码行数:11,代码来源:controle_contas.py

示例3: Main

# 需要导入模块: from tkinter.ttk import Entry [as 别名]
# 或者: from tkinter.ttk.Entry import get [as 别名]
class Main(Frame):
    """Main class for our browser.
        Note that we inherit from Frame, making this a Frame object.
    """
    def __init__(self, master):
        Frame.__init__(self, master)
        self.master = master
        self.master.title("Browser")
        self.header = {"User-Agent":"Tkinter Browser 0.1"}

        # Here we make our widgets.
        self.top_frame = Frame(self)
        self.url_frame = Frame(self.top_frame)
        self.url_label = Label(self.url_frame, text="Url: ", anchor="n")
        self.url_entry = Entry(self.url_frame, width=80)
        self.url_button = Button(self.url_frame, text="Go", command=self.go_button)
        self.bottom_frame = Frame(self)
        self.text_field = Text(self.bottom_frame)

        #Here we pack our widgets.
        self.top_frame.pack(side="top", padx=15, pady=15)
        self.url_frame.pack(anchor="center")
        self.bottom_frame.pack(side="bottom", fill="both", expand=True)
        self.text_field.pack(side="bottom", fill="both", expand=True)
        self.url_label.pack(side="left")
        self.url_entry.pack(side="left", fill="x", expand=True)
        self.url_button.pack(side="left", padx=5)
        self.text_field.config(state="disabled", padx=5, pady=5)

    def go_button(self):
        url = self.url_entry.get()
        if url:
            if "http://" not in url:
                url = "http://"+url
            page_text = self.get_page(url)
            self.text_field.config(state="normal")
            self.text_field.delete(1.0, "end")
            self.text_field.insert("end", page_text)
            self.text_field.config(state="disable")

    def get_page(self, url):
        s = requests.Session()
        resp = s.get(url, headers=self.header)
        data = resp.text
        soup = bs(data, "html.parser")
        page_text = soup.find_all(text=True)
        page_text = filter(self.visible, page_text)
        return "".join([str(i)+'\n' for i in page_text])


    def visible(self, e):
        if e.parent.name in ('style', 'script', '[document]', 'head', 'title'):
            return False
        elif re.match('<!--.*-->', str(e.encode('utf-8'))):
            return False
        return True
开发者ID:Exodus111,项目名称:Projects,代码行数:58,代码来源:browser.py

示例4: MyTestDialog

# 需要导入模块: from tkinter.ttk import Entry [as 别名]
# 或者: from tkinter.ttk.Entry import get [as 别名]
class MyTestDialog( ModalDialog ):

    def body( self, master ):
        """
        Override the empty ModalDialog.body function
            to set up the dialog how we want it.
        """
        from tkinter.ttk import Label, Entry

        Label( master, text="First:" ).grid( row=0 )
        Label( master, text="Second:" ).grid( row=1 )

        self.e1 = Entry( master )
        self.e2 = Entry( master )

        self.e1.grid( row=0, column=1 )
        self.e2.grid( row=1, column=1 )
        return self.e1 # initial focus
    # end of MyTestDialog.apply


    def validate( self ):
        """
        Override the empty ModalDialog.validate function
            to check that the results are how we need them.
        """
        try: int( self.e1.get() ) and int( self.e2.get() )
        except ValueError:
            print( "ERROR: We need two valid integers!" )
            return False
        return True
    # end of MyTestDialog.validate


    def apply( self ):
        """
        Override the empty ModalDialog.apply function
            to process the results how we need them.
        """
        first = int( self.e1.get() )
        second = int( self.e2.get() )
        print( first, second ) # or something
        self.result = (first, second,)
开发者ID:alerque,项目名称:Biblelator,代码行数:45,代码来源:ModalDialog.py

示例5: escrever_mascara_entry

# 需要导入模块: from tkinter.ttk import Entry [as 别名]
# 或者: from tkinter.ttk.Entry import get [as 别名]
    def escrever_mascara_entry(evento_char, ref_entry: ttk.Entry, mascara: str, especial: str = ''):
        """ Método estático para formatar a entrada de um Entry de acordo com mascara.
        Pode ser usado sem instanciação.
        :param evento_char: event.char do evento.
        :param ref_entry: Referência do componente Entry.
        :param mascara: Mascara base para a formatação. Deve apresentar espacos onde quer ser inseridos os números.
        :return: none. """
        # Apaga o Entry caso o conteúdo seja o default.
        if ref_entry.get() == mascara:
            ref_entry.delete(0, 'end')

        # O event.char captura de tecla literalmente, mas não captura teclas de controle(Backspace, ...).
        # O event.keysym usa uma nomenclatura diferente, e captura todas as teclas.
        # Tkinter 8.5 reference gui for Python. 161-162.
        if evento_char in string.digits or evento_char in especial:
            pos = len(ref_entry.get())
            try:
                if mascara[pos] != ' ':
                    ref_entry.insert('end', mascara[pos])
            except IndexError:
                ref_entry.delete(0, 'end')
开发者ID:paulocsilvajr,项目名称:python-code,代码行数:23,代码来源:controle_contas.py

示例6: Query

# 需要导入模块: from tkinter.ttk import Entry [as 别名]
# 或者: from tkinter.ttk.Entry import get [as 别名]
class Query(Toplevel):
    """Base class for getting verified answer from a user.

    For this base class, accept any non-blank string.
    """
    def __init__(self, parent, title, message, *, text0='', used_names={},
                 _htest=False, _utest=False):
        """Create popup, do not return until tk widget destroyed.

        Additional subclass init must be done before calling this
        unless  _utest=True is passed to suppress wait_window().

        title - string, title of popup dialog
        message - string, informational message to display
        text0 - initial value for entry
        used_names - names already in use
        _htest - bool, change box location when running htest
        _utest - bool, leave window hidden and not modal
        """
        Toplevel.__init__(self, parent)
        self.withdraw()  # Hide while configuring, especially geometry.
        self.parent = parent
        self.title(title)
        self.message = message
        self.text0 = text0
        self.used_names = used_names
        self.transient(parent)
        self.grab_set()
        windowingsystem = self.tk.call('tk', 'windowingsystem')
        if windowingsystem == 'aqua':
            try:
                self.tk.call('::tk::unsupported::MacWindowStyle', 'style',
                             self._w, 'moveableModal', '')
            except:
                pass
            self.bind("<Command-.>", self.cancel)
        self.bind('<Key-Escape>', self.cancel)
        self.protocol("WM_DELETE_WINDOW", self.cancel)
        self.bind('<Key-Return>', self.ok)
        self.bind("<KP_Enter>", self.ok)
        self.resizable(height=False, width=False)
        self.create_widgets()
        self.update_idletasks()  # Needed here for winfo_reqwidth below.
        self.geometry(  # Center dialog over parent (or below htest box).
                "+%d+%d" % (
                    parent.winfo_rootx() +
                    (parent.winfo_width()/2 - self.winfo_reqwidth()/2),
                    parent.winfo_rooty() +
                    ((parent.winfo_height()/2 - self.winfo_reqheight()/2)
                    if not _htest else 150)
                ) )
        if not _utest:
            self.deiconify()  # Unhide now that geometry set.
            self.wait_window()

    def create_widgets(self):  # Call from override, if any.
        # Bind to self widgets needed for entry_ok or unittest.
        self.frame = frame = Frame(self, padding=10)
        frame.grid(column=0, row=0, sticky='news')
        frame.grid_columnconfigure(0, weight=1)

        entrylabel = Label(frame, anchor='w', justify='left',
                           text=self.message)
        self.entryvar = StringVar(self, self.text0)
        self.entry = Entry(frame, width=30, textvariable=self.entryvar)
        self.entry.focus_set()
        self.error_font = Font(name='TkCaptionFont',
                               exists=True, root=self.parent)
        self.entry_error = Label(frame, text=' ', foreground='red',
                                 font=self.error_font)
        self.button_ok = Button(
                frame, text='OK', default='active', command=self.ok)
        self.button_cancel = Button(
                frame, text='Cancel', command=self.cancel)

        entrylabel.grid(column=0, row=0, columnspan=3, padx=5, sticky=W)
        self.entry.grid(column=0, row=1, columnspan=3, padx=5, sticky=W+E,
                        pady=[10,0])
        self.entry_error.grid(column=0, row=2, columnspan=3, padx=5,
                              sticky=W+E)
        self.button_ok.grid(column=1, row=99, padx=5)
        self.button_cancel.grid(column=2, row=99, padx=5)

    def showerror(self, message, widget=None):
        #self.bell(displayof=self)
        (widget or self.entry_error)['text'] = 'ERROR: ' + message

    def entry_ok(self):  # Example: usually replace.
        "Return non-blank entry or None."
        self.entry_error['text'] = ''
        entry = self.entry.get().strip()
        if not entry:
            self.showerror('blank line.')
            return None
        return entry

    def ok(self, event=None):  # Do not replace.
        '''If entry is valid, bind it to 'result' and destroy tk widget.

        Otherwise leave dialog open for user to correct entry or cancel.
#.........这里部分代码省略.........
开发者ID:1st1,项目名称:cpython,代码行数:103,代码来源:query.py

示例7: HelpSource

# 需要导入模块: from tkinter.ttk import Entry [as 别名]
# 或者: from tkinter.ttk.Entry import get [as 别名]
class HelpSource(Query):
    "Get menu name and help source for Help menu."
    # Used in ConfigDialog.HelpListItemAdd/Edit, (941/9)

    def __init__(self, parent, title, *, menuitem='', filepath='',
                 used_names={}, _htest=False, _utest=False):
        """Get menu entry and url/local file for Additional Help.

        User enters a name for the Help resource and a web url or file
        name. The user can browse for the file.
        """
        self.filepath = filepath
        message = 'Name for item on Help menu:'
        super().__init__(
                parent, title, message, text0=menuitem,
                used_names=used_names, _htest=_htest, _utest=_utest)

    def create_widgets(self):
        super().create_widgets()
        frame = self.frame
        pathlabel = Label(frame, anchor='w', justify='left',
                          text='Help File Path: Enter URL or browse for file')
        self.pathvar = StringVar(self, self.filepath)
        self.path = Entry(frame, textvariable=self.pathvar, width=40)
        browse = Button(frame, text='Browse', width=8,
                        command=self.browse_file)
        self.path_error = Label(frame, text=' ', foreground='red',
                                font=self.error_font)

        pathlabel.grid(column=0, row=10, columnspan=3, padx=5, pady=[10,0],
                       sticky=W)
        self.path.grid(column=0, row=11, columnspan=2, padx=5, sticky=W+E,
                       pady=[10,0])
        browse.grid(column=2, row=11, padx=5, sticky=W+S)
        self.path_error.grid(column=0, row=12, columnspan=3, padx=5,
                             sticky=W+E)

    def askfilename(self, filetypes, initdir, initfile):  # htest #
        # Extracted from browse_file so can mock for unittests.
        # Cannot unittest as cannot simulate button clicks.
        # Test by running htest, such as by running this file.
        return filedialog.Open(parent=self, filetypes=filetypes)\
               .show(initialdir=initdir, initialfile=initfile)

    def browse_file(self):
        filetypes = [
            ("HTML Files", "*.htm *.html", "TEXT"),
            ("PDF Files", "*.pdf", "TEXT"),
            ("Windows Help Files", "*.chm"),
            ("Text Files", "*.txt", "TEXT"),
            ("All Files", "*")]
        path = self.pathvar.get()
        if path:
            dir, base = os.path.split(path)
        else:
            base = None
            if platform[:3] == 'win':
                dir = os.path.join(os.path.dirname(executable), 'Doc')
                if not os.path.isdir(dir):
                    dir = os.getcwd()
            else:
                dir = os.getcwd()
        file = self.askfilename(filetypes, dir, base)
        if file:
            self.pathvar.set(file)

    item_ok = SectionName.entry_ok  # localize for test override

    def path_ok(self):
        "Simple validity check for menu file path"
        path = self.path.get().strip()
        if not path: #no path specified
            self.showerror('no help file path specified.', self.path_error)
            return None
        elif not path.startswith(('www.', 'http')):
            if path[:5] == 'file:':
                path = path[5:]
            if not os.path.exists(path):
                self.showerror('help file path does not exist.',
                               self.path_error)
                return None
            if platform == 'darwin':  # for Mac Safari
                path =  "file://" + path
        return path

    def entry_ok(self):
        "Return apparently valid (name, path) or None"
        self.entry_error['text'] = ''
        self.path_error['text'] = ''
        name = self.item_ok()
        path = self.path_ok()
        return None if name is None or path is None else (name, path)
开发者ID:1st1,项目名称:cpython,代码行数:94,代码来源:query.py

示例8: Query

# 需要导入模块: from tkinter.ttk import Entry [as 别名]
# 或者: from tkinter.ttk.Entry import get [as 别名]
class Query(Toplevel):
    """Base class for getting verified answer from a user.

    For this base class, accept any non-blank string.
    """
    def __init__(self, parent, title, message, *, text0='', used_names={},
                 _htest=False, _utest=False):
        """Create popup, do not return until tk widget destroyed.

        Additional subclass init must be done before calling this
        unless  _utest=True is passed to suppress wait_window().

        title - string, title of popup dialog
        message - string, informational message to display
        text0 - initial value for entry
        used_names - names already in use
        _htest - bool, change box location when running htest
        _utest - bool, leave window hidden and not modal
        """
        Toplevel.__init__(self, parent)
        self.withdraw()  # Hide while configuring, especially geometry.
        self.configure(borderwidth=5)
        self.resizable(height=False, width=False)
        self.title(title)
        self.transient(parent)
        self.grab_set()
        self.bind('<Key-Return>', self.ok)
        self.bind('<Key-Escape>', self.cancel)
        self.protocol("WM_DELETE_WINDOW", self.cancel)
        self.parent = parent
        self.message = message
        self.text0 = text0
        self.used_names = used_names
        self.create_widgets()
        self.update_idletasks()  # Needed here for winfo_reqwidth below.
        self.geometry(  # Center dialog over parent (or below htest box).
                "+%d+%d" % (
                    parent.winfo_rootx() +
                    (parent.winfo_width()/2 - self.winfo_reqwidth()/2),
                    parent.winfo_rooty() +
                    ((parent.winfo_height()/2 - self.winfo_reqheight()/2)
                    if not _htest else 150)
                ) )
        if not _utest:
            self.deiconify()  # Unhide now that geometry set.
            self.wait_window()

    def create_widgets(self):  # Call from override, if any.
        # Bind to self widgets needed for entry_ok or unittest.
        self.frame = frame = Frame(self, borderwidth=2, relief='sunken', )
        entrylabel = Label(frame, anchor='w', justify='left',
                           text=self.message)
        self.entryvar = StringVar(self, self.text0)
        self.entry = Entry(frame, width=30, textvariable=self.entryvar)
        self.entry.focus_set()

        buttons = Frame(self)
        self.button_ok = Button(buttons, text='Ok',
                width=8, command=self.ok)
        self.button_cancel = Button(buttons, text='Cancel',
                width=8, command=self.cancel)

        frame.pack(side='top', expand=True, fill='both')
        entrylabel.pack(padx=5, pady=5)
        self.entry.pack(padx=5, pady=5)
        buttons.pack(side='bottom')
        self.button_ok.pack(side='left', padx=5)
        self.button_cancel.pack(side='right', padx=5)

    def entry_ok(self):  # Example: usually replace.
        "Return non-blank entry or None."
        entry = self.entry.get().strip()
        if not entry:
            showerror(title='Entry Error',
                    message='Blank line.', parent=self)
            return None
        return entry

    def ok(self, event=None):  # Do not replace.
        '''If entry is valid, bind it to 'result' and destroy tk widget.

        Otherwise leave dialog open for user to correct entry or cancel.
        '''
        entry = self.entry_ok()
        if entry is not None:
            self.result = entry
            self.destroy()
        else:
            # [Ok] moves focus.  (<Return> does not.)  Move it back.
            self.entry.focus_set()

    def cancel(self, event=None):  # Do not replace.
        "Set dialog result to None and destroy tk widget."
        self.result = None
        self.destroy()
开发者ID:SharSmall,项目名称:cpython,代码行数:97,代码来源:query.py

示例9: Example

# 需要导入模块: from tkinter.ttk import Entry [as 别名]
# 或者: from tkinter.ttk.Entry import get [as 别名]
class Example(Frame):
    def __init__(self, parent, q):
        Frame.__init__(self, parent)
        self.queue = q
        self.parent = parent
        self.initUI()

    def initUI(self):
        self.parent.title("Pi computation")
        self.pack(fill=BOTH, expand=True)

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

        lbl1 = Label(self, text="Digits:")
        lbl1.grid(row=0, column=0, sticky=E, padx=10, pady=10)

        self.ent1 = Entry(self, width=10)
        self.ent1.insert(END, "4000")
        self.ent1.grid(row=0, column=1, sticky=W)

        lbl2 = Label(self, text="Accuracy:")
        lbl2.grid(row=0, column=2, sticky=E, padx=10, pady=10)

        self.ent2 = Entry(self, width=10)
        self.ent2.insert(END, "100")
        self.ent2.grid(row=0, column=3, sticky=W)

        self.startBtn = Button(self, text="Start",
                               command=self.onStart)
        self.startBtn.grid(row=1, column=0, padx=10, pady=5, sticky=W)

        self.pbar = Progressbar(self, mode='indeterminate')
        self.pbar.grid(row=1, column=1, columnspan=3, sticky=W+E)

        self.txt = scrolledtext.ScrolledText(self)
        self.txt.grid(row=2, column=0, rowspan=4, padx=10, pady=5,
                      columnspan=5, sticky=E+W+S+N)

    def onStart(self):
        self.startBtn.config(state=DISABLED)
        self.txt.delete("1.0", END)

        self.digits = int(self.ent1.get())
        self.accuracy = int(self.ent2.get())

        self.p1 = Process(target=self.generatePi, args=(self.queue,))
        self.p1.start()
        self.pbar.start(DELAY2)
        self.after(DELAY1, self.onGetValue)

    def onGetValue(self):
        if (self.p1.is_alive()):
            self.after(DELAY1, self.onGetValue)
            return
        else:
            try:
                self.txt.insert('end', self.queue.get(0))
                self.txt.insert('end', "\n")
                self.pbar.stop()
                self.startBtn.config(state=NORMAL)
            except queue.Empty:
                print("queue is empty")

    def generatePi(self, queue):
        getcontext().prec = self.digits
        time.sleep(10)

        pi = Decimal(0)
        k = 0
        n = self.accuracy

        while k < n:
            pi += (Decimal(1)/(16**k))*((Decimal(4)/(8*k+1)) -
                                        (Decimal(2)/(8*k+4)) -
                                        (Decimal(1)/(8*k+5)) -
                                        (Decimal(1)/(8*k+6)))
            k += 1
            print(self.p1.is_alive())

        queue.put(pi)
        print("end")
开发者ID:chengyi818,项目名称:kata,代码行数:84,代码来源:1_calculating_pi.py

示例10: CreateCustomer

# 需要导入模块: from tkinter.ttk import Entry [as 别名]
# 或者: from tkinter.ttk.Entry import get [as 别名]
class CreateCustomer(Frame):
  """Create customer screen"""
  
  def __init__(self, master):
    Frame.__init__(self,master)
    
    self.master = master
    self.frame = Frame(self.master)
    self.initUI()
  
  def initUI(self):
    self.master.title("3D Printer - Add Customer")
    self.style = Style()

    default_padding = {'padx': 10, 'pady' : 10}

    #TODO change alignment    
    #Left frame for labels
    self.left_frame = Frame(self.master)
    
    self.name_label = Label(self.left_frame, text = "Name", style="BW.TLabel")
    self.name_label.pack(default_padding)

    self.surname_label = Label(self.left_frame, text = "Surname", style="BW.TLabel")
    self.surname_label.pack(default_padding)    

    self.email_label = Label(self.left_frame, text = "Email", style="BW.TLabel")
    self.email_label.pack(default_padding)

    self.cellphone_label = Label(self.left_frame, text = "Cellphone", style="BW.TLabel")
    self.cellphone_label.pack(default_padding)

    #Right frame for entries
    self.right_frame = Frame(self.master)
    
    self.name_entry = Entry(self.right_frame)
    self.name_entry.pack(default_padding)    

    self.surname_entry = Entry(self.right_frame)
    self.surname_entry.pack(default_padding)

    self.email_entry = Entry(self.right_frame)
    self.email_entry.pack(default_padding)

    self.cellphone_entry = Entry(self.right_frame)
    self.cellphone_entry.pack(default_padding)
    
    #Bottom frame for button
    self.button_frame = Frame(self.master)
    self.create_customer_button = Button(self.button_frame, text = "Create Customer", command = self.save_customer)
    self.create_customer_button.pack(default_padding)

    self.button_frame.pack(side = BOTTOM, fill = "x", expand = True)
    self.left_frame.pack(side = LEFT, expand = True, fill = "y")
    self.right_frame.pack(side = RIGHT, expand = True, fill = "y")

    self.frame.pack()

  def save_customer(self):
    print("saving customer")

    self.customer = Customer(self.name_entry.get(), self.surname_entry.get(),
                             self.email_entry.get(), self.cellphone_entry.get())
    if not self.customer.validate():
      messagebox.showerror(message = "All fields are mandatory, please fill in all the fields")
      return
    
    db = TinyDB('db/db.json')
    self.customer_id = db.insert(self.customer.__dict__)
    
    #TODO redirect to next page
    self.go_to_execute_script()
  
  def go_to_execute_script(self):
    """redirect to next page"""
    
    self.execute_script = Toplevel(self, self.master)
    self.app = ExecuteScript(self.execute_script)
开发者ID:khlumzeemee,项目名称:3dprinter,代码行数:80,代码来源:Application.py

示例11: BookManagerUi

# 需要导入模块: from tkinter.ttk import Entry [as 别名]
# 或者: from tkinter.ttk.Entry import get [as 别名]
class BookManagerUi(Frame):

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

        self.parent = parent

        self.initUI()

        self.db = dao('blist') #데이터베이스 관리 클래스 생성


    def initUI(self):

        self.parent.title("Book Manager")
        self.style = Style()
        self.style.theme_use("default")
        self.pack(fill=BOTH, expand=1)

        self.columnconfigure(0, pad=3)
        self.columnconfigure(1, pad=3)
        self.columnconfigure(2, pad=3)
        self.rowconfigure(0, pad=3)
        self.rowconfigure(1, pad=3)
        self.rowconfigure(2, pad=3)
        self.rowconfigure(3, pad=3)
        self.rowconfigure(4, pad=3)
        self.rowconfigure(5, pad=3)
        self.rowconfigure(6, pad=3)


        self.input_bname=''
        self.input_aname=''
        self.input_price=0
        self.delete=''

        lb_bookname = Label(self, text="bookname:")
        lb_bookname.grid(row=0, column =0 ,sticky=W, pady=4, padx=5)

        self.entry_bookname = Entry(self)
        self.entry_bookname.grid(row=0, column = 1 )

        lb_author = Label(self, text="author:")
        lb_author.grid(row=0, column =2,sticky=W, pady=4, padx=5)

        self.entry_author = Entry(self)
        self.entry_author.grid(row=0, column = 3 )


        lb_price = Label(self, text="price:")
        lb_price.grid(row=0, column =4 ,sticky=W, pady=4, padx=5)

        self.entry_price = Entry(self)
        self.entry_price.grid(row=0, column = 5 ,padx=15)


        abtn = Button(self, text="Add", command=lambda:self.clicked_add())
        abtn.grid(row=0, column=6)

        sbtn = Button(self, text="Serach", command = lambda:self.clicked_search())
        sbtn.grid(row=1, column=6, pady=4)

        dbtn = Button(self, text="Delete", command = lambda:self.clicked_delete())
        dbtn.grid(row=2, column=6, pady=4)

        self.lb = Listbox(self)

        self.lb.grid(row=3,column = 0, columnspan = 6,rowspan= 4, sticky = E+W+S+N)
        self.lb.bind("<<ListboxSelect>>", self.onSelect)


    #삭제를 위한 select부분
    def onSelect(self,val):
        sender = val.widget
        idx = sender.curselection()
        value = sender.get(idx)

        self.delete = value

    # 데이터 추가 버튼
    def clicked_add(self):
        bname =self.entry_bookname.get()
        aname = self.entry_author.get()
        price = self.entry_price.get()

        self.lb.delete(0,END)


        # 입력받을 데이터가 모자란지 검사
        if(len(bname) >0 and len(aname)>0 and len(price)>0 ):
            #가격에 문자를 입력했을 경우 처리
            try:
                priceI = eval(price)
            except:
                self.lb.insert(END,"you input wrong price. it must be integer")

            #사용자가 입력한 내용중 중복된 책이름이 있을 경우(저자는 책이 여러가지일 수 있으니 제외)
            rec = self.db.excute_select(bname,'')
            if ( len(rec) >0):
                self.lb.insert(END,bname +" is already in the database")
#.........这里部分代码省略.........
开发者ID:hangyeolkim91,项目名称:python,代码行数:103,代码来源:bookmanager.py

示例12: HelpSource

# 需要导入模块: from tkinter.ttk import Entry [as 别名]
# 或者: from tkinter.ttk.Entry import get [as 别名]
class HelpSource(Query):
    "Get menu name and help source for Help menu."
    # Used in ConfigDialog.HelpListItemAdd/Edit, (941/9)

    def __init__(self, parent, title, *, menuitem="", filepath="", used_names={}, _htest=False, _utest=False):
        """Get menu entry and url/local file for Additional Help.

        User enters a name for the Help resource and a web url or file
        name. The user can browse for the file.
        """
        self.filepath = filepath
        message = "Name for item on Help menu:"
        super().__init__(parent, title, message, text0=menuitem, used_names=used_names, _htest=_htest, _utest=_utest)

    def create_widgets(self):
        super().create_widgets()
        frame = self.frame
        pathlabel = Label(frame, anchor="w", justify="left", text="Help File Path: Enter URL or browse for file")
        self.pathvar = StringVar(self, self.filepath)
        self.path = Entry(frame, textvariable=self.pathvar, width=40)
        browse = Button(frame, text="Browse", width=8, command=self.browse_file)

        pathlabel.pack(anchor="w", padx=5, pady=3)
        self.path.pack(anchor="w", padx=5, pady=3)
        browse.pack(pady=3)

    def askfilename(self, filetypes, initdir, initfile):  # htest #
        # Extracted from browse_file so can mock for unittests.
        # Cannot unittest as cannot simulate button clicks.
        # Test by running htest, such as by running this file.
        return filedialog.Open(parent=self, filetypes=filetypes).show(initialdir=initdir, initialfile=initfile)

    def browse_file(self):
        filetypes = [
            ("HTML Files", "*.htm *.html", "TEXT"),
            ("PDF Files", "*.pdf", "TEXT"),
            ("Windows Help Files", "*.chm"),
            ("Text Files", "*.txt", "TEXT"),
            ("All Files", "*"),
        ]
        path = self.pathvar.get()
        if path:
            dir, base = os.path.split(path)
        else:
            base = None
            if platform[:3] == "win":
                dir = os.path.join(os.path.dirname(executable), "Doc")
                if not os.path.isdir(dir):
                    dir = os.getcwd()
            else:
                dir = os.getcwd()
        file = self.askfilename(filetypes, dir, base)
        if file:
            self.pathvar.set(file)

    item_ok = SectionName.entry_ok  # localize for test override

    def path_ok(self):
        "Simple validity check for menu file path"
        path = self.path.get().strip()
        if not path:  # no path specified
            showerror(title="File Path Error", message="No help file path specified.", parent=self)
            return None
        elif not path.startswith(("www.", "http")):
            if path[:5] == "file:":
                path = path[5:]
            if not os.path.exists(path):
                showerror(title="File Path Error", message="Help file path does not exist.", parent=self)
                return None
            if platform == "darwin":  # for Mac Safari
                path = "file://" + path
        return path

    def entry_ok(self):
        "Return apparently valid (name, path) or None"
        name = self.item_ok()
        path = self.path_ok()
        return None if name is None or path is None else (name, path)
开发者ID:abalkin,项目名称:cpython,代码行数:80,代码来源:query.py

示例13: Query

# 需要导入模块: from tkinter.ttk import Entry [as 别名]
# 或者: from tkinter.ttk.Entry import get [as 别名]
class Query(Toplevel):
    """Base class for getting verified answer from a user.

    For this base class, accept any non-blank string.
    """

    def __init__(self, parent, title, message, *, _htest=False, _utest=False):  # Call from override.
        """Create popup, do not return until tk widget destroyed.

        Additional subclass init must be done before calling this.

        title - string, title of popup dialog
        message - string, informational message to display
        _htest - bool, change box location when running htest
        _utest - bool, leave window hidden and not modal
        """
        Toplevel.__init__(self, parent)
        self.configure(borderwidth=5)
        self.resizable(height=FALSE, width=FALSE)
        self.title(title)
        self.transient(parent)
        self.grab_set()
        self.bind("<Key-Return>", self.ok)
        self.protocol("WM_DELETE_WINDOW", self.cancel)
        self.parent = parent
        self.message = message
        self.create_widgets()
        self.update_idletasks()
        # needs to be done here so that the winfo_reqwidth is valid
        self.withdraw()  # Hide while configuring, especially geometry.
        self.geometry(
            "+%d+%d"
            % (
                parent.winfo_rootx() + (parent.winfo_width() / 2 - self.winfo_reqwidth() / 2),
                parent.winfo_rooty()
                + ((parent.winfo_height() / 2 - self.winfo_reqheight() / 2) if not _htest else 150),
            )
        )  # centre dialog over parent (or below htest box)
        if not _utest:
            self.deiconify()  # geometry set, unhide
            self.wait_window()

    def create_widgets(self):  # Call from override, if any.
        frame = Frame(self, borderwidth=2, relief="sunken")
        label = Label(frame, anchor="w", justify="left", text=self.message)
        self.entry = Entry(frame, width=30)  # Bind name for entry_ok.
        self.entry.focus_set()

        buttons = Frame(self)  # Bind buttons for invoke in unittest.
        self.button_ok = Button(buttons, text="Ok", width=8, command=self.ok)
        self.button_cancel = Button(buttons, text="Cancel", width=8, command=self.cancel)

        frame.pack(side="top", expand=TRUE, fill="both")
        label.pack(padx=5, pady=5)
        self.entry.pack(padx=5, pady=5)
        buttons.pack(side="bottom")
        self.button_ok.pack(side="left", padx=5)
        self.button_cancel.pack(side="right", padx=5)

    def entry_ok(self):  # Usually replace.
        "Check that entry not blank."
        entry = self.entry.get().strip()
        if not entry:
            showerror(title="Entry Error", message="Blank line.", parent=self)
        return entry

    def ok(self, event=None):  # Do not replace.
        """If entry is valid, bind it to 'result' and destroy tk widget.

        Otherwise leave dialog open for user to correct entry or cancel.
        """
        entry = self.entry_ok()
        if entry:
            self.result = entry
            self.destroy()
        else:
            # [Ok] (but not <Return>) moves focus.  Move it back.
            self.entry.focus_set()

    def cancel(self, event=None):  # Do not replace.
        "Set dialog result to None and destroy tk widget."
        self.result = None
        self.destroy()
开发者ID:xulukai,项目名称:cpython,代码行数:85,代码来源:query.py

示例14: MarkovDemo

# 需要导入模块: from tkinter.ttk import Entry [as 别名]
# 或者: from tkinter.ttk.Entry import get [as 别名]
class MarkovDemo(Frame):

    "MarkovDemo(master=None, **kw) -> MarkovDemo instance"

    TEXT = dict(height=2, width=46, wrap=WORD)  # Text Options
    GRID = dict(padx=5, pady=5)                 # Grid Options

    # Initialize a MarkovDemo instance with a GUI for interaction.

    def __init__(self, master=None, **kw):
        "Initialize the MarkovDemo instance's widgets and settings."
        super().__init__(master, **kw)
        self.build_widgets()
        self.place_widgets()
        self.setup_widgets()
        self.grid_rowconfigure(2, weight=1)
        self.grid_rowconfigure(3, weight=1)
        self.grid_columnconfigure(0, weight=1)
        self.key = self.primer = None

    def build_widgets(self):
        "Build the various widgets that will be used in the program."
        # Create processing frame widgets.
        self.processing_frame = LabelFrame(self, text='Processing Mode:')
        self.mode_var = StringVar(self, 'encode')
        self.decode_button = Radiobutton(self.processing_frame,
                                         text='Decode Cipher-Text',
                                         command=self.handle_radiobuttons,
                                         value='decode',
                                         variable=self.mode_var)
        self.encode_button = Radiobutton(self.processing_frame,
                                         text='Encode Plain-Text',
                                         command=self.handle_radiobuttons,
                                         value='encode',
                                         variable=self.mode_var)
        self.freeze_var = BooleanVar(self, False)
        self.freeze_button = Checkbutton(self.processing_frame,
                                         text='Freeze Key & Primer',
                                         command=self.handle_checkbutton,
                                         offvalue=False,
                                         onvalue=True,
                                         variable=self.freeze_var)
        # Create encoding frame widgets.
        self.encoding_frame = LabelFrame(self, text='Encoding Options:')
        self.chain_size_label = Label(self.encoding_frame, text='Chain Size:')
        self.chain_size_entry = Entry(self.encoding_frame)
        self.plain_text_label = Label(self.encoding_frame, text='Plain-Text:')
        self.plain_text_entry = Entry(self.encoding_frame)
        # Create input frame widgets.
        self.input_frame = LabelFrame(self, text='Input Area:')
        self.input_text = ScrolledText(self.input_frame, **self.TEXT)
        # Create output frame widgets.
        self.output_frame = LabelFrame(self, text='Output Area:')
        self.output_text = ScrolledText(self.output_frame, **self.TEXT)

    def place_widgets(self):
        "Place the widgets where they belong in the MarkovDemo frame."
        # Locate processing frame widgets.
        self.processing_frame.grid(sticky=EW, **self.GRID)
        self.decode_button.grid(row=0, column=0, **self.GRID)
        self.encode_button.grid(row=0, column=1, **self.GRID)
        self.freeze_button.grid(row=0, column=2, **self.GRID)
        # Locate encoding frame widgets.
        self.encoding_frame.grid(sticky=EW, **self.GRID)
        self.chain_size_label.grid(row=0, column=0, sticky=W, **self.GRID)
        self.chain_size_entry.grid(row=0, column=1, sticky=EW, **self.GRID)
        self.plain_text_label.grid(row=1, column=0, sticky=W, **self.GRID)
        self.plain_text_entry.grid(row=1, column=1, sticky=EW, **self.GRID)
        self.encoding_frame.grid_columnconfigure(1, weight=1)
        # Locate input frame widgets.
        self.input_frame.grid(sticky=NSEW, **self.GRID)
        self.input_text.grid(sticky=NSEW, **self.GRID)
        self.input_frame.grid_rowconfigure(0, weight=1)
        self.input_frame.grid_columnconfigure(0, weight=1)
        # Locate output frame widgets.
        self.output_frame.grid(sticky=NSEW, **self.GRID)
        self.output_text.grid(sticky=NSEW, **self.GRID)
        self.output_frame.grid_rowconfigure(0, weight=1)
        self.output_frame.grid_columnconfigure(0, weight=1)

    def setup_widgets(self):
        "Setup each widget's configuration for the events they handle."
        self.input_text.bind('<Key>', self.handle_key_events)
        self.input_text.bind('<Control-Key-a>', self.handle_control_a)
        self.input_text.bind('<Control-Key-/>', lambda event: 'break')
        self.output_text['state'] = DISABLED
        self.output_text.bind('<Control-Key-a>', self.handle_control_a)
        self.output_text.bind('<Control-Key-/>', lambda event: 'break')

    ########################################################################

    # Take care of any special event needing dedicated processing.

    def handle_radiobuttons(self):
        "Change the interface based on the encoding / decoding setting."
        if self.encrypting:
            self.freeze_button.grid()
            if not self.freeze_var.get():
                self.encoding_frame.grid()
        else:
#.........这里部分代码省略.........
开发者ID:jacob-carrier,项目名称:code,代码行数:103,代码来源:recipe-578076.py

示例15: ModelFrame

# 需要导入模块: from tkinter.ttk import Entry [as 别名]
# 或者: from tkinter.ttk.Entry import get [as 别名]
class ModelFrame(LabelFrame):
	
	topPadding = 12

	def __init__(self,parent):        
		LabelFrame.__init__(self,parent,text="Model",borderwidth=5)
		
		self.selection = tkinter.IntVar()
		
		self.exponential = Radiobutton(self,text="Exponential model",variable=self.selection,value=Model.EXP.value,command=self.changeSelection)
		self.powerlaw = Radiobutton(self,text="Power law model",variable=self.selection,value=Model.POW.value,command=self.changeSelection)
		self.weibull = Radiobutton(self,text="Weibull model",variable=self.selection,value=Model.WEI.value,command=self.changeSelection)

		self.exponential.grid(row=0,column=0,sticky="W",padx=10,pady=(self.topPadding,5))
		self.powerlaw.grid(row=1,column=0,sticky="W",padx=10,pady=5)
		self.weibull.grid(row=2,column=0,sticky="W",padx=10,pady=(5,0))
		
		seperator = Separator(self, orient=tkinter.VERTICAL)
		seperator.grid(row=0, column=1, rowspan=3, sticky="NS", padx=(20,10), pady=(self.topPadding,0))
		
		## Exponential setup

		self.expNumberOfSegments_L = Label(self,text="Number of segments: ")
		self.expNumberOfSegments_E = Entry(self,width=5, justify="right")

		self.expNumberOfSegments_E.insert(0, settings.EXP_DEFAULT_NUMBER_OF_SEGMENTS)

		self.expWidgets = [self.expNumberOfSegments_L,self.expNumberOfSegments_E]
		
		## Power law setup

		self.powProximalLimit_L = Label(self,text="Proximal limit of integration: ")
		self.powProximalLimit_E = Entry(self,width=5, justify="right")
		self.powDistalLimit_L = Label(self,text="Distal limit of integration: ")
		self.powDistalLimit_E = Entry(self,width=5, justify="right")

		self.powProximalLimit_E.insert(0, settings.POW_DEFAULT_PROXIMAL_LIMIT)
		self.powDistalLimit_E.insert(0, settings.POW_DEFAULT_DISTAL_LIMIT)

		self.powWidgets = [self.powProximalLimit_L,self.powProximalLimit_E,
						   self.powDistalLimit_L,self.powDistalLimit_E]
		
		## Weibull setup

		self.weiNumberOfRuns_L = Label(self,text="Number of runs: ")
		self.weiNumberOfRuns_E = Entry(self,width=5, justify="right")
		self.weiIterationsPerRun_L = Label(self,text="Iterations per run: ")
		self.weiIterationsPerRun_E = Entry(self,width=5, justify="right")

		self.weiEstimatedTime_L = Label(self,text="Estimated time (s): ")
		self.weiEstimatedTime_E = CustomEntry(self,width=5, justify="right")
		self.weiEstimatedTime_E.setUserEditable(False)

		self.weiLambdaLowerBoundL = Label(self,text="\u03BB lower bound:")
		self.weiLambdaUpperBoundL = Label(self,text="\u03BB upper bound:")
		self.weiLambdaLowerBoundE = Entry(self,width=5, justify="right")
		self.weiLambdaUpperBoundE = Entry(self,width=5, justify="right")

		self.weiKLowerBoundL = Label(self,text="k lower bound:")
		self.weiKUpperBoundL = Label(self,text="k upper bound:")
		self.weiKLowerBoundE = Entry(self,width=5, justify="right")
		self.weiKUpperBoundE = Entry(self,width=5, justify="right")

		self.weiNumberOfRuns_E.insert(0, settings.WEI_DEFAULT_NUMBER_OF_RUNS)
		self.weiIterationsPerRun_E.insert(0, settings.WEI_DEFAULT_ITERATIONS_PER_RUN)
		self.weiLambdaLowerBoundE.insert(0, settings.WEI_DEFAULT_LAMBDA_LOWER_BOUND)
		self.weiLambdaUpperBoundE.insert(0, settings.WEI_DEFAULT_LAMBDA_UPPER_BOUND)
		self.weiKLowerBoundE.insert(0, settings.WEI_DEFAULT_K_LOWER_BOUND)
		self.weiKUpperBoundE.insert(0, settings.WEI_DEFAULT_K_UPPER_BOUND)

		
		self.weiWidgets = [self.weiNumberOfRuns_L,self.weiNumberOfRuns_E,
						   self.weiIterationsPerRun_L,self.weiIterationsPerRun_E,
						   self.weiEstimatedTime_L,self.weiEstimatedTime_E,
						   self.weiLambdaLowerBoundL,self.weiLambdaUpperBoundL,self.weiLambdaLowerBoundE,self.weiLambdaUpperBoundE,
						   self.weiKLowerBoundL,self.weiKUpperBoundL,self.weiKLowerBoundE,self.weiKUpperBoundE]
		
		## General

		self.currentWidgets = []
		self.selection.set(Model.EXP.value)
		self.changeSelection()
		
	def changeSelection(self):
		
		for widget in self.currentWidgets:
			widget.grid_remove()

		modelType = Model(self.selection.get())
		
		sX = 10
		bX = 20
		
		if modelType == Model.EXP:
			self.expNumberOfSegments_L.grid(row=0,column=2,padx=(bX,sX),pady=(self.topPadding,5),sticky="W")
			self.expNumberOfSegments_E.grid(row=0,column=3,padx=(sX,bX),pady=(self.topPadding,5),sticky="W")
			self.currentWidgets = self.expWidgets
		elif modelType == Model.POW:
			self.powProximalLimit_L.grid(row=0,column=2,padx=(bX,sX),pady=(self.topPadding,5),sticky="W")
			self.powProximalLimit_E.grid(row=0,column=3,padx=(sX,bX),pady=(self.topPadding,5),sticky="W")
#.........这里部分代码省略.........
开发者ID:MatthewDaggitt,项目名称:AshCalc,代码行数:103,代码来源:model_frame.py


注:本文中的tkinter.ttk.Entry.get方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。