首页 > 解决方案 > Tkinter - 如何在函数之间切换列表?

问题描述

我想在函数中创建一个列表,并通过单击将一个值附加到该列表中Button

使用 按钮Check,我想检查列表的内容。但是这个函数中的列表可能是未知的。

你能用这个简单的例子解释一下我如何将列表从函数移交pressButton100给函数checkList()吗?

import tkinter as tk


# Define what happens when press Button100
def pressButton100():
    liste = []
    liste.append(100)

#Define what happens when press Button Check
def checkList(liste):
    pressButton100(liste)

# Create Window
app = tk.Tk()

# Create Button100
Button100 = tk.Button(app, text="100", command=lambda:pressButton100())
ButtonCheck = tk.Button(app, text="check", command=lambda:checkList())

# Pack Button100
Button100.pack()
ButtonCheck.pack()

# Mainloop
app.mainloop()

标签: pythonfunctiontkinterreturn

解决方案


首先,如果您想为按钮功能提供参数,您需要:

from functools import partial

并改变这个:

ButtonCheck = tk.Button(app, text="check", command=lambda:checkList())

进入这个:

ButtonCheck = tk.Button(app, text="check", command=partial(checkList, liste))

其次,为了实现访问您的目标liste,您必须定义liste globally,因此有一种方法:

import tkinter as tk
from functools import partial
 
# Define what happens when press Button100
liste = []
def pressButton100():
    global liste
    liste.append(100)

#Define what happens when press Button Check
def checkList(liste):
    pressButton100(liste)

# Create Window
app = tk.Tk()

# Create Button100
Button100 = tk.Button(app, text="100", command=lambda:pressButton100())
ButtonCheck = tk.Button(app, text="check", command=partial(checkList, liste))

# Pack Button100
Button100.pack()
ButtonCheck.pack()

# Mainloop
app.mainloop()

从 tkinter 按钮功能到另一个 tkinter 按钮功能是不可能的,因为它们有范围handover listelocal

并且partial()是一个有用的工具,它告诉按钮command正在接收parameter.

另外,另一种方法(解析liste每个按钮功能)是这样的(最佳方法):

liste = []
def pressButton100(liste):
    liste.append(100)

#Define what happens when press Button Check
def checkList(liste):
    pressButton100(liste)

Button100 = tk.Button(app, text="100", command=partial(pressButton100, liste))
ButtonCheck = tk.Button(app, text="check", command=partial(checkList, liste))

另一种方法是使用 OOP,为您的应用创建一个类:

import tkinter as tk

class TkinterApplication:
    def __init__(self):
        self.liste = []
        self.app = tk.Tk()
        self.Button100 = tk.Button(app, text="100", command=self.pressButton100)
        self.ButtonCheck = tk.Button(app, text="check", command=self.checkList)

        self.Button100.pack()
        self.ButtonCheck.pack()

    def pressButton100(self):
        self.liste.append(100)

    def checkList(self):
        self.pressButton100()

    def run(self):
        self.app.mainloop()

结果,liste将仅在您的应用程序类中具有全局范围。


推荐阅读