TKINTER文本自动填充

发布于 2025-01-19 12:21:43 字数 1105 浏览 0 评论 0原文

我正在尝试使用TKINTER为PYTHON做一个简单的个人IDE。我以前已经看过它,并有所有形式的语法突出显示到内置终端,但没有自动填充的问题。我知道您可以使用许多方法在入口中使用自动填充,但是在使用文本条目搜索自动填充后,我找不到任何东西。如果我能得到一些帮助,那就太好了!我正在寻找类似于这里看到的东西。

类似想法的代码:

from ttkwidgets.autocomplete import AutocompleteEntry
from tkinter import *

countries = [
        'Antigua and Barbuda', 'Bahamas','Barbados','Belize', 'Canada',
        'Costa Rica ', 'Cuba', 'Dominica', 'Dominican Republic', 'El Salvador ',
        'Grenada', 'Guatemala ', 'Haiti', 'Honduras ', 'Jamaica', 'Mexico',
        'Nicaragua', 'Saint Kitts and Nevis', 'Panama ', 'Saint Lucia', 
        'Saint Vincent and the Grenadines', 'Trinidad and Tobago', 'United States of America'
        ]

ws = Tk()
ws.title('PythonGuides')
ws.geometry('400x300')
ws.config(bg='#f25252')

frame = Frame(ws, bg='#f25252')
frame.pack(expand=True)

Label(
    frame, 
    bg='#f25252',
    font = ('Times',21),
    text='Countries in North America '
    ).pack()

entry = AutocompleteEntry(
    frame, 
    width=30, 
    font=('Times', 18),
    completevalues=countries
    )
entry.pack()

ws.mainloop()

I am trying to make a simple and personal IDE for python using tkinter. I have seen it done before and have everything form syntax highlighting to a built in terminal but have the problem of no autofill. I know that you can have autofill in entry's with many methods out there but after searching for autofill with Text entries I couldn't find anything. If I could get some help that would be fantastic! I am looking for something similar to what is seen here.

Code of similar idea:

from ttkwidgets.autocomplete import AutocompleteEntry
from tkinter import *

countries = [
        'Antigua and Barbuda', 'Bahamas','Barbados','Belize', 'Canada',
        'Costa Rica ', 'Cuba', 'Dominica', 'Dominican Republic', 'El Salvador ',
        'Grenada', 'Guatemala ', 'Haiti', 'Honduras ', 'Jamaica', 'Mexico',
        'Nicaragua', 'Saint Kitts and Nevis', 'Panama ', 'Saint Lucia', 
        'Saint Vincent and the Grenadines', 'Trinidad and Tobago', 'United States of America'
        ]

ws = Tk()
ws.title('PythonGuides')
ws.geometry('400x300')
ws.config(bg='#f25252')

frame = Frame(ws, bg='#f25252')
frame.pack(expand=True)

Label(
    frame, 
    bg='#f25252',
    font = ('Times',21),
    text='Countries in North America '
    ).pack()

entry = AutocompleteEntry(
    frame, 
    width=30, 
    font=('Times', 18),
    completevalues=countries
    )
entry.pack()

ws.mainloop()

Link to source code of AutocompleteEntry

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

瞎闹 2025-01-26 12:21:43

基本算法非常简单:

  • 拦截密钥发行(在TKINTER自动插入文本后发生的键)在
  • 光标之前获取单词
  • 对于基本的自动完整功能, 添加的零件以使未来的按键将替换它,

您还可以为选项卡键添加一个绑定,该键可以查看是否有可见的自动完整文本,并将光标移至末端。

这是一个非常有黑客的示例来说明该原理,尽管它缺乏任何防弹,优化或处理边缘案例,例如回头架时,在单词中间打字,选择替代替换等等

。这不是实现自动完成的最佳方法,它仅说明了这些概念。

import tkinter as tk

class AutocompleteText(tk.Text):
    def __init__(self, *args, **kwargs):
        self.callback = kwargs.pop("autocomplete", None)
        super().__init__(*args, **kwargs)

        # bind on key release, which will happen after tkinter
        # inserts the typed character
        self.bind("<Any-KeyRelease>", self._autocomplete)

        # special handling for tab, which needs to happen on the
        # key _press_
        self.bind("<Tab>", self._handle_tab)

    def _handle_tab(self, event):
        # see if any text has the "autocomplete" tag
        tag_ranges= self.tag_ranges("autocomplete")
        if tag_ranges:
            # move the insertion cursor to the end of
            # the selected text, and then remove the "sel"
            # and "autocomplete" tags
            self.mark_set("insert", tag_ranges[1])
            self.tag_remove("sel", "1.0", "end")
            self.tag_remove("autocomplete", "1.0", "end")

            # prevent the default behavior of inserting a literal tab
            return "break"

    def _autocomplete(self, event):
        if event.char and self.callback:
            # get word preceeding the insertion cursor
            word = self.get("insert-1c wordstart", "insert-1c wordend")

            # pass word to callback to get possible matches
            matches = self.callback(word)

            if matches:
                # autocomplete on the first match
                remainder = matches[0][len(word):]

                # remember the current insertion cursor
                insert = self.index("insert")

                # insert at the insertion cursor the remainder of
                # the matched word, and apply the tag "sel" so that
                # it is selected. Also, add the "autocomplete" text
                # which will make it easier to find later.
                self.insert(insert, remainder, ("sel", "autocomplete"))

                # move the cursor back to the saved position
                self.mark_set("insert", insert)


def get_matches(word):
    # For illustrative purposes, pull possible matches from 
    # what has already been typed. You could just as easily 
    # return a list of pre-defined keywords.
    words = text.get("1.0", "end-1c").split()
    matches = [x for x in words if x.startswith(word)]
    return matches

root = tk.Tk()
text = AutocompleteText(root, autocomplete=get_matches)
text.pack(fill="both", expand=True)

root.mainloop()

For a rudimentary autocomplete feature the basic algorithm is fairly simple:

  • intercept key releases (which occur after tkinter automatically inserts the text that was typed)
  • get the word before the cursor and call a callback to find possible matches
  • add the first possible match, and select the part that was added so that future keypresses will replace it

You can also add a binding for the tab key that will see if there is autocomplete text that is visible, and move the cursor to the end.

This is a very hacked-together example to illustrate the principle, though it lacks any bulletproofing, optimizations, or handling of edge cases such as when backspacing, typing in the middle of a word, choosing alternate replacements, etc.

Just to be clear: this isn't the best way to implement autocomplete, it merely illustrates the concepts.

import tkinter as tk

class AutocompleteText(tk.Text):
    def __init__(self, *args, **kwargs):
        self.callback = kwargs.pop("autocomplete", None)
        super().__init__(*args, **kwargs)

        # bind on key release, which will happen after tkinter
        # inserts the typed character
        self.bind("<Any-KeyRelease>", self._autocomplete)

        # special handling for tab, which needs to happen on the
        # key _press_
        self.bind("<Tab>", self._handle_tab)

    def _handle_tab(self, event):
        # see if any text has the "autocomplete" tag
        tag_ranges= self.tag_ranges("autocomplete")
        if tag_ranges:
            # move the insertion cursor to the end of
            # the selected text, and then remove the "sel"
            # and "autocomplete" tags
            self.mark_set("insert", tag_ranges[1])
            self.tag_remove("sel", "1.0", "end")
            self.tag_remove("autocomplete", "1.0", "end")

            # prevent the default behavior of inserting a literal tab
            return "break"

    def _autocomplete(self, event):
        if event.char and self.callback:
            # get word preceeding the insertion cursor
            word = self.get("insert-1c wordstart", "insert-1c wordend")

            # pass word to callback to get possible matches
            matches = self.callback(word)

            if matches:
                # autocomplete on the first match
                remainder = matches[0][len(word):]

                # remember the current insertion cursor
                insert = self.index("insert")

                # insert at the insertion cursor the remainder of
                # the matched word, and apply the tag "sel" so that
                # it is selected. Also, add the "autocomplete" text
                # which will make it easier to find later.
                self.insert(insert, remainder, ("sel", "autocomplete"))

                # move the cursor back to the saved position
                self.mark_set("insert", insert)


def get_matches(word):
    # For illustrative purposes, pull possible matches from 
    # what has already been typed. You could just as easily 
    # return a list of pre-defined keywords.
    words = text.get("1.0", "end-1c").split()
    matches = [x for x in words if x.startswith(word)]
    return matches

root = tk.Tk()
text = AutocompleteText(root, autocomplete=get_matches)
text.pack(fill="both", expand=True)

root.mainloop()

很酷不放纵 2025-01-26 12:21:43

今天,我告诉您如何使用ListBox创建AutoCompeAtion输入框,而无需OOP。
如果您不知道OOP可能会为您提供帮助。

您可以创建自动完成输入框和搜索框,只有一条线差。

from tkinter import *
import re

root=Tk()


def fun1(event, *args, **kwargs):
      global data
      if (e.get()==''):
            lb.place_forget()            
            lb.delete(0, END)
       
      else:
            lb.delete(0, END)
            value=e.get()
            lb.place(x=0, y=20)

            for items in data:
                        if (re.search(value, items, re.IGNORECASE)):    
                                    lb.insert(END, items)
                                
        
            print(value)
            pass
        
        



def CurSelet(evt):

  

    valued=lb.get(ACTIVE)
    e.delete(0, END)
    e.insert(END, valued)
    lb.place_forget() 

    print( valued)
        





def  down(ddd):
 
                  lb.focus()
                  lb.selection_set(0)

s=StringVar()


e=Entry(root,     textvariable=s)
e.grid(row=2, column=2)

s.trace('w', fun1)


e.bind('<Down>',     down)


for i in range(4,12):
      ee=Entry(root)
      ee.grid(row=i, column=2)



data=['Angular', 'action Script', 'Basic', 'GW-Basic' , 'C', 'C++', 'C#', 
'Django' ,'Dot-Net',  'Flask' , 'Go-Lang', 'Html', 'Python', 'PHP', 'Pearl', 
'Java', 'Javascript', 'Kotlin',  'Rust', 'R', 'S', 'Sr', 'Tekken 7', 'Tekken 
Tag' ]

lb=Listbox(root)
lb.place_forget()
lb.bind("<Button-3>", CurSelet)
lb.bind("<Right>",  CurSelet)


root.mainloop()

print(Listbox.curselection)

这是搜索栏。如果您将自动完成使用

if (re.match(value, items, re.IGNORECASE)):  

代替IF(re.Search(值,项目,re.ignorecase))):

仅在searchbar&amp;自动完成。

Today i tell you How you create Autocompeletion Entry box with Listbox without OOP.
If you not know about OOP that this Code may help you.

You can create autocompletion Entry box and Search box one code only one line Difference.

from tkinter import *
import re

root=Tk()


def fun1(event, *args, **kwargs):
      global data
      if (e.get()==''):
            lb.place_forget()            
            lb.delete(0, END)
       
      else:
            lb.delete(0, END)
            value=e.get()
            lb.place(x=0, y=20)

            for items in data:
                        if (re.search(value, items, re.IGNORECASE)):    
                                    lb.insert(END, items)
                                
        
            print(value)
            pass
        
        



def CurSelet(evt):

  

    valued=lb.get(ACTIVE)
    e.delete(0, END)
    e.insert(END, valued)
    lb.place_forget() 

    print( valued)
        





def  down(ddd):
 
                  lb.focus()
                  lb.selection_set(0)

s=StringVar()


e=Entry(root,     textvariable=s)
e.grid(row=2, column=2)

s.trace('w', fun1)


e.bind('<Down>',     down)


for i in range(4,12):
      ee=Entry(root)
      ee.grid(row=i, column=2)



data=['Angular', 'action Script', 'Basic', 'GW-Basic' , 'C', 'C++', 'C#', 
'Django' ,'Dot-Net',  'Flask' , 'Go-Lang', 'Html', 'Python', 'PHP', 'Pearl', 
'Java', 'Javascript', 'Kotlin',  'Rust', 'R', 'S', 'Sr', 'Tekken 7', 'Tekken 
Tag' ]

lb=Listbox(root)
lb.place_forget()
lb.bind("<Button-3>", CurSelet)
lb.bind("<Right>",  CurSelet)


root.mainloop()

print(Listbox.curselection)

This is Search bar. If you Make AutoCompletion Use

if (re.match(value, items, re.IGNORECASE)):  

in place of if (re.search(value, items, re.IGNORECASE)):

only re.match and re.search Defferane between searchbar & autocompletion.

enter image description here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文