首页 > 解决方案 > Tkinter 按钮循环浏览列表

问题描述

我是一个零编码经验的完整新生儿。到目前为止,我已经摸索并设法使用 tkinter 创建了一个带有框架和标签的 GUI。我试图弄清楚如何创建一个按钮,每次单击时其标签都会更改以重复循环浏览列表。任何帮助将不胜感激。

标签: pythontkinter

解决方案


另一种改变颜色的方法(只是与@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,所以这里是如何将它减少到两行:importand 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 代码,但如果你想向你的朋友炫耀......你可以在一行中做到这一点......这就是你如何做到的。


资料来源:

PS如果你正在学习python,我真的建议Corey Schafer教程,IMO他们很棒


推荐阅读