Chaotic.Python
Chaotic.Python

Reputation: 47

Tkinter, GUI and global variables

I'm having trouble passing an argument to my second function, which is defined in my first variable within a class.

In function 1 open_file() I define global fp which is a user input filepath. In function 2 split_lines() I have the first argument as that filepath fp which I want to read off the same file defined from function 1. In my button for that second function I can't get it to work off fp as it says it's not defined.

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)

This is my button:

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

Upvotes: 2

Views: 179

Answers (1)

Tim Roberts
Tim Roberts

Reputation: 54635

The PROBLEM is that you are not passing the split_lines function. You are CALLING the function at the time you create the button, and passing its RESULT to command=. At the time it is called, open_file hasn't been called yet.

You need a lambda:

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

Upvotes: 1

Related Questions