我在此代码思路运行与Tkinter的那取决于我按下键盘上数字的”七段显示灯的应用程序。
import tkinter as tk
import keyboard
import time
from PIL import ImageTk, Image
def main():
window = tk.Tk()
window.title("AutoSegment")
window.geometry("459x767")
path=r"C:\Users\The Man Himself\Desktop\SSG\welcome.jpg"
img = ImageTk.PhotoImage(Image.open(path))
panel = tk.Label(window, image = img).pack(side = "bottom", fill = "both", expand = "yes")
listener()
tk.mainloop()
def set(name):
path=r"C:\Users\The Man Himself\Desktop\SSG\%s.jpg" %name
img = ImageTk.PhotoImage(Image.open(path))
panel = tk.Label(window, image = img).pack(side = "bottom", fill = "both", expand = "yes")
listener()
tk.mainloop()
def listener():
while True:
try:
if keyboard.is_pressed('1'):
set("1")
break
elif keyboard.is_pressed('2'):
set("2")
break
elif keyboard.is_pressed('3'):
set("3")
break
elif keyboard.is_pressed('4'):
set("4")
break
elif keyboard.is_pressed('5'):
set("5")
break
elif keyboard.is_pressed('6'):
set("6")
break
elif keyboard.is_pressed('7'):
set("7")
break
elif keyboard.is_pressed('8'):
set("8")
break
elif keyboard.is_pressed('9'):
set("9")
break
elif keyboard.is_pressed('0'):
set("0")
break
except:
set("error")
main()
我还没有与keyboard
模块的工作,但我可以告诉你如何不用它的工作。
一对夫妇的事情;被这意味着名称window
是局部的功能的功能内创建的窗口。相反,创造在全球范围内的窗口。另外,功能set()
是一个内置的功能,如果你重新定义它,你将不能访问内置函数。我把它称为set_display()
代替。
正如您将在panel
改变形象,最好在全局命名空间创建它。此外,为了能够改变它,你必须保持一个参考,即给它取名panel
,然后包装。否则,该名称panel
将指向从pack()
的返回值是= None
。
当您以后更改图像中的标签在功能set_display()
还必须保存在标签中的图像的引用,明确在我的示例代码注释。
然后我使用bind()
挂钩键盘这是在窗口小部件的Tkinter的标准方法。从那以后,我开始mainloop()
它等待,直到按下一个键,然后调用keypress()
。
import tkinter as tk
from PIL import ImageTk, Image
def set_display(name):
path = r"C:\Users\The Man Himself\Desktop\SSG\%s.jpg" %name
img = ImageTk.PhotoImage(Image.open(path))
panel.config(image=img) # Load new image into label
panel.image = img # Save reference to image
def keypress(event):
if event.char == '': # Shift, ctrl etc, returns empty char
set_display('error')
elif event.char in '1234567890': # Hook all numbers
set_display(event.char)
else:
set_display('error')
window = tk.Tk()
window.title("AutoSegment")
window.geometry("459x767")
# Create Seven Segment Display label in global namespace
path = r"C:\Users\The Man Himself\Desktop\SSG\welcome.jpg"
img = ImageTk.PhotoImage(Image.open(path))
panel = tk.Label(window, image=img)
panel.pack(side="bottom", fill="both", expand="yes")
window.bind('<KeyPress>', keypress)
window.mainloop()