下面是我的代码的一个例子。
我正试图用tkinter在python中创建一个GUI。我想要一个有变量的应用程序,比如说var_list,它作为参数引入到函数中,我使用command=lambda: analize(var_list)按钮运行这个函数
我希望能够通过按下按钮(向列表中添加字符串的按钮)来修改变量。我也有一个功能:
def button_clicked(e):
if ((e["text"]).lower()) in var_list:
var_list.pop(var_list.index((e["text"]).lower())) #this adds a string to the list
else:
var_list.append((e["text"]).lower()) #this deletes the string from the list if it was already there该函数正常工作,我尝试打印var_list,每次按下按钮它都会更新。问题是我之前必须将var_list创建为空列表,当我运行函数analize(var_list)时,它使用的是空列表而不是更新的列表。
我每次从列表中添加/删除某些内容时,对如何更新全局变量有什么想法吗?
from tkinter import *
from PIL import ImageTk
def show_frame(frame):
frame.tkraise()
def button_clicked(e):
if ((e["text"]).lower()) in var_list:
var_list.pop(var_list.index((e["text"]).lower()))
else:
var_list.append((e["text"]).lower())
def analize(x):
#does stuff with the list
window = Tk()
frame1 = Frame(window)
frame2 = Frame(window)
canvas1 = Canvas(frame1,width = 1280, height = 720)
canvas1.pack(expand=YES, fill=BOTH)
image = ImageTk.PhotoImage(file="background.png")
var_list = []
button1 = Button(canvas1, text="Analize",font=("Arial"),justify=CENTER, width=10, command=lambda: [show_frame(frame2),analize(x=var_list)])
button1.place(x=(1280/2)-42, y=400)
button2 = Button(canvas1, text="String1",font=("Arial"),justify=CENTER, width=10, command=lambda: button_clicked(button2))
button2.place(x=(1280/2)-42, y=450)
button3 = Button(canvas1, text="String2",font=("Arial"),justify=CENTER, width=10, command=lambda: button_clicked(button3))
button3.place(x=(1280/2)-42, y=500)谢谢
发布于 2021-08-30 11:51:46
您可以创建一个全局变量例如:-global var,现在您可以在其他定义中访问它,以便像这样操作变量
global var
var = 0 # if you want to set a default value to the variable before calling the
function
def change_var():
global var
var = 1使用全局
强烈建议使用全局操作,如果您正在处理包含或需要操作变量的函数,则非常必要。
如果在函数中没有给出全局变量,则变量将驻留在函数中,并且不能在函数之外访问它。
希望这个答案是有帮助的,顺便说一句,我不确定这是否是你想要的答案,因为你的问题还不清楚,也许可以给出一个你认为有必要改变或更新变量的情况。
发布于 2021-08-30 10:09:16
抱歉,我不明白你的意思,但我想这个例子会对你有帮助-
import tkinter as tk
root = tk.Tk()
var_list = []
def change_val(n):
var_list.append(n)
label1.config(text=var_list)
def remove():
try:
var_list.pop()
label1.config(text=var_list)
except:
pass
label1 = tk.Label(root,text=var_list)
label1.pack()
button1 = tk.Button(root,text='1',command=lambda:change_val(1))
button1.pack()
button2 = tk.Button(root,text='2',command=lambda:change_val(2))
button2.pack()
button3 = tk.Button(root,text='3',command=lambda:change_val(3))
button3.pack()
button4 = tk.Button(root,text='Pop Element',command=remove)
button4.pack()
root.mainloop()https://stackoverflow.com/questions/68982106
复制相似问题