简体   繁体   中英

Show updated text in Tkinter Label

I have made a program that displays a window, and prints user input into a Label , and will add any future input to the Label on a new line.

My issue is once it gets to x number of lines, the text goes outside the range of the Label , and you cannot see it.

What I would like to do is to have the new input placed at the bottom of all the inputs, causing the top line to be pushed up and out of the top of the label.

Here is the whole code so far:

from tkinter import *

string = None
labelContents = ""

class App(Frame):
    def __init__(self, master):
        Frame.__init__(self, master)
        self.master = master
        self.initUI()

    def initUI(self):
        global string
        self.master.title("Tkinter test")

        string = StringVar()

        frame = Frame(self, relief=RIDGE, borderwidth=3, width=300, height=50)
        frame.pack(fill=BOTH, expand=1)

        label = Label(self, justify=LEFT, relief=RIDGE, borderwidth=3, textvariable=string, width=300, height=5, anchor=NW)
        label.pack(fill=BOTH, expand=1)

        self.pack(fill=BOTH, expand=1)

        self.textEntry = Entry(self)
        self.textEntry.bind('<Return>', self.updateLabel)
        self.textEntry.pack(side=TOP, fill=X, padx=5, pady=5)

        closeButton = Button(self, text="Close", height=1, width=10, command=self.close)
        closeButton.pack(side=RIGHT, padx=5, pady=5)

    def close(self):
        self.master.destroy()

    def updateLabel(self, event):
        global string
        global labelContents
        labelContents += self.textEntry.get()
        labelContents += "\n"
        string.set(labelContents)
        self.textEntry.delete(0, END)

def main():
    root = Tk()
    root.geometry("400x500+440+262")
    root.resizable(0, 0)
    app = App(root)
    root.mainloop()

if __name__ == "__main__":
    main()

It sounds like you want to be using a text widget or listbox instead of a label, since widgets have the ability to scroll things off of the top. Otherwise, you'll have to manage the data in the label yourself.

For the latter, in your updateLabel function you can first fetch the existing contents of the label, and split on newlines to give you a list. Next, append the new item and pop items off if the list is longer than 5. Then, join the list with newlines and put that back into the label.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM