【发布时间】:2019-06-07 10:53:42
【问题描述】:
我一直在查看我的代码,并且对 tkinter 很陌生。我的代码的目的是在 Canvas 小部件中显示文本,而不是覆盖标签。但不确定如何执行此操作:
我的代码如下:
from tkinter import *
class Example(Frame):
def printLabel(self):
self.hello = []
self.hello.append('Hello')
self.hello.append('World!')
return(self.hello)
def updatePanel(self):
self.panelA.config(text="{}".format(self.printLabel()))
def __init__(self, root):
Frame.__init__(self, root)
self.buttonA()
self.viewingPanel()
def buttonA(self):
self.firstPage = Button(self, text="Print Text", bd=1, anchor=CENTER, height = 11, width = 13, command=lambda: self.updatePanel())
self.firstPage.place(x=0, y=0)
def viewingPanel(self):
self.panelA = Label(self, bg='white', width=65, height=13, padx=3, pady=3, anchor=NW, text="")
self.panelA.place(x=100, y=0)
self.cl= Canvas(self.panelA,bg='WHITE',width=165,height=113,relief=SUNKEN)
canvas_id = self.cl.create_text(15, 15, anchor="nw")
self.xb= Scrollbar(self.panelA,orient="horizontal", command=self.cl.xview)
self.xb.pack(side=BOTTOM,fill=X)
self.xb.config(command=self.cl.xview)
self.yb= Scrollbar(self.panelA,orient="vertical", command=self.cl.yview)
self.yb.pack(side=RIGHT,fill=Y)
self.yb.config(command=self.cl.yview)
self.cl.itemconfig(canvas_id,font=('Consolas',9), text="{}".format(self.printLabel()))
self.cl.configure(scrollregion = self.cl.bbox("all"))
self.cl.config(xscrollcommand=self.xb.set, yscrollcommand=self.yb.set)
self.cl.config(width=250,height=150)
self.cl.pack(side=LEFT,expand=True,fill=BOTH)
def main():
root = Tk()
root.title("Tk")
root.geometry('378x176')
app = Example(root)
app.pack(expand=True, fill=BOTH)
root.mainloop()
if __name__ == '__main__':
main()
Hello World! 应该在Canvas 中不带括号显示,但主要问题是当我单击Button 时,它只会与画布重叠并打印出附加到Label。
Label 应该在 Canvas 内。
【问题讨论】:
-
self.hello是一个列表,打印为一个列表。将其更改为" ".join(self.hello)。但是你为什么首先将它构建为一个列表呢?你想做self.hello=""; self.hello += 'Hello'吗? -
括号正在打印,因为
printLabel()方法返回list。您可以通过将其最后一行更改为return(' '.join(self.hello))来摆脱它们。 -
我不太明白你所说的“主要问题”是什么。当
Button被按下时你想发生什么? -
当我执行 GUI 时,文本出现而不单击 ButtonA,但是当单击 ButtonA 时,Hello World 文本显示为画布上的标签。我想要实现的是一个 GUI,它仅在单击 ButtonA 时才在画布中显示文本,即 Hello World!从我的角度来看,我添加了一个标签,然后将标签嵌入到画布中,因此当单击按钮时,它看起来就像文本出现在标签上。我正在努力实现这一目标,请对此有任何建议吗?
-
GUI 已执行 > 不应有文本 > 单击 ButtonA > Hello World! > 文本应该出现在画布中,而不是重叠的标签中。问题 = 点击前出现文本,点击按钮时出现在标签上
标签: python canvas text tkinter