有没有一种方法可以根据是否有人按下按钮来做出条件声明(tkinter)

时间:2020-02-29 15:35:12

标签: python list tkinter

这是我的代码:

    root = tkinter.Tk()

    canvas = tkinter.Canvas(root, width=960, height=720)
    image = ImageTk.PhotoImage(Image.open('TitleScreen.png'))

    canvas.create_image(0, 0, anchor=tkinter.NW, image=image)
    canvas.create_text(485, 375, font=("Times", 25, 'bold'),
                       text='You live in Valencia, Venezuela. You have 2 kids, and a '
                            '\n'
                            'significant other. You barely have enough money to take care '
                            '\n'
                            'of your family, food is running out, and electricity outages '
                            '\n'
                            'are a daily occurrence. Do you  want to leave in search '
                            '\n'
                            'of a better life? [y/n]', fill='white')

    y = Button(root, text='Y', command=buttonFunctionY, bg='black', bd=5, font=('Times', 20), activebackground='blue',
               activeforeground='black', fg='black')
    y.place(x=435, y=465)

    n = Button(root, text='N', command=buttonFunctionN, bg='black', bd=5, font=('Times', 20), activebackground='blue',
               activeforeground='black', fg='black')
    n.place(x=485, y=465)

    if option == 'y':
        canvas.create_image(0, 0, anchor=tkinter.NW, image=image)
        canvas.create_text(485, 375, font=("Times", 25, 'bold'),
                           text='Great, good decision. First should you prepare for the trip by buying supplies? [y/n]',
                           fill='white')

    canvas.pack()

    root.mainloop()

我的主要问题临近尾声,我试图根据是否按下按钮来创建条件,但是我不知道该怎么做。

1 个答案:

答案 0 :(得分:0)

您必须在回调函数内而不是在按钮对象初始化下方定义单击时的反应。可能您已定义buttonFunctionY。如果是这样,则在函数中添加行以输出“ good choice”文本。否则,定义该buttonFunctionY函数(在按钮中使用之前,但在导入之后)。令人惊讶的是,有时在Python中,您必须先定义函数,然后脚本才能真正使用它们。

def buttonFunctionY():
        canvas.create_image(0, 0, anchor=tkinter.NW, image=image)
        canvas.create_text(485, 375, font=("Times", 25, 'bold'),
                           text='Great, good decision. First should you prepare for the trip by buying supplies? [y/n]',
                           fill='white')