【发布时间】: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