如何使用字符串作为变量?

时间:2019-11-19 19:10:54

标签: python tkinter

我正在尝试创建一个函数,该函数将基于小部件的状态和小部件本身来更改Tkinter小部件的文本。在此函数中,我还需要更改作为变量使用的状态值,以便以后更改它,因此它不仅适用于一种情况。到目前为止,这是我所拥有的,并且不起作用,因为当我对变量进行全局化时,它表示它是参数并且是全局变量。我知道这是很基本的东西,我知道这行不通,但是我想知道是否有办法解决这个感谢!

from tkinter import*
from definitions import*

root = Tk()
root.title("Chemistry Tool")
root.iconbitmap('favicon.ico')

#### MODLE (Data,Methods) ####
state_1 = 0


def drop_down(state, state_var, button):
    global setattr(state_var)
    if state == 0:
        button.config(text="↓")
        state_var = 1
    else:
        button.config(text="→")
        state_var = 0



#### Controlers (Widgets that change data) ####
drop1 = Button(root, text="→", bg="WHITE", command= lambda: drop_down(state_1, "state_1", drop1))
drop1.grid(row=0, column=0, sticky=N)

#### VIEW (Widgets that display outputs) ####
display = Text(root, bg="WHITE")
display.grid(row=0, column=2, columnspan=2, rowspan=2, sticky=SE)

root.mainloop()

输出:

  File "D:/Devlopment/Python/AP-Computer-Science-Project-1/main.py", line 13
    global setattr(state_var)
                  ^
SyntaxError: invalid syntax

2 个答案:

答案 0 :(得分:0)

我只是不基于文本的实际值进行更改,而不是根据上面使用的名为state的变量使用的系统。

from tkinter import*
from definitions import*

root = Tk()
root.title("Chemistry Tool")
root.iconbitmap('favicon.ico')

#### MODLE (Data,Methods) ####


def drop_down(button):
    if button['text'] == "→":
        button.config(text="↓")
    elif button['text'] == "↓":
        button.config(text="→")
        state_var = 0
    print(button['text'])



#### Controlers (Widgets that change data) ####
drop1 = Button(root, text="→", bg="WHITE", width=2, command= lambda: drop_down(drop1))
drop1.grid(row=0, column=0, sticky=N)

#### VIEW (Widgets that display outputs) ####
display = Text(root, bg="WHITE")
display.grid(row=0, column=2, columnspan=2, rowspan=2, sticky=SE)

root.mainloop()

答案 1 :(得分:0)

您可以将元素的状态存储在字典中,并传递该字典的密钥:

from tkinter import*
from definitions import*

root = Tk()
root.title("Chemistry Tool")
root.iconbitmap('favicon.ico')

#### MODLE (Data,Methods) ####
state_1 = 0

states = {"state_1" : 0}

def drop_down(state_var, button):
    if states[state_var] == 0:
        button.config(text="↓")
        states[state_var] = 1
    else:
        button.config(text="→")
        states[state_var] = 0



#### Controlers (Widgets that change data) ####
drop1 = Button(root, text="→", bg="WHITE", command= lambda: drop_down("state_1", drop1))
drop1.grid(row=0, column=0, sticky=N)

#### VIEW (Widgets that display outputs) ####
display = Text(root, bg="WHITE")
display.grid(row=0, column=2, columnspan=2, rowspan=2, sticky=SE)

root.mainloop()