【问题标题】:How do i display my results in the GUI?如何在 GUI 中显示我的结果?
【发布时间】:2017-12-25 04:32:55
【问题描述】:
#this picks a random number
def roll_dice():
    from random import randint
    for x in range(2):
        print(randint(1,6))
#this makes the GUI
from tkinter import *
root = Tk()
root.title('first GUI')
root.geometry('500x500')
app = Frame(root)
app.grid()
label = Label(app, text = 'Dice Simulator')
label.grid()
button1 = Button(app, text = 'Roll Dice', command = roll_dice)
button1.grid()
root.mainloop()

我用它来模拟掷两个骰子并显示结果。这是我作为程序员的第一个项目,也是我制作 tkinter 的第一次体验

【问题讨论】:

标签: python python-3.x tkinter


【解决方案1】:

您希望始终在程序顶部导入模块,这样您的代码更易于阅读。

要显示来自roll_dice 的结果,您首先需要在一个文本框中显示结果。我打电话给这个盒子output你可以这样做:

output = Text(root, height=1, width=5) #create the output box
output.place(x=100,y=100) #place the output box at desire place on the UI

现在要在output 框中显示结果,我们可以使用insert Tkinter 函数。执行以下操作:

output.delete('1.0', END)     #clears the output box
output.insert(END, randint(1,6))   #insert the result into the

使用您的代码,它应该如下所示:

def roll_dice():
    for x in range(2):
        output.delete('1.0', END)     #clears the output box
        output.insert(END, randint(1,6))   #insert the result into the output box
#this makes the GUI


root = Tk()
root.title('first GUI')
root.geometry('500x500')
app = Frame(root)
app.grid()
label = Label(app, text = 'Dice Simulator')
label.grid()
button1 = Button(app, text = 'Roll Dice', command = roll_dice)
button1.grid()
output = Text(root, height=1, width=5) #create the output box
output.place(x=100,y=100) #place the output box at desire place on the UI

root.mainloop()

结果:

欢迎来到 StackOverflow。我希望这是您正在寻找的答案。干杯

【讨论】:

  • 如果您要使用网格,请使用row/column = number。网格不应该像包一样使用。如果您想使用这样的基本示例,请改用pack()
猜你喜欢
  • 2021-10-22
  • 2010-10-21
  • 1970-01-01
  • 2010-11-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-24
  • 1970-01-01
  • 2021-12-10
相关资源
最近更新 更多