繁体   English   中英

在另一个函数中调用在一个函数中定义的变量,然后使用按钮重置变量

[英]calling a variable defined in one function in another and resetting a variable using a button

我的python GUI应用程序生成并显示一些随机值。 我有开始,停止和计算按钮。 我有randomGenerator函数。 我每秒都在打电话。 它生成两个值的列表。 我要追加此列表,以便获得列表列表。 我只想在按停止按钮后再次按开始时将此列表列表重置为空。 方法get_max_list应提供由randomGenerator生成的列表值的最大值。 如何将此列表值传递给get_max_list。 (对不起,我是python学习者)

import tkinter as tk
import random
import threading
start_status = False
calc_list=[]
rand = random.Random()

def randomGenerator():
    global calc_list
    if start_status:
        outputs = []
        Out1= rand.randrange(0,100,1)
        Out2= rand.randrange(0,100,1)
        outputs.append(Out1)
        outputs.append(Out2)

        output_1.set(Out1)  #to display in the GUI
        output_2.set(Out2)
        calc_list.append(outputs)       #i am trying to rest this to empty #when i press start after pressing stopping. 
        print(calc_list)
    win.after(1000, randomGenerator)

def start_me():
    global start_status
    start_status = True
    stopButton.config(state="normal")
    startButton.config(state="disabled")
    calcButton.config(state="disabled")
    calc_list=[]  #it doesn't work

def stop_me():
    global start_status
    start_status = False
    startButton.config(state="normal")
    stopButton.config(state="disabled")
    calcButton.config(state="normal")

def get_max_list(calc_list): #this doesn't work ?
    return [max(x) for x in zip(*calc_list)]
win = tk.Tk()
win.geometry('800x800')


output_1 = tk.StringVar()
output_2 = tk.StringVar()
output_1_label = tk.Label(win, textvariable=output_1)
output_1_label.place(x=200, y=100)

output_2_label = tk.Label(win, textvariable=output_2)
output_2_label.place(x=200, y=200)

startButton = tk.Button(win, text="Start" command = lambda:threading.Thread(target = start_me).start())
startButton.place(x=200, y=500)

stopButton = tk.Button(win, text="Stop", state=tk.DISABLED,  command= lambda:threading.Thread(target = stop_me).start())
stopButton.place(x=200, y=600)

calcButton = tk.Button(win, text="calculate", state=tk.DISABLED, command= lambda:threading.Thread(target = get_max_list).start())
calcButton.place(x=200, y=700)

win.after(1000, randomGenerator)
win.mainloop()

对于第一个问题,如前所述,您没有为列表calc_list声明global

def start_me():
    global start_status, calc_list
    ...
    calc_list=[]

对于您的get_max_list函数,它需要一个参数calc_list 您将需要通过修改thread lambda函数将列表作为参数提供:

calcButton = tk.Button(win, text="calculate", state=tk.DISABLED, command= lambda:threading.Thread(target = get_max_list,args=(calc_list,)).start())

或者只是让您的函数根本不使用arg:

def get_max_list():
    return [max(x) for x in zip(*calc_list)]

暂无
暂无

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

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