A..
A..

Reputation: 375

Python Need Access to variable created in a function from another function

As i have set search term to global for the first function - shouldnt the second function be able to access it - if not how would i get this to work?

import sys
import os.path
from tkinter import *
import math

def setupsearch():
    exist = os.path.isfile('messages.txt')
    if exist == True:
        global searchterm
        gui2 = Toplevel(master=gui)
        Label(gui2, text = "Search Term").grid(row = 0)
        searchterm = Entry(gui2).grid(row = 1)
        Button(gui2, text="Search", command = search).grid(row = 2)
    else:
        labelprint = "No Stored Messages"
        add = Label(gui, text = labelprint, width = 30)
        add.grid(row = 2, column =2)

def search():
    searchterm = 
    with open('messages.txt', 'r') as inF:
        i = 1
        for line in inF:
            if searchterm in line:
                print("found it in line " + str(i))
                i = i + 1
            else:
                print("Not in line " + str(i))
                i = i + 1  

gui = Tk()

Button(gui, text="Retriever", command=setupsearch).grid(row = 5, column = 0)

mainloop( )

Upvotes: 0

Views: 85

Answers (3)

gboffi
gboffi

Reputation: 25093

In your setupsearch use

        Button(gui2,
               text="Search",
               command = lambda: search(thesearchterm)).grid(row = 2)

and of course modify the definition of search

def search(searchterm):
    ...

Note that I used lambda: search(the_searchterm) for a good reason, as searchterm = Entry(...) is a widget. Please read a tutorial on Tkinter.Entry or simply, from the shell prompt, use man Entry (you must have installed the docs for tk, of course).

Upvotes: 1

jez
jez

Reputation: 15369

Each function that wants to change the value of the searchterm global variable needs to declare global searchterm. The global statement doesn't change properties of the variable itself—rather, it changes properties of the function, specifically the way the current function sets and gets values for the variable name in question.

You can get away with accessing a global variable from inside a function, without declaring it global, provided (a) there is no local variable of the same name to conflict with it, and (b) you don't need to change its global value.

If you don't say global searchterm but then assign something to searchterm, the function will simply create a local variable of that name.

Upvotes: 1

zaxvo
zaxvo

Reputation: 196

You want to begin your second function by stating:

def search():
    global searchterm
    ## rest of function goes here

Then you'll be able to access the global variable from within search()

With that being said...I'm sure you know that, in general, having global variables is a bad idea.

Upvotes: 0

Related Questions