而不是更新全局值,设置参数并返回函数

问题描述 投票:-2回答:1

更新:我现在明白这实际上只是对范围与导入的混淆。我正在更新全局值,我找不到从另一个“Sum Function”文件返回多个值的方法。现在,我知道可以使用Alex指出的元组轻松完成。

所以,这是我写的一些代码。你可能会发现我的数学函数并没有真正采用任何参数。而我正试图改变它,因为Sum,Subtraction和函数就像那些采用两个参数,而像sin这样的函数只需要一个..现在我想问的是我怎么能实现给它参数并返回答案而不是更新全球价值,就像我在这里所做的那样。任何和所有帮助将不胜感激

from tkinter import *
import math

root= Tk()
num1=StringVar()


txtDisplay = Entry(root, textvariable = num1, width=17, font='Arial 25',justify="right");
txtDisplay.focus();
txtDisplay.grid(columnspan=5,row=0,ipady=8,padx=18,pady=10)


a=0
common=''
condition=0

oneButton = Button(root, text="1", width='5',command = lambda: clck(1 ))
oneButton.grid(row=6, column=1, ipady=8, ipadx=8)
twoButton = Button(root, text="2", width='5',command = lambda: clck(2))
twoButton.grid(row=6, column=2, ipady=8, ipadx=8)

addButton = Button(root, text="+", width='5',command = lambda: addition() )
addButton.grid(row=7, column=4, ipady=8, ipadx=8, padx=(0, 11))

subButton = Button(root, text="-", width='5',command = lambda: subtraction() )
subButton.grid(row=8, column=4, ipady=8, ipadx=8, padx=(0, 11))

sinButton = Button(root, text="sin", width='5',command = lambda: sin() )
sinButton.grid(row=9, column=4, ipady=8, ipadx=8, padx=(0, 11))


def clck (number):
    global common
    common+= str(number)
    num1.set(common)

def sin():
    global common
    global a
    a = math.sin(int(a))
    num1.set(a)

def addition():
    global a
    global common
    try:
        a=a+ int(common)
    except:
        pass
    #print(a)
    num1.set(a)
    common=''
    global condition
    condition='add'
def subtraction():
    global a
    global common
    a=a- int(common)
    #print(a)
    num1.set(a)
    common=''

root.mainloop()

另外,我现在知道我只实现了几个按钮。如果有任何方法可以改进我的代码,请让我知道,如果有什么是你没有得到的。

python function tkinter global-variables
1个回答
0
投票

看看这个示例代码:

def add(arg_1, arg_2, arg_3):
    # do some stuff
    return arg_1 + int(arg_2), "new value", "new condition"

a = 1
common = "old value"
condition = "old condition"    

a, common, condition = sum(a, common, condition)
addButton = Button(root, text="+", width="5", command=lambda: addition(a, common, condition))

如果你的函数将N个变量作为参数并更改它们中的每一个,那么你的函数可以返回N个元素的元组,你可以在这些元素上“扩散”你的变量,从而改变它们。使用此方法,您可以更改全局变量,而无需在所有函数中将其声明为全局变量。

除此之外,except: offensive_word = 2是什么意思?你正在创建一个什么都不做的变量。如果你想让你的except块为空,只需写下except: pass

© www.soinside.com 2019 - 2024. All rights reserved.