python - 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()
解决方案
首先,如果您想为按钮功能提供参数,您需要:
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
liste
local
并且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
将仅在您的应用程序类中具有全局范围。
推荐阅读
- laravel - 首次在 Heroku 上部署 Laravel 5.7 时出错
- neo4j - 在导入 CSV 时为节点的属性创建列表类型集合
- python - Python selenium 未在 Chrome 中显示证书错误页面
- python - 在 Keras 预测后显示百分比
- hazelcast-jet - hazelcast jet 是否从集群发送/接收数据
- php - 由于单选按钮错误,我的数据没有插入数据库
- docker - var/jenkins_home 文件夹在哪里?
- java - 从 Android Volley 请求在 Spring Boot 中使用和生成 JSON 数据的正确方法是什么
- javascript - 测试带有函数的 React 组件 setState 重载
- c++ - 更新 GCC 和提升 RedHat 7.6 的最佳实践