简体   繁体   English

有没有办法在不使用全局的情况下在不同的函数中使用相同的变量?

[英]is there a way to use same variables in different functions without using global?

check1 = False
def adding():
    global f_num, s_num, check1
    check1 = True
    e.delete(0, END)
    f_num = e.get()

    s_num = e.get()
    e.delete(0, END)

def show_answer():
    if check1:
        e.insert(0,f_num+s_num) 

I'm new to coding and using this website...I'm using tkinter module to build a calculator.我是编码和使用这个网站的新手......我正在使用 tkinter 模块来构建计算器。 when I set the show_answer() function in the equal sign button it was supposed to show the answer to the addition to the numbers.当我在等号按钮中设置show_answer() function 时,它应该显示数字加法的答案。

If you are using tkinter, then you can define it in your root.如果您使用的是 tkinter,那么您可以在根目录中定义它。 Like:喜欢:

root.Variable = True

Here is an example:这是一个例子:

from tkinter import *

root = Tk()

root.Check1 = 0

def command():
    print(root.Check1)
    root.Check1 += 1


Button(text="Hello World", command=command).grid()

root.mainloop()

It keeps adding 1 to root.Check1 and you can access the variable normally inside and outside the functions.它不断将 1 添加到root.Check1并且您可以在函数内部和外部正常访问该变量。 You can use this concept.你可以使用这个概念。 Or stay with globals and use return或者继续使用globals并使用return

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

相关问题 在 Python 的不同函数中使用相同的变量 - Using the same variables in different functions in Python 对于不同功能的变量使用相同的名称? - Using the same name for variables which are in different functions? 如何在不使用“全局”的情况下更改 Python 函数中的变量 - How to change variables in Python functions without using 'global' 我应该使用类来定义将使用相同参数的函数,还是应该使用全局变量? - Should I use a class to define functions that will use the same arguments, or should I use global variables? 在python(jupyter)中复制变量/对相同的变量使用不同的函数 - Copy a variable in python (jupyter) / Use different functions with same variables 如何使用导入函数中的全局变量 - How to use Global Variables from Imported Functions Python 如何使用np.select运行不同的函数来修改全局变量? - Python How to use np.select to run different functions to modify global variables? 使用在函数中声明的变量,并在不同类的另一个函数中使用它们 - Using variables declared in functions and use them in another function in a different class 处理在没有全局变量的函数中使用的变量 - Handling Variables To Be Used Across Functions Without Global Variables 导入函数时使用全局变量 - Using global variables when importing functions
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM