python - 在 Tkinter 中按下给定按钮时,我无法触发随机功能
问题描述
我正在制作一个按钮,它将在 Python 的 tkinter 模块中显示一条消息。
起初,按钮上有文字。单击它时,它将显示一个消息框。消息框是“弹出”或“错误消息”。下面的代码将显示一个执行上述语句的示例函数。
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:\Users\VMWZh\Downloads\Icons8-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 — Tcl/Tk 的 Python 接口
Python 教程和 Python 模块
点击时随机 显示,没有.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
推荐阅读
- laravel - Laravel 7 - Eloquent ORM 在使用一对一关系时从 2 个表中获取数据
- android - ViewPager2:监听 setCurrentItem() 完成
- java - 指令被跳过,这里有没有我没有看到的错误?
- javascript - 在 FireStore 中查询空字段
- java - Glassfish4:由于war文件中WEB-INF/lib/jackson-*.jar中的Java9 module-info.class而出现异常?
- python - Tensorboard 仅显示嵌入层的 8 个节点
- python - 你如何使用从`ImageFont.getmask`返回的`Image.core`?
- .net - 从当前正在构建的程序集中检索使用 GenericTypeParameterBuilder 类型的函数(委托)类型
- arrays - 创建一个函数,在数组中查找基于 Lat long 的最近对象
- python - 检查字符串是否包含特定的特殊字符、字母数字字符并以字母结尾