简体   繁体   English

如何调用function外的局部变量?

[英]How to call local variable outside function?

I was trying to call local variables outside far from a function that I made.我试图调用远离我制作的 function 之外的局部变量。 I was playing with Tkinter in python. Here is the sample code.我在python中玩Tkinter。这是示例代码。 Is that possible to call variables outside function anywhere?是否可以在任何地方调用 function 之外的变量?

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 .在这里你可以看到我做了一个按钮命令 function name load_auto_button_output并且我通过 txt_box.insert 调用了text_box中的所有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?现在,如何在text_box.insert之外调用load_auto_button_output或者如何在 function 之外调用s1s2变量?

I have tried global but it's not working by my side我试过 global 但它在我身边不起作用

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.然后我必须返回 function load_auto_button_output () ,然后它会自动从按钮打印值而无需单击,当我按下自动加载按钮时没有任何反应。

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.您无法在 function 之外访问 function 的局部变量。有时,如果您从 function 中调用任何函数,则可以将它们的值传递给其他函数,但它们正在被定义,但这在这种情况下无济于事。

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.你说你试过使用global变量但它没有用——但它应该有,所以下面的代码展示了如何这样做。

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.我还修改了您的代码,使其在很大程度上遵循PEP 8 - Python 代码指南的样式指南,从而使其更具可读性。

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.我更改了代码以显示在一个 function 中设置全局变量的值后如何使用它们。 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.具体来说,现在有另一个按钮,其command=选项是一个新的 function,它将存储在全局变量中的值放入文本框中。


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()

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

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