简体   繁体   中英

Tkinter window showing up too early

I'm trying to build a binary lamp in Python using Tkinter. The steps are as follows:

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

However, this doesn't always work as I expect it to.

The code:

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

The bug: When I run this in my IDE (Wing 101), it patiently waits for me to input the number I want to show before drawing the image. However, if I run it straight from the python shell (ie I just click on bin_lamp.py) it opens and creates the tk window and shows a blank screen, without waiting for me to tell it what number I want.

After I actually enter the number, it draws what I want it to, but is there any way I can stop the blank tk window with the blank canvas from actually showing up until I'm done entering the input?

You can either put the input before you create the window with tk = Tk() , or you can leave everything as is, but hide the window and show it once it's done. Simply hide the window after it has been created and show it afterwards:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM