Skip to content
Advertisement

Print variable from external file. NameError: name ‘x’ is not defined

I would like to get that: if I select item A in the combobox of main.py, then the variable example is printed as placeholder in phrase (both are located in the external file external.py). So I would like to simply get the phrase of external.py to be printed in the textbox in main.py.

enter image description here

The problem is that phrase is in an external file and does not recognize x.get() in the condition, because x.get() is in the main file main.py, so rightly it is undefined and I get the error:

    phrase =  ("{example}" if x.get() == "A" else "")
NameError: name 'x' is not defined

external.py

phrase =  ("{example}" if x.get() == "A" else "")
example = ("abcdefghilmno")

main.py

from tkinter import ttk
import tkinter as tk
from tkinter import *

import external

root = tk.Tk()
root.geometry("200x150")

x=ttk.Combobox(root, width = 16)
x.place(x=15, y=10)
x['value'] = ["A", "B", "C"]
x.set("Item")

text = tk.Text(root,width=20,height=2)
text.place(x=15, y=50)

def write():
        
    text.delete(1.0,END)     
    text.insert(tk.END, external.phrase.format(example=example))

btn = Button(root, text="Print", command=write())
btn.pack()
btn.place(x=15, y=100)
 
root.mainloop()

IMPORTANT: I need the condition in the same line as the phrase and of the same code structure as much as possible to mine, because the code is part of my small personal project and if I change the code structure then nothing will work anymore.

Advertisement

Answer

Put the code in external.py into a function, and call that from your write() function. Use x.get() in the main program, so that the module isn’t dependent on your variable names or the fact that the main program uses Tkinter.

external.py:

example = "abcdefghilmno"
def format_phrase(template, testword, *params):
    return template.format(params) if testword == "A" else ""

main.py:

def write():
    text.delete(1.0,END)     
    text.insert(tk.END, external.format_phrase("{example}", x.get(), example=external.example))
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement