当在Tkinter中按下给定按钮时,我无法触发随机功能

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了当在Tkinter中按下给定按钮时,我无法触发随机功能相关的知识,希望对你有一定的参考价值。

我正在创建一个按钮,它将在Python中的tkinter模块中显示一条消息。

At first, the button has text on it. When it is clicked, it will display a messagebox. A messagebox is a "pop-up" or "error message."

下面的代码将显示执行上述句子的示例函数。

def joke1():
    messagebox.showinfo(title = "There are three types of people in this world", message = "Those who can count and those who can't.")

root = Tk()
root.title("Joke Board 1.0 by Jamlandia")
root.iconbitmap(r"C:UsersVMWZhDownloadsIcons8-ios7-Messaging-Lol.ico")
button = Button(text = "There are three types of people in this world", bg = '#42f474', fg = 'black', command = joke1)
test = Button()

button.grid(column = 0, row = 0)

test.grid(column = 1, row = 0)
root.mainloop()

我无法找到一种方法来对其进行编码,这样当你按下按钮时,它将运行与按钮上显示的笑话相关的函数,然后随机绑定到一个新函数,并将文本更改为与该功能相关的笑话。

答案

问题:按下按钮,......随机...改成笑话

tkinter — Python interface to Tcl/Tk

The Python Tutorial and Python Module


Joke上单击显示随机Button,没有messagbox

import tkinter as tk
import random

class App(tk.Tk):
    def __init__(self):
        super().__init__()

        self.joke_index = 0
        self.jokes = [("There are three types of people in this world", "Those who can count and those who can't."),
                      ('Grew up with six brothers', 'That’s how I learned to dance–waiting for the bathroom'),
                      ('Always borrow money from a pessimist.', 'He won’t expect it back.')
                      ]

        self.label1 = tk.Label(self)
        self.label1.grid(row=0, column=0, pady=3)

        self.label2 = tk.Label(self)
        self.label2.grid(row=1, column=0, pady=3)

        button = tk.Button(self,
                           text='Show next Joke',
                           command=self.show_random_joke,
                           bg='#42f474', fg='black'
                           )
        button.grid(row=2, column=0, pady=3)

    def show_random_joke(self):
        v = -1
        while v == self.joke_index:
            v = random.randrange(0, len(self.jokes)-1)
        self.joke_index = v

        self.label1['text'], self.label2['text'] = self.jokes[self.joke_index]

if __name__ == "__main__":
    App().mainloop()

用Python测试:3.5

以上是关于当在Tkinter中按下给定按钮时,我无法触发随机功能的主要内容,如果未能解决你的问题,请参考以下文章

在 Python Tkinter 中按下按钮后如何清除窗口?

确定在 Tkinter 中按下了哪个按钮?

在 Tkinter 中按下按钮后如何清除 Entry 小部件?

在 chrome 中按下鼠标按钮时无法应用悬停样式

在SwiftUI中按下按钮时的随机图像[关闭]

如何在python tkinter中按下按钮之前使窗口状态空闲?