【问题标题】:Justify line in text Tkinter在文本 Tkinter 中对齐行
【发布时间】:2015-08-05 19:09:40
【问题描述】:

我正在尝试构建一个回答用户问题的机器人,我想在框架的右侧显示用户问题,在左侧显示机器人答案。我已经阅读了一篇关于使用标签 (How to set justification on Tkinter Text box) 在文本中进行对齐的帖子,但我无法将其应用于我的代码,而且我根本不熟悉标签。你能帮我吗,我做错了什么? (如果不清楚请告诉我)

这是我的代码:

from tkinter import *

window = Tk()

ia_answers= "test\n"
input_frame = LabelFrame(window, text="User :", borderwidth=4)
input_frame.pack(fill=BOTH, side=BOTTOM)
input_user = StringVar()
input_field = Entry(input_frame, text=input_user)
input_field.pack(fill=BOTH, side=BOTTOM)

ia_frame = LabelFrame(window, text="Discussion",borderwidth = 15, height = 100, width = 100)
ia_frame.pack(fill=BOTH, side=TOP)

text = Text(ia_frame, state='disabled', text="ok")
text.pack()
text.tag_configure("right", justify='right')
text.tag_add("right", 1.0, "end")
def Enter_pressed(event):
    """Took the current string in the Entry field."""
    input_get = input_field.get()
    input_user.set("")
    text.configure(state='normal')
    text.insert('end', input_get)
    text.insert('end',ia_answers)
    text.configure(state='disabled')

input_field.bind("<Return>", Enter_pressed)
window.mainloop()

【问题讨论】:

  • 你为什么不简单地使用 2 个文本小部件?
  • 我已经尝试过,但它会说我必须为每个问题和答案创建一个文本小部件,以便有类似:问题答案问题答案而不是问题问题答案答案

标签: python text tkinter


【解决方案1】:

创建两个标签——“左”和“右”,设置对齐属性,然后在插入文本时将标签应用于文本。严格来说,您不需要“left”标签,但它使您的代码意图更加清晰。

text = Text(ia_frame, state='disabled', text="ok")

text.tag_configure("right", justify="right")
text.tag_configure("left", justify="left")
...
text.insert("end", "this is right-justified\n", "right")
text.insert("end", "this is left-justified\n", "left")
...

【讨论】:

  • 我试图把它放在我的代码中,但它不能正常工作: text.insert("end", input_get, "right") text.insert("end", ia_answers, “左”)
  • 我找到了解决方案,我忘记了“\n”,现在可以了,谢谢:)
猜你喜欢
  • 2017-12-03
  • 2020-11-28
  • 2016-09-16
  • 2023-03-28
  • 1970-01-01
  • 2011-12-26
  • 1970-01-01
  • 1970-01-01
  • 2021-12-30
相关资源
最近更新 更多