You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python基于Tkinter实现点击按钮从SQLite随机提取词汇展示功能

Tkinter+SQLite随机抽词功能实现代码

以下代码默认你现有项目中已存在如下可直接调用的对象,若变量名和你实际代码不一致,替换为你自己的变量名即可:

  • Tk主窗口对象:示例中命名为root
  • 多行Text文本框组件:示例中命名为text_box
  • 已完成连接的SQLite连接对象:示例中命名为conn

功能1:Button1点击抽Word1词汇实现

def get_random_word1():
    # 清空文本框原有内容
    text_box.delete(1.0, "end")
    cursor = conn.cursor()
    # 数据库层面随机排序后取第一条,效率更高
    cursor.execute("SELECT Word1 FROM TableExample ORDER BY RANDOM() LIMIT 1")
    result = cursor.fetchone()
    if result:
        text_box.insert("end", result[0])
    cursor.close()

功能2:Button2点击抽Word2+Word3拼接实现

def get_random_combined_word():
    text_box.delete(1.0, "end")
    cursor = conn.cursor()
    # 分别随机抽取两个列的词汇
    cursor.execute("SELECT Word2 FROM TableExample ORDER BY RANDOM() LIMIT 1")
    word2 = cursor.fetchone()
    cursor.execute("SELECT Word3 FROM TableExample ORDER BY RANDOM() LIMIT 1")
    word3 = cursor.fetchone()
    if word2 and word3:
        # 拼接为带空格的字符串
        combined_str = f"{word2[0]} {word3[0]}"
        text_box.insert("end", combined_str)
    cursor.close()

按钮事件绑定示例

你现有按钮的创建代码中修改command参数绑定对应函数即可:

# 绑定Button1
button1 = tk.Button(root, text="抽取单个词汇", command=get_random_word1)
# 绑定Button2
button2 = tk.Button(root, text="抽取组合词汇", command=get_random_combined_word)

注意事项:

  1. 程序退出前记得执行conn.close()关闭数据库连接,避免资源泄漏
  2. 代码已内置空数据判空逻辑,表内无数据时不会抛出异常
  3. 若你需要保留文本框历史内容,删除text_box.delete(1.0, "end")这行即可

内容的提问来源于stack exchange,提问作者Giovanni Russo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.16 18:15:08