【发布时间】:2021-02-15 03:34:54
【问题描述】:
我正在创建一个允许用户制作自定义骰子的程序,但是当我打开一个带有调用后端骰子掷骰逻辑的按钮的 GUI 窗口时,它会中断。换句话说,窗口没有打开,代码只是在终端中运行。当按钮像我想要的那样被单击时不会发生这种情况,而是当我运行代码时,它不会打开任何 GUI 窗口并且代码在终端中执行。代码在没有 GUI 的情况下工作,如果我取出骰子按钮回调,GUI 可以工作,但不能一起工作。
感谢任何帮助!
import random
import tkinter as tk
def dice_roll():
dice = []
x = 0
# used to check if the input is a whole number, if it isn't, you get a message
while True:
while x == 0:
try:
SIDE_AMT = int(input("How many sides would you like? (min is 2, max is infinite): ")) # amt is amount
x = 1
except ValueError:
print("Sorry it has to be a whole number.")
if SIDE_AMT > 1:
for side in range(SIDE_AMT):
print(f"What would you like side {side + 1} to be?:")
dice.append(str(input()))
break
else:
print("You can't have a dice with one side!")
x = 0
# roll function
def roll():
dice_side = random.choice(dice)
print(f"I choose {dice_side}!")
roll_num = 0
while True:
if roll_num == 0:
spin_it = str(input("Type 'roll' if you would like to roll the dice: "))
if spin_it == "roll":
roll()
else:
print("Sorry, you have to type roll correctly.")
roll_num += 1
elif roll_num == 1:
while True:
spin_it = str(input("Type 'roll' if you would like to roll the dice again!: "))
if spin_it == "roll":
roll()
else:
print("Sorry, you have to type roll correctly.")
if __name__ == '__main__':
gui = tk.Tk()
gui.title("Dice Roll")
gui.geometry("1912x1090")
gui.configure(bg='#a2a2a1', borderwidth=5,
relief="raised")
# title
title = tk.Label(gui, text='Unique Dice', font=("Times
New Roman", 52))
title.configure(bg='#a2a2a1', fg='#195190',
borderwidth=3, relief='raised')
# make a dice?
dice = tk.Button(gui,
text="Yes!",
fg="red",
command=dice_roll())
no_dice = tk.Button(gui,
text="No",
fg="red",
command=quit)
# frame = tk.Frame(gui, height=200, width=200)
# frame['borderwidth'] = 10
# frame['relief'] = 'sunken'
# frame.pack()
dice.pack()
no_dice.pack()
title.pack()
gui.mainloop()
【问题讨论】:
-
首先在
if __name__ == '__main__':你应该只放置主要函数,因为有一个while循环阻塞它,所以部分代码永远不会被执行 -
你还想展示什么?
-
它不会打开任何 GUI,因为脚本在循环中运行
标签: function user-interface button tkinter window