我在使用python 2.7时遇到了问题,已经使用了好几天,但没有找到。
我编写了一个简单的平均计算程序,并使其成为了一个自动将其保存到文本文件并显示在列表框中的插件。
但是该数据未在列表框中正确列出。顺便说一句,我从另一个来源获得了自动完成代码。
您必须输入40,90,60之类的数字!
#coding:utf-8
from Tkinter import *
import re
d=open("kayit.txt", "r+")
lista = []
lista.insert(1, d.read())
#Kaçıncı baytta olduğunu söyler.
d.seek(0)
class AutocompleteEntry(Entry):
def __init__(self, lista, *args, **kwargs):
#Entry girişini oluşturan kod.
Entry.__init__(self, *args, **kwargs)
self.lista = lista
self.var = self["textvariable"]
if self.var == '':
self.var = self["textvariable"] = StringVar()
self.var.trace('w', self.changed)
self.bind("<Right>", self.selection)
self.bind("<Up>", self.up)
self.bind("<Down>", self.down)
self.lb_up = False
Button(text='Calculate', command=self.hesapla).grid(row=2, column=0)
Button(text='Clear', command=lambda :self.delete(0,END)).grid(row=3, column=0)
def hesapla(self):
veri=self.get()
d.write(veri)
d.write("\n")
try:
if veri=="":
sonuc.config(text="Please don't\n leave it blank!")
else:
num=veri.split(",")
toplam=0
for n in num:
toplam=toplam+float(n)
sonuc.config(text=toplam/len(num))
except ValueError:
sonuc.config(text="You must enter\n a valid number!")
def changed(self, name, index, mode):
if self.var.get() == '':
self.lb.destroy()
self.lb_up = False
else:
words = self.comparison()
if words:
if not self.lb_up:
self.lb = Listbox()
self.lb.bind("<Double-Button-1>", self.selection)
self.lb.bind("<Right>", self.selection)
self.lb.place(x=self.winfo_x(), y=self.winfo_y() + self.winfo_height())
self.lb_up = True
self.lb.delete(0, END)
for w in words:
self.lb.insert(END, w)
else:
if self.lb_up:
self.lb.destroy()
self.lb_up = False
def selection(self, event):
if self.lb_up:
self.var.set(self.lb.get(ACTIVE))
self.lb.destroy()
self.lb_up = False
self.icursor(END)
def up(self, event):
if self.lb_up:
if self.lb.curselection() == ():
index = '0'
else:
index = self.lb.curselection()[0]
if index != '0':
self.lb.selection_clear(first=index)
index = str(int(index) - 1)
self.lb.selection_set(first=index)
self.lb.activate(index)
def down(self, event):
if self.lb_up:
if self.lb.curselection() == ():
index = '0'
else:
index = self.lb.curselection()[0]
if index != END:
self.lb.selection_clear(first=index)
index = str(int(index) + 1)
self.lb.selection_set(first=index)
self.lb.activate(index)
def comparison(self):
pattern = re.compile('.*' + self.var.get() + '.*')
return [w for w in self.lista if re.match(pattern, w)]
if __name__ == '__main__':
root = Tk()
entry = AutocompleteEntry(lista, root)
entry.grid(row=0, column=0)
sonuc=Label()
sonuc.config(text="No action has\n been made
yet.",relief="sunken",font="bold 13",bg="lightblue",width=20,height=2)
sonuc.grid(row=1,column=0)
root.mainloop()
d.close()