python - Tkinter 按钮循环浏览列表
问题描述
我是一个零编码经验的完整新生儿。到目前为止,我已经摸索并设法使用 tkinter 创建了一个带有框架和标签的 GUI。我试图弄清楚如何创建一个按钮,每次单击时其标签都会更改以重复循环浏览列表。任何帮助将不胜感激。
解决方案
另一种改变颜色的方法(只是与@TheLizzard略有不同的方法):
import tkinter as tk
from itertools import cycle
def change_button():
text = next(texts)
button.config(text=text, fg=text)
texts = cycle(["red", "orange", "blue", "black"])
root = tk.Tk()
button = tk.Button(root, command=change_button)
change_button()
button.pack()
root.mainloop()
这里使用了内置模块中的函数itertools
: cycle
,它返回一个迭代器,基本上允许无限循环其中的项目。
另一种有趣的单行方法(Python 3.8+ 版本)change_button()
使用海象运算符 ( :=
) 替换函数中的两行,它基本上返回值并同时将其分配给变量(顺便说一下,这种方法与以下是完全可以接受的):
def change_button():
button.config(text=(text := next(texts)), fg=text)
编辑:
如果你真的想压缩它,你可以简单地这样做(不需要change_function()
在一行中定义 and ):
button = tk.Button(root, text=(t := next(texts)), fg=t, command=lambda: button.config(text=(text := next(texts)), fg=text))
甚至这个(与上面相同,但现在按钮也打包在同一行中(但是在这里你必须使用海象运算符,否则button = None
)):
(button := tk.Button(root, text=(t := next(texts)), fg=t, command=lambda: button.config(text=(text := next(texts)), fg=text))).pack()
EDIT2:我今天遇到了这个并记得上面的方法确实将代码减少到 3 行:import cycles
, assign iterator
, define button and pack it, and assign commands to it
,所以这里是如何将它减少到两行:import
and button with iterator, with command and gets packed
:
(button := tk.Button(root, text=(t := next(texts := cycle(["red", "orange", "blue", "black"]))), fg=t, command=lambda: button.config(text=(text := next(texts)), fg=text))).pack()
现在它真的很短,但是您可以通过移动导入来缩短它(因为在初始化Tk
实例后按钮必须保持原位)所以将导入移动到按钮旁边(现在实际上只有一行大约循环和更改按钮的颜色和文本):
from itertools import cycle; (button := tk.Button(root, text=(t := next(texts := cycle(["red", "orange", "blue", "black"]))), fg=t, command=lambda: button.config(text=(text := next(texts)), fg=text))).pack()
注意:
虽然可能,但我真的不建议使用上述方法(最后 4 种(在此处的两条微妙线之间)),它们使代码非常不可读,并且(尤其是最后一种)破坏PEP 8 - 样式指南对于 Python 代码,但如果你想向你的朋友炫耀......你可以在一行中做到这一点......这就是你如何做到的。
资料来源:
next()
官方文档(也许不是那么容易理解)- Corey Schafer 关于迭代器的教程(在他谈论的地方加盖时间戳
next()
) - Corey Schafer 的教程
itertools
(在他所说的地方加盖时间戳cycle
) :=
Lex Fridman关于海象算子 ( ) 的视频
PS如果你正在学习python,我真的建议Corey Schafer教程,IMO他们很棒
推荐阅读
- twitter-bootstrap - 如何使用 Bootstrap 使导航栏切换按钮/下拉菜单在“sm”屏幕尺寸下工作?
- jquery - JQuery 多步进度条:next_fs 问题
- java - 如何在其他类中显示来自 JTextField 的文本?
- java - 用 JFreeChart 实现蜘蛛图
- ios - 更改 iOS Xamarin 表单上的导航栏高度?
- java - @ResponseBody,不要尊重对象的构造函数
- postgresql - 橙色(数据挖掘)psycopg2 使用 postgresql 12.2 连接失败“不支持的前端协议”
- javascript - 一个属性值可以作为参数传递给另一个属性,其值是通过函数计算的吗?(在带有类的 Javascript ES6 中)
- r - 如何为我的 3 个图在一张图中拟合一条线性回归线?
- c++ - 为什么没有执行其中一个 while 循环(C++)?