#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的经历
答案 0 :(得分:0)
您希望始终在程序顶部导入模块,这样您的代码就更容易阅读。
要显示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。我希望这是你正在寻找的答案。干杯