我对Python非常陌生(并且大部分是编程),我正在开发一个项目来指示信标莫尔斯码,并监听信标之间的莫尔斯码。Python虽然在Tkinter循环?
我有灯塔工作,可能不是最好的代码,但它确实工作,但是当循环开始时,Tkinter屏幕冻结,停止信标按钮不工作,直到所有信标完成。
我想无限地运行信标,只是使用停止信标按钮来停止它,但到目前为止我似乎无法弄清楚如何停止循环。
#!usr/bin/env python
import sys
import re
import tkMessageBox
from Tkinter import *
import pygame
import time
CODE = {'A': '.-', 'B': '-...', 'C': '-.-.',
'D': '-..', 'E': '.', 'F': '..-.',
'G': '--.', 'H': '....', 'I': '..',
'J': '.---', 'K': '-.-', 'L': '.-..',
'M': '--', 'N': '-.', 'O': '---',
'P': '.--.', 'Q': '--.-', 'R': '.-.',
'S': '...', 'T': '-', 'U': '..-',
'V': '...-', 'W': '.--', 'X': '-..-',
'Y': '-.--', 'Z': '--..',
'0': '-----', '1': '.----', '2': '..---',
'3': '...--', '4': '....-', '5': '.....',
'6': '-....', '7': '--...', '8': '---..',
'9': '----.'
}
ONE_UNIT = 0.5
THREE_UNITS = 3 * ONE_UNIT
SEVEN_UNITS = 7 * ONE_UNIT
PATH = 'morse_sound_files/'
def verify(string):
keys = CODE.keys()
for char in string:
if char.upper() not in keys and char != ' ':
sys.exit('Error the charcter ' + char + ' cannot be translated to Morse Code')
beaconout = ''
beaconTEXT = 'this is text that is default'
def ask_quit():
if tkMessageBox.askokcancel("Quit", "are you sure you want to quit?"):
root.destroy()
def getinput():
incomingTEXT = incoming.get()
outboundTEXT = outbound.get()
beaconTEXT = beaconmessage.get(1.0,"end")
beaconout = outboundTEXT+" "+outboundTEXT+" "+outboundTEXT+" "+beaconTEXT+""+incomingTEXT
print beaconout
beaconout = beaconout.replace('\n', ' ')
print beaconout
print 'Welcome to Alphabet to Morse Code Translator v.01'
msg = beaconout
#verify(msg)
print
pygame.init()
for char in msg:
if char == ' ':
print ' '*7,
time.sleep(SEVEN_UNITS)
else:
print CODE[char.upper()],
pygame.mixer.music.load(PATH + char.upper() + '_morse_code.ogg')
pygame.mixer.music.play()
time.sleep(THREE_UNITS)
root = Tk()
root.geometry("800x600+300+300")
frame = Frame(root, width=1000, height=600)
label1 = Label(root, text="To: Call Sign:")
label2 = Label(root, text="Your Call Sign:")
label3 = Label(root, text="Enter your message:")
outbound = StringVar()
outboundcallsign = Entry(root, textvariable=outbound)
incoming = StringVar()
inboundcallsign = Entry(root, textvariable=incoming)
beacon = StringVar()
beaconmessage = Text(root, height=1, width=30)
label1.grid(row=1, sticky=E)
label2.grid(row=2, sticky=E)
label3.grid(row=3, sticky=E)
outboundcallsign.grid(row=1, column=1)
inboundcallsign.grid(row=2, column=1)
beaconmessage.grid(row=4, columnspan=4)
cbox = Checkbutton(root, text="message is ready to beacon?")
cbox.grid(columnspan=2)
submitbut = Button(root,text="Start Beacon", command = getinput)
submitbut.grid(row=14,column=1)
submitbut.bind("<Button-1>")
cancelbut = Button(root,text="Stop Beacon", command=ask_quit)
cancelbut.grid(row=14, column=3)
root.mainloop()
难以重现您的问题,但问题似乎是UI线程被阻止。把'getinput'中的东西放到一个线程中,或者使用'root.after'而不是'sleep'来重写''msg'循环中的char' –