需要在输入框Python Tkinter中显示\ r \ n

时间:2014-12-03 05:36:27

标签: python string python-3.x tkinter tkinter-entry

我有一个程序,我需要在输入框中显示\ r \ n字符。但是在tkinter的这个输入框中,它们没有显示出来。当我通过串口发送和返回时,\ r \ n显示返回的内容,因此字符在那里,它们只是没有显示。

有没有办法让这些字符显示在输入框中,而不必每次都手动输入。

这是代码

from tkinter import *


title_str = "Entry Boxes Test"

root = Tk()
root.title(title_str)

f1_value = StringVar()
f1_value.set("=> HELP\r\n")
f2_value = StringVar()
f2_value.set("=> VERSION\r\n")


def callback_f1():
    listbox.insert(END,  f1_entry.get())
    listbox.see(END)
    return


def callback_f2():
    listbox.insert(END,  f2_entry.get())
    listbox.see(END)
    return

title_frame = Frame(root)
title_frame.pack(side=TOP)

body_frame = Frame(root)
body_frame.pack(side=TOP)

left = Frame(body_frame)
right = Frame(body_frame)
left.pack(side=LEFT)
right.pack(side=LEFT)

bottom_frame = Frame(root)
bottom_frame.pack(side=TOP)

#attach scroll bar to bottom frame for messages
scrollbar = Scrollbar(bottom_frame)
scrollbar.pack(side=RIGHT, fill=Y)

listbox = Listbox(bottom_frame, width=40)
listbox.pack()

# attach listbox to scrollbar
listbox.config(yscrollcommand=scrollbar.set)
scrollbar.config(command=listbox.yview)

title_var = StringVar()
title = Label(title_frame, textvariable=title_var, relief=FLAT, height=2)
title_var.set(title_str)
title.pack(side=TOP)

#F1 and F2
f1_button = Button(left, text="F1", width=15, height=2, command=callback_f1, state=NORMAL)
f1_button.pack(side=TOP)
f1_entry = Entry(left, textvariable=f1_value, width=18)
f1_entry.pack(side=TOP)
f2_button = Button(right, text="F2", width=15, height=2, command=callback_f2, state=NORMAL)
f2_button.pack(side=TOP)
f2_entry = Entry(right, textvariable=f2_value, width=18)
f2_entry.pack(side=TOP)


root.mainloop()

我尝试将其分开,如

f1_value.set("=> Help" + "\r\n")

f1_value.set("=> FUP{ret}".format(ret="\r\n"))

但到目前为止没有工作。

提前致谢!

通过序列发送此内容,

ser = serial.Serial()
def write_ser(st):
    ser.write(st.encode())
    time.sleep(1)
    while ser.inWaiting():
        try:
            s = ser.read(20)
        except:
            listbox.insert(END, "read failed")
            listbox.see(END)
            return
        listbox.insert(END,  "<" + str(s)[2:-1] + ">")
        listbox.see(END)
    return

,例如对于f1,

def callback_f1():
    listbox.insert(END,  f1_entry.get())
    listbox.see(END)
    write_ser(f1_entry.get())
    return

1 个答案:

答案 0 :(得分:1)

如果你的意思是按字面意思显示\,请逃避它们:

f1_value = StringVar()
f1_value.set("=> HELP\\r\\n")
f2_value = StringVar()
f2_value.set("=> VERSION\\r\\n")

或使用r'raw string literals'

f1_value = StringVar()
f1_value.set(r"=> HELP\r\n")
f2_value = StringVar()
f2_value.set(r"=> VERSION\r\n")