繁体   English   中英

Tkinter、GUI 和全局变量

[英]Tkinter, GUI and global variables

我在将参数传递给我的第二个函数时遇到问题,该函数在类中的第一个变量中定义。

在函数 1 open_file()中,我定义了global fp ,它是用户输入文件路径。 在函数 2 split_lines()中,我有第一个参数作为文件路径fp ,我想读取从函数 1 定义的同一个文件。在我的第二个函数的按钮中,我无法让它在fp上工作,因为它说它是没有定义的。

def open_file(self):  # Defines the function that opens the user's file in specific location.
    global fp
    fp = askopenfilename(filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")])
    if not fp:
        return
    txt_edit.delete("1.0", tk.END)
    with open(fp, mode="r", encoding="utf-8") as input_file:
        text = input_file.read()
        txt_edit.insert(tk.END, text)
    window.title(f"Linestring Compiler V1.0 - {fp}")

# Defines the function that reads, delimits and quantifies the data.
def split_lines(fp, delimiter, remove = '^[0-9.]+$'):
    for line in fp:
        tokens = line.split(delimiter)
        tokens = [re.sub(remove, "", token) for token in tokens]
        clean_list = list(filter(lambda e:e.strip(), tokens))
        print(clean_list)
    txt_edit.delete("1.0", tk.END)
    #with open(user_filepath, mode="r", encoding="utf-8") as input_file:
    text = clean_list.read()
    txt_edit.insert(tk.END, text)

这是我的按钮:

btn_compile = tk.Button(frm_buttons, text="Compile Lines", command=Sequence.split_lines(fp, "/"))

问题是您没有传递split_lines函数。 您在创建按钮时调用该函数,并将其结果传递给command= 在它被调用的时候, open_file还没有被调用。

你需要一个 lambda:

btn_compile = tk.Button(frm_buttons, text="Compile Lines", command=lambda: Sequence.split_lines(fp, "/"))

暂无
暂无

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

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