如何解决Tkinter不打开窗口
我正在创建一个程序,该程序允许用户制作自定义骰子,但是当我打开一个带有调用后端骰子滚动逻辑的按钮的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",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()
解决方法
您可能想要执行以下操作:
import tkinter as tk
from random import choice
root = tk.Tk()
root.geometry('400x600')
root.resizable(False,False)
root.config(bg='light blue')
dice_numbers = [1,2,3,4,5,6]
rolled_nums = []
def roll():
if len(rolled_nums):
rolled_nums[0].pack_forget()
rolled_nums.pop(0)
chosen_number = choice(dice_numbers)
text = tk.Label(root,text=f'{chosen_number}',font='arial 500 bold',bg='light blue')
text.pack()
rolled_nums.append(text)
button = tk.Button(root,text='Roll Dice!',font='arial 20 bold',relief='raised',width='300',bg='dark red',fg='black',command=lambda: roll())
button.pack()
root.mainloop()
随意调整此代码,如果有疑问->询问
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。