【问题标题】:Tkinter Not Opening WindowTkinter 不打开窗口
【发布时间】: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


【解决方案1】:

你可能想做这样的事情:

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()

随意调整此代码,如果您有任何问题 -> 询问

【讨论】:

  • 糟糕,当我在那里输入代码时,我的意思是除了 name == main 下的内容之外的所有内容都在掷骰子函数中
  • 另外你为什么要使用 lambda 作为按钮上的命令?
  • @KylenWilliams tbh idk 我应该了解一下,但您可以尝试不这样做,看看会发生什么
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-06-14
  • 2013-09-18
  • 2018-11-17
  • 2019-08-07
  • 2018-05-11
  • 2013-06-30
  • 1970-01-01
相关资源
最近更新 更多