Python 每次程序启动时应用随机函数(来自其中的两个)
我创建了两个函数来更改应用程序的主题。以下是一些例子:Python 每次程序启动时应用随机函数(来自其中的两个),python,function,Python,Function,我创建了两个函数来更改应用程序的主题。以下是一些例子: def redtheme(): text.config(background="light salmon", foreground="red", insertbackground="red") def greentheme(): text.config(background="pale green", foreground="dark green", insertba
def redtheme():
text.config(background="light salmon", foreground="red",
insertbackground="red")
def greentheme():
text.config(background="pale green", foreground="dark green",
insertbackground="dark green")
def bluetheme():
text.config(background="light blue", foreground="dark blue",
insertbackground="blue")
(text是文本小部件的名称)
我想创建一个函数,使这些函数中的任意一个在应用程序启动时运行。
换句话说,我想要一个在应用程序启动时执行的函数,该函数将从random.choice()
中选择一个函数并执行该函数:
full = (redtheme, greentheme, bluetheme)
selected = random.choice(full)
# here, it could be text.config(full)?? or what?
我如何使这三个函数中的一个在应用程序启动时执行,正如下面的注释中所建议的那样代码是您想要的一个小示例:
import tkinter as tk
import random
root = tk.Tk()
text = tk.Text(root)
def redtheme():
text.config(background="light salmon", foreground="red",
insertbackground="red")
def greentheme():
text.config(background="pale green", foreground="dark green",
insertbackground="dark green")
def bluetheme():
text.config(background="light blue", foreground="dark blue",
insertbackground="blue")
full = (redtheme, greentheme, bluetheme)
selected = random.choice(full)
selected()
text.pack()
root.mainloop()
上面的代码基本上利用了一个事实,即您可以将函数引用分配给变量,这里函数名称引用中的随机选择首先分配给selected
,然后将selected
作为函数调用
另外,请参见下面的随机函数调用示例:
random.choice((redtheme, greentheme, bluetheme))()
只需在
mainloop
之前调用selected
,因为它是列表中的随机函数。