简体   繁体   English

Python Tkinter更新文本小部件

[英]Python Tkinter updating a Text Widget

So I am new to Tkinter, and I am trying to add a graphic interface to a little file tail program I wrote. 因此,我是Tkinter的新手,我正在尝试向我编写的一个文件尾程序添加图形界面。 I have got everything working from a command line perspective but I am having issue's getting the text box to update on my application when you you initially load the file or when you add a line. 从命令行的角度来看,我可以正常工作,但是当您初次加载文件或添加行时,无法在应用程序上更新文本框。 I see that it calls tk but doesn't update as expected. 我看到它调用tk,但是没有按预期更新。 below is the code: 下面是代码:

from sys import argv
import threading
import tkinter


class MyTkApp(threading.Thread):
    def __init__(self):
        self.root = tkinter.Tk()
        self.root.title("PyTail V 1.0")
        self.s = tkinter.StringVar()
        self.s.set('Begging Tail of File')
        self.text_window = tkinter.Text(self.root, height=20, width=80)
        self.text_window.insert(tkinter.END, self.s.get())
        self.text_window.pack()
        self.root.update()
        threading.Thread.__init__(self)


def run(self):
    self.root.mainloop()


def get_current_line_count(lines):
    lines = lines.count("\n")
    return lines


def get_file(tail_name):
    file = open(tail_name, 'r')
    lines = file.read()
    file.close()
    return lines


def print_lines(lines, begin_line, tail_app):
    split_lines = lines.split("\n")
    for num in range(begin_line, len(split_lines)-1):
        #  print(split_lines[num])
        tail_app.s.set(split_lines[num])



def correct_args(argv):
    if not len(argv) == 2:
        return False
    else:
        return True


def update_window(current_lines, tail_app):
    try:
        file_lines = get_file(argv[1])
        new_lines = get_current_line_count(file_lines)
        if new_lines > current_lines:
            print_lines(file_lines, current_lines, tail_app)
            current_lines = new_lines

    except (KeyboardInterrupt, SystemExit):
            print("Now Exiting.....")
    return current_lines


if correct_args(argv):
    file_lines = get_file(argv[1])
    current_lines = get_current_line_count(file_lines)
    app = MyTkApp()
    app.start()
    print_lines(file_lines, 0, app)
    x = True
    while x:
        current_lines = update_window(current_lines, app)
else:
    print("You must supply the name of a file")

So I was going about this all wrong. 所以我要解决所有这些错误。 since Tk is even driven it's always going to go into that loop and not give me what I expected. 因为Tk甚至被驱动,所以它总是会进入该循环,而不给我我期望的结果。 I fixed this by starting from scratch and using the .after method. 我通过从头开始并使用.after方法来解决此问题。 Below is my revision. 以下是我的修订。 Overall was a really good learning experience for python and GUI. 总体而言,对于python和GUI而言,这是一次非常不错的学习体验。

from sys import argv
import tkinter as tk


text = tk.Text
current_line = 0
file_lines = []
pause_status = False


def pause_updates():
    global pause_status
    if pause_status:
        pause_status = False
        root.title("Pytail v1.0 - Watching File")
    else:
        pause_status = True
        root.title("Pytail v1.0 - Paused")

 def get_current_line_count(lines):
    lines = lines.count("\n")
    return lines


def get_file(tail_name):
    file = open(tail_name, 'r')
    lines = file.read()
    file.close()
    return lines

def print_lines(begin_line):
    global text
    global file_lines
    text.config(state=tk.NORMAL)
    split_lines = file_lines.split("\n")
    for num in range(begin_line, len(split_lines)-1):
        text.insert("end", (split_lines[num])+"\n")
        text.yview(tk.END)
     text.config(state=tk.DISABLED)
     text.update()

def update_window():
    try:
        global current_line
        global file_lines
        global pause_status
        if not pause_status:
            file_lines = get_file(argv[1])
            new_lines = get_current_line_count(file_lines)
            if new_lines > current_line:
                print_lines(current_line)
                current_line = new_lines
     except (KeyboardInterrupt, SystemExit):
         print("Now Exiting.....")
     root.after(1000, update_window)

def create_interface():
    global text
    global file_lines
    frame = tk.Frame(root, background="black")
    frame.place(x=10, y=10)
    frame2 = tk.Frame(root)
    scr = tk.Scrollbar(frame)
    text = tk.Text(frame, background="black", fg="green")
    text.insert("1.0", "Beginning of Tail File" + "\n")
    scr.config(command=text.yview)
    scr.pack(side="right", fill="y", expand=False)
    text.pack(side="left", fill="both", expand=True)
    frame.pack(side=tk.TOP, fill="both", expand=True)
    frame2.pack(side="bottom", anchor="w")
    pause = tk.Button(frame2, text="Pause", command=pause_updates)
    pause.pack()
    print_lines(0)
    update_window()


def correct_args(argv):
    if not len(argv) == 2:
        return False
    else:
        return True


if correct_args(argv):
    root = tk.Tk()
    root.title("Pytail v1.0 - Watching File")
    file_lines = get_file(argv[1])
    current_line = get_current_line_count(file_lines)
    create_interface()
    root.mainloop()

change self.text_window = tkinter.Text(self.root, height=20, width=80) 更改self.text_window = tkinter.Text(self.root, height=20, width=80)

to self.text_window = tkinter.Label(self.root,textvariable=self.s, height=20, width=80) self.text_window = tkinter.Label(self.root,textvariable=self.s, height=20, width=80)

then get rid of the line right after that 然后在那之后摆脱这条线

then you can just do self.s.set("Test New Text!") 那么您可以只做self.s.set("Test New Text!")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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