简体   繁体   English

我如何随机选择“ def”?

[英]How do i randomly chooce a “def”?

take a look at this python 3 code. 看一下这个python 3代码。

import random
from tkinter import *
from PIL import Image, ImageTk


def img1():

root = Tk()
root.geometry("400x400")

load = Image.open("1.png")
render = ImageTk.PhotoImage(load)
img = Label(image=render)
img.image = render
img.place(x=0,y=0)


def img2():

root = Tk()
root.geometry("400x400")

load = Image.open("2.png")
render = ImageTk.PhotoImage(load)
img = Label(image=render)
img.image = render
img.place(x=0,y=0)


def img3():

root = Tk()
root.geometry("400x400")

load = Image.open("3.png")
render = ImageTk.PhotoImage(load)
img = Label(image=render)
img.image = render
img.place(x=0,y=0)


def img4():

root = Tk()
root.geometry("400x400")

load = Image.open("4.png")
render = ImageTk.PhotoImage(load)
img = Label(image=render)
img.image = render
img.place(x=0,y=0)


def img5():

root = Tk()
root.geometry("400x400")

load = Image.open("5.png")
render = ImageTk.PhotoImage(load)
img = Label(image=render)
img.image = render
img.place(x=0,y=0)



def img6():

root = Tk()
root.geometry("400x400")

load = Image.open("6.png")
render = ImageTk.PhotoImage(load)
img = Label(image=render)
img.image = render
img.place(x=0,y=0)


List_img = [img1(), img2(), img3(), img4(), img5(), img6()]
random.choice(List_img)

I want to choose one image at random, but it keeps pushing all of them at once. 我想随机选择一张图像,但它会同时推动所有图像。

the last two lines are where it gets complicated. 最后两行很复杂。

I do not get an error. 我没有收到错误。

Im fairly new to python so be nice <3 我是python的新手,所以很好<3

(So I have too much code with little text and i have to add more so bear with me c;) (所以我的代码太多了,文本很少,我必须添加更多代码,所以请耐心等待c;)

If you only want to call one of the functions, put the functions themselves in the list, not the result of calling the functions. 如果只想调用其中一个函数,请将函数本身放在列表中,而不要放在调用函数的结果中。

The parentheses in img1() are how you call the function. img1()中的括号是调用函数的方式。 If you just want to treat the function itself as a value, that's just img1 . 如果您只想将函数本身视为值, img1 So: 所以:

List_img = [img1, img2, img3, img4, img5, img6]

And then, of course, you have to call the one you choose. 然后,当然,您必须调用您选择的那个。 In the same way that img1() means to call the function img1 , this: 以与img1()调用函数img1相同的方式,这是:

random.choice(List_img)()

… means to call whatever function gets chosen by random.choice . …意味着调用random.choice选择的任何函数。

The key idea here is that functions are “first-class values”—you can stick them in lists, pass them to functions, store them in variables, etc., just like you can with numbers or strings, and then you can call them later. 这里的关键思想是函数是“一流的值”-您可以将它们粘贴在列表中,将它们传递给函数,将它们存储在变量中,等等,就像使用数字或字符串一样,然后可以调用它们后来。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM