【问题标题】:Tkinter window showing up too earlyTkinter 窗口显示得太早
【发布时间】:2020-12-14 05:36:06
【问题描述】:

我正在尝试使用 Tkinter 在 Python 中构建二进制灯。 步骤如下:

    1. Prompt user for input, using the console/shell.
    2. Draw the lamp
    3. Use mainloop to show the image

但是,这并不总是像我期望的那样工作。

代码:

    from tkinter import *

    HEIGHT = 235
    WIDTH = 385

    tk = Tk()
    canvas = Canvas(tk, width=WIDTH, height=HEIGHT, bg="grey")


    size = 35

    canvas.pack()
    def dec_to_binh(num, lst):
        if num>1:
            dec_to_binh(num // 2, lst)
        lst.append(num%2)
        return lst
    def dec_to_bin(num):
        answ = dec_to_binh(num, [])
        while len(answ) < 4:
            answ.insert(0,0)
        return answ
    class Diode:
        def __init__(self, x, y, label):
            self.shape = canvas.create_oval(x, y, x+size, y+size, width=4,
                                    outline='black', fill='#232323')
            self.label = canvas.create_text(x+int(size/2), y+size+10, text=str(label))
            self.onOff = 0
        def update(self, num):
            if int(num) == 1:
                canvas.itemconfig(self.shape, fill=oncolor)
                onOff = 1
            else:
                canvas.itemconfig(self.shape, fill='black')
                onOff = 0

    class Lamp:
        def __init__(self):
            self.LEDs = [Diode(100, 100, 8), Diode(150, 100, 4), Diode(200, 100, 2), Diode(250, 100, 1)]
    
        def update(self, number):
            n=0
            for i in self.LEDs:
                i.update(dec_to_bin(number)[n])
                n=n+1


    print("What to show as a binary lamp?")

    answer=int(input())
    while answer > 15 or answer < 0:
        print("Invalid input, can only show between range of 0 to 15 inclusive")
        answer=int(input())
    lamp = Lamp()
    lamp.update(answer)

    tk.mainloop()

错误: 当我在我的 IDE(Wing 101)中运行它时,它会耐心地等待我输入要显示的数字,然后再绘制图像。 但是,如果我直接从 python shell 运行它(即我只需单击 bin_lamp.py),它会打开并创建 tk 窗口并显示一个空白屏幕,而无需等待我告诉它我想要什么数字。

在我实际输入数字后,它会绘制我想要的内容,但是有什么方法可以阻止带有空白画布的空白 tk 窗口实际显示,直到我完成输入?

【问题讨论】:

  • 尝试在创建Tk() 的实例之前放置控制台输入部分。顺便说一句,最好不要将控制台输入与 GUI 混合。

标签: python tkinter tkinter-canvas wing-ide


【解决方案1】:

您可以在使用tk = Tk() 创建窗口之前输入输入,或者您可以保留所有内容,但隐藏窗口并在完成后显示它。只需在创建后隐藏窗口并在之后显示它:

tk = Tk()
tk.withdraw()
# do all your processing
tk.deiconify()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-12
    • 1970-01-01
    • 2016-07-27
    • 2018-01-08
    • 2014-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多