这里的第一个问题。
这是我的代码-
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,并在它们之间循环,而不是保持静态……
发布于 2021-07-20 05:18:44
您需要保存对该按钮的引用,以便可以对其调用configure方法。此外,我强烈建议使用比lambda更合适的函数,因为函数更容易阅读和调试。
def update_button():
button.configure(text=next(preset_numbers))
button = tk.Button(root, width = 20, command = update_button)
button.pack()发布于 2021-07-20 05:16:48
如果你想让按钮本身改变文本,我想这是一种方法:
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,如果=是关键字参数,则不要在它周围留空格
发布于 2021-07-20 05:16:34
你在找这样的东西吗?:
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来更改它的命令属性。
编辑:
一种更简单的方法:
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()使用这种方法,代码看起来会更好
https://stackoverflow.com/questions/68447069
复制相似问题