我将如何向该代码添加选项和其他功能

时间:2019-03-31 14:40:12

标签: python tkinter

我有一个框架,可以从文本文件中读取数据,并逐行显示。每行都存储为单独的标签,用户可以单击这些标签。如果单击标签,则会从页面上将其删除,并且文本文件中的该行也会被删除。 现在,我想这样做,以便如果单击标签,则用户可以选择是从文本文件/标签编辑数据,还是像以前一样删除行。

def newbooking():

    def populate(frame2):
        count = 0
        removeLbl = Label(frame2,text='Click on the selected booking you wish to delete:',
                          font=('Courier',23),bg='#333333',fg='#CCCCCC')
        removeLbl.grid(row=0,column=0)

        #class to allow highlighting and deleting of displayed data
        class HighlightLabel(Label):
            def __init__(self,master=None,highlight='grey',lowlight=None,**kwargs):
                super().__init__(master,**kwargs)
                if lowlight is None:
                    lowlight = self['bg']

                self.bind('<Enter>', lambda *args: self.config(bg=highlight))
                self.bind('<Leave>', lambda *args: self.config(bg=lowlight))
                self.bind('<Button-1>',self.deleteClick)

            #function which stops the clicked label from being displayed
            def deleteClick(self,*args):
                if not deleteActiveBtn:
                    return
                deleteLine(self['text'])

                self.destroy()

        deleteActiveBtn = True

        #function which deletes clicked data from text file
        def deleteLine(deleteData):

            with open('Bookings.txt') as f:
                oldFile = f.readlines()

            with open('Bookings.txt','w') as f:
                print(deleteData)
                old1 =([[item for item in line.strip().split()] for line in oldFile])
                for old1 in oldFile:
                    print(old1)
                    if old1 != (deleteData+"\n"):
                        f.write(old1)
                    elif old1 != (deleteData): #last line in file doesn't have \n
                        f.write(old1)                       

        #displays the data from the text file in line by line format
        with open('Bookings.txt','r+') as f:
            bookings  = ([[item for item in line.strip().split()] for line in f])
        for booking in bookings:
            bookingData = HighlightLabel(frame2,text=booking,width=60,anchor='w',bg='#333333',fg='#CCCCCC')
            bookingData.grid(row=count,column=3)
            count+=5

现在它现在可以正常工作,但是我在按一个按钮?编辑或删除选项以及编辑数据的功能。

1 个答案:

答案 0 :(得分:0)

您可以创建一个弹出菜单并将其绑定到每个小部件。在我的示例中,我仅编辑或删除标签,而不更改文件。

from tkinter import *
from tkinter import simpledialog

class PopupMenuDemo(Frame):
    def __init__(self):
        Frame.__init__(self)
        self.pack(expand=True, fill='both')
        self.master.title("Popup Menu Demo")
        self.master.geometry("300x200")

        self.frame = Frame(self, bg='tan')
        self.frame.pack(expand=YES, fill=BOTH)

        # Create some sample data for labels
        file_lines = ['One', 'Two', 'Three', 'Four']
        # Create labels
        self.label_list = []    # Save label widgets in a list
        for line in file_lines:
            label = Label(self.frame, text=line, width=10, bg='white')
            label.pack(pady=(10,0))
            self.label_list.append(label)

        self.menu = Menu(self.frame, tearoff=0)
        self.menu.add_command(label='Delete', command=self.label_delete)
        self.menu.add_command(label='Edit', command=self.label_edit)
        # Bind every widget to <Button-1>
        for widget in self.label_list:
            widget.bind("<Button-1>", self.popup_menu)

    def popup_menu(self, event):
        self.widget = event.widget  # Remember which widget was clicked
        self.menu.post(event.x_root, event.y_root)

    def label_delete(self):
        self.widget.destroy()

    def label_edit(self):
        text = self.widget.cget('text')
        result = simpledialog.askstring('Change data', 'Edit the line',
                                        initialvalue=text)
        self.widget.config(text=result)

if __name__ == "__main__":
    PopupMenuDemo().mainloop()