0

I was trying to call local variables outside far from a function that I made. I was playing with Tkinter in python. Here is the sample code. Is that possible to call variables outside function anywhere?

from tkinter import *
font1 = "Roboto 14"

window = Tk()
window.geometry("1200x800")
window.title("TEST")
canvas = Canvas(window, bg = "#FFFFFF", height = 800, width = 1200, bd = 0,
                highlightthickness = 0)
canvas.place(x = 0, y = 0)

def load_auto_button_output ():
    get_text_file = r"Links.txt"
    read_text_file =  open(get_text_file, 'r')

    intermediate = read_text_file.read()
    urlList = intermediate.split("\n")

    s1 = urlList[0]
    s2 = urlList[1]

    txt_box.insert(0.0,
        s1  + '\n' +
        s2  + '\n'
    )

def load_automatically_button ():
    load_auto_button = Button(window, text = 'Automatically Load', font = font1 ,
                              width = 25, bd = 1, highlightthickness = 0,
                              relief = "ridge", command = load_auto_button_output)
    load_auto_button.place(x = 540, y = 60)

load_automatically_button ()

txt_box = Text(window, bg = 'white', font = font1, height = 10, width = 70, bd = 3,
               relief = "flat", wrap=WORD)
txt_box.place(x = 370, y = 500)

window.resizable(False, False)
window.mainloop()

Here you can see I made a button command function name load_auto_button_output and I called all output inside text_box , via txt_box.insert.

Now, how do I call text_box.insert outside of that load_auto_button_output or how do I call s1, s2 variables outside that function?

I have tried global but it's not working by my side

global s1, s2

then I had to return the function load_auto_button_output (), then it's automatically print values from the button without a click and nothing happen when I press the Automatically Load button.

5
  • maybe pass them as parameters? Commented Apr 1, 2022 at 6:58
  • how do I pass parameters, I am a newbie, and I have less knowledge about parameters in a function. can you please help me? Commented Apr 1, 2022 at 7:02
  • w3schools.com/python/python_functions.asp Commented Apr 1, 2022 at 7:04
  • maybe it's possible by these parameters. :) Commented Apr 1, 2022 at 7:09
  • "how do I pass parameters, I am a newbie, and I have less knowledge about parameters in a function. can you please help me? " If you don't understand the words we use to talk about programming, or the basic techniques, you should fix this by working through a tutorial on Python, not by asking on Stack Overflow. You should make sure you understand the fundamentals before trying to use tkinter or anything more sophisticated. That said: you absolutely do know how to do this. When you write the code window.title("TEST"), for example, you are passing "TEST" to window.title. Commented Apr 1, 2022 at 7:44

1 Answer 1

1

You can't access the local variables of a function outside the function. Sometimes you can pass their values to other functions if you call any from the function were they are being defined, but that doesn't help in this case.

You said you tried using global variables and it didn't work — but it should have, so the code below show how to do it that way.

I've also modified your code so it follows the PEP 8 - Style Guide for Python Code guidelines to a large degree so to make it more readable.

Update

I've changed the code to show how one might use the global variables after their values are set in one function in another. It also better illustrates how event-driven programming works.

Specifically, there's is now another button whose command= option is a new function that puts the values stored in the global variables into the text box.


import tkinter as tk   # PEP 8 says to avoid 'import *'.
from tkinter.constants import *  # However this is OK.
import tkinter.messagebox as messagebox


FONT1 = 'Roboto 14'  # Global constant.
LINKS_FILE_PATH = r'Links.txt'

# Define global variables.
s1, s2 = None, None

window = tk.Tk()
window.geometry('1200x800')
window.title('Test')
canvas = tk.Canvas(window, bg='#FFFFFF', height=800, width=1200, bd=0,
                   highlightthickness=0)
canvas.place(x=0, y=0)

def load_links():
    """Load URLs from links file."""
    global s1, s2  # Declare global variables being assigned to.

    with open(LINKS_FILE_PATH, 'r') as read_text_file:
        urlList = read_text_file.read().splitlines()

    s1, s2 = urlList[:2]  # Assign first two links read to the global variables.

    messagebox.showinfo('Success!', 'URLs loaded from file')
    put_in_text_box_btn.config(state=NORMAL)  # Enable button.

def put_in_text_box():
    """Put current values of global variables s1 and s2 into text box."""
    txt_box.delete('1.0', END)  # Clear Text widget's contents.
    txt_box.insert(0.0, s1+'\n' + s2+'\n')  # Insert them into the Text widget.


load_links_btn = tk.Button(window, text='Load Links', font=FONT1, width=25, bd=1,
                           highlightthickness=0, relief='ridge', command=load_links)
load_links_btn.place(x=540, y=60)

put_in_text_box_btn = tk.Button(window, text='Put in text box', font=FONT1, width=25,
                                bd=1, highlightthickness=0, relief='ridge',
                                state=DISABLED, command=put_in_text_box)
put_in_text_box_btn.place(x=540, y=100)

quit_btn = tk.Button(window, text='Quit', font=FONT1, width=25, bd=1,
                     highlightthickness=0, relief='ridge', command=window.quit)
quit_btn.place(x=540, y=140)

txt_box = tk.Text(window, bg='white', font=FONT1, height=10, width=70, bd=3,
                  relief='flat', wrap=WORD)
txt_box.place(x=370, y=500)

window.resizable(False, False)
window.mainloop()

Sign up to request clarification or add additional context in comments.

4 Comments

thank you very much, there you insert txt_box.insert(0.0, s1+'\n' + s2+'\n') inside load_auto_button_output() function, If i want to declare it before window.resizable(False, False) then?. actually i want it. can you please tell what should i do? for declare that s1, s2 or txt_box.insert(0.0, s1+'\n' + s2+'\n') out of function.
I am not sure I understand what you are now asking. After the s1, s2 = urlList[:2] assignment in the load_auto_button_output(): function, the values put into s1 and s2 can be accessed from anywhere in your code. This means, for example that inserting them into the Text widget could be done in some other function if it is called.
i put this code txt_box.insert(0.0, s1+'\n' + s2+'\n') # Insert them into the Text widget. before window.resizable(False, False) window.mainloop() Traceback (most recent call last): File "path", line 36, in <module> txt_box.insert(0.0, s1+'\n' + s2+'\n') # Insert them into the Text widget. TypeError: unsupported operand type(s) for +: 'NoneType' and 'str
You can't do that then. You don't understand how GUI programs work. They're user-event driven as opposed to being procedurally driven — the latter programming paradigm probably being what you're familiar with. After initialization almost everything in them executes as a reaction to something the used has done (via the mouse or keyboard) interacting with the graphical interface. Which, in a nutshell, means you can't just do things whenever you feel like it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.