【问题标题】:How do I print the random outcome of an entry input in a list?如何打印列表中条目输入的随机结果?
【发布时间】:2020-12-03 16:38:01
【问题描述】:

代码

list = [ee1.get(), ee2.get(), ee3.get(), ee4.get(), ee5.get(), ee6.get(), ee7.get(), ee8.get(), ee9.get(), ee10.get()]
context = "What does", random.choice(list),"mean?"
labelquestion = Label(window, text = context, font = "Serif 10 bold")

问题

当我运行它时,它会输出"{What does} {} mean?"

如何解决这个问题,使其输出"What does"-random entry from list-"this mean?" (列表中的东西都是条目)

【问题讨论】:

  • 看起来这就是这段代码正在做的事情......你能发布一些minimal reproducible example吗?另外,尽量避免命名变量,如内置名称,如list
  • 随机拉的ee好像是个空白对象。你确定 .get() 返回你想要的字符串吗?
  • 这是因为context 是一个元组。请改用context = f'What does "{random.choice(list)}" mean?'。顺便说一句,不要使用关键字 (list) 作为变量名。
  • @acw1668 我已经按照你说的做了并且已经改进了,但是现在打印"What does "" mean?"它不打印条目的输入。
  • 请显示此代码的运行方式/时间。如果它没有显示数据,它可能在用户有机会输入任何内容之前运行。

标签: python tkinter python-3.7


【解决方案1】:

以下是基于您的代码和评论中的信息的示例:

import tkinter as tk
import random

window = tk.Tk()

ee1 = tk.Entry(window)
ee1.grid(row=0, column=0)

ee2 = tk.Entry(window)
ee2.grid(row=0, column=1)

ee3 = tk.Entry(window)
ee3.grid(row=0, column=2)

ee4 = tk.Entry(window)
ee4.grid(row=0, column=3)

ee5 = tk.Entry(window)
ee5.grid(row=0, column=4)

ee6 = tk.Entry(window)
ee6.grid(row=1, column=0)

ee7 = tk.Entry(window)
ee7.grid(row=1, column=1)

ee8 = tk.Entry(window)
ee8.grid(row=1, column=2)

ee9 = tk.Entry(window)
ee9.grid(row=1, column=3)

ee10 = tk.Entry(window)
ee10.grid(row=1, column=4)

def submit():
    words = [ee1.get(), ee2.get(), ee3.get(), ee4.get(), ee5.get(), 
             ee6.get(), ee7.get(), ee8.get(), ee9.get(), ee10.get()]
    context = f"What does '{random.choice(words)}' mean?"
    labelquestion.config(text=context)

tk.Button(window, text="Submit", command=submit).grid(row=2, column=0, sticky='w')

labelquestion = tk.Label(window, font="Serif 10 bold")
labelquestion.grid(row=2, column=1, columnspan=4)

window.mainloop()

【讨论】:

  • 使用将行和列作为参数然后循环行和列+填充列表而不是10个变量的函数会更好吗? :)
  • @Ruli 我只是想模拟 OP 代码,以显示如果这些条目有输入,然后单击按钮触发功能,context 不应显示来自random.choice() 的空字符串。
猜你喜欢
  • 1970-01-01
  • 2020-07-24
  • 2018-11-09
  • 2022-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多