如何在控制台中打印文本框中的文本?

问题描述

好的,所以我刚刚开始学习如何用python编码,我真的很喜欢用tkinter制作gui。我遇到了一个我无法解决的问题!希望有人能够提供帮助。

import tkinter as tk
window = tk.Tk()

text_Box = tk.Text()


text_Box.pack()

window.geometry("700x500+50+60")

window.title('Welcome!')



label = tk.Label(
     text="Hello,Welcome to my first app!",foreground="white",background="black"
)

button = tk.Button(
        text="click me!",width="25",height="5"
)




button.pack()
label.pack()



window.mainloop()

所以我只需要在按下按钮时将文本框中的内容打印到控制台中即可。

解决方法

使用print(text_box.get(1.0,'end-1c'))1.0的意思是“行1.字符0”。 'end-1c'的意思是“ Text的结尾减去1个字符”。整个过程都包含您要返回的范围(包含在内)。您想省略最后一个字符,因为Text小部件会自动在其中添加换行符〜除非您希望在打印件中使用该字符,然后只需使用'end'

以下示例是您应用的OOP实现。它被严厉地评论给您指明方向。

import tkinter as tk


#extend root
class App(tk.Tk):
    #application constants
    WIDTH,HEIGHT,X,Y,TITLE = 700,500,50,60,'Welcome'

    #class constructor
    def __init__(self):
        #super()
        tk.Tk.__init__(self)

        #force this row and column to take up as much space as possible
        #affects textfield and welcome
        self.grid_columnconfigure(0,weight=1)
        self.grid_rowconfigure(0,weight=1)
        
        #same thing as your "text_box"
        self.textfield = tk.Text(self)
        self.textfield.grid(row=0,column=0,columnspan=2,sticky='nswe')
        
        #same thing as your "label" but given a more descriptive name
        self.welcome = tk.Label(self,text="Welcome to my first app!",fg="white",bg="black")
        self.welcome.grid(row=1,sticky='nswe')
        
        #same thing as your "button" but given a more descriptive name,and a purpose
        #note: width and height are in characters,not pixels ~ same for Label and Text
        self.print_btn = tk.Button(self,text="print",width=5,height=1,command=self.toConsole)
        self.print_btn.grid(row=1,column=1)
        
    def toConsole(self):
        #how to send text from a textfield to the console
        print(self.textfield.get(1.0,'end-1c'))
        
        
#properly initialize your app
if __name__ == '__main__':
    app = App()
    app.title(App.TITLE)
    app.geometry(f'{App.WIDTH}x{App.HEIGHT}+{App.X}+{App.Y}')
    app.resizable(width=False,height=False)
    app.mainloop()