Tkinter按钮编号循环Tkinter问题

2024-06-01 11:16:43 发布

您现在位置:Python中文网/ 问答频道 /正文

这里的第一个问题

这是我的密码-

import tkinter as tk
from tkinter import *
from itertools import cycle

root = Tk()
root.geometry("200x200")
root.title("Button: 0, 1 and 2.")

preset_numbers = cycle(["0", "1", "2"])

lbl = tk.Label(root, text = next(preset_numbers), width=20)
lbl.pack()

tk.Button(root, width = 20, command = lambda: lbl.config(text = next(preset_numbers))).pack()

root.mainloop()

我有点困惑,我怎么能让按钮本身显示0 1 2,并在它们之间循环,而不是保持静止


Tags: textfromimport密码tkinterbuttonrootwidth
3条回答

您需要保存对按钮的引用,以便可以对其调用configure方法。另外,我强烈建议使用比lambda更合适的函数,因为函数更易于阅读和调试

def update_button():
    button.configure(text=next(preset_numbers))

button = tk.Button(root, width = 20, command = update_button)
button.pack()

你在找这样的东西吗

import tkinter as tk
from tkinter import *
from itertools import cycle

root = Tk()
root.geometry("200x200")
root.title("Button: 0, 1 and 2.")

preset_numbers = cycle((0, 1, 2))

button = tk.Button(root, width=20, text=next(preset_numbers))
# Please note that the `button.pack()` is on its own line.
button.pack()

button.config(command=lambda: button.config(text=next(preset_numbers)))

root.mainloop()

它将按钮分配给名为button的变量。然后,它对其调用.config,以更改其命令属性。同样正如@BryanOakley所说的,如果使用函数而不是lambda,那么调试就会容易得多


编辑:

更简单的方法是:

import tkinter as tk
from tkinter import *
from itertools import cycle

def change_buttons_text():
    button.config(text=next(preset_numbers))

root = Tk()
root.geometry("200x200")
root.title("Button: 0, 1 and 2.")

preset_numbers = cycle((0, 1, 2))

text = next(preset_numbers)
button = tk.Button(root, width=20, text=text, command=change_buttons_text)
button.pack()

root.mainloop()

使用此方法,代码看起来更好

如果您想让按钮本身更改文本,我想这是一种方法:

import tkinter as tk
from itertools import cycle

root = tk.Tk()
root.geometry("200x200")
root.title("Button: 0, 1 and 2.")

preset_numbers = cycle((1, 2, 3))

btn = tk.Button(root, text=next(preset_numbers), width=20, 
                command=lambda: btn.config(text=next(preset_numbers)))
btn.pack()

root.mainloop()

有几件事值得一提:

我强烈建议不要使用通配符(*)当导入一些东西时,你应该要么导入你需要的东西,例如from module import Class1, func_1, var_2等等,要么导入整个模块:import module然后你也可以使用别名:import module as md或者类似的东西,关键是除非你真正知道你在做什么,否则不要导入所有东西;名字冲突是个问题

另外,我建议遵循PEP8,如果它是一个关键字参数,那么在=周围不要有空格

相关问题 更多 >