简体   繁体   中英

How do i randomly chooce a “def”?

take a look at this python 3 code.

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

(So I have too much code with little text and i have to add more so bear with me 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. If you just want to treat the function itself as a value, that's just 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:

random.choice(List_img)()

… means to call whatever function gets chosen by 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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