简体   繁体   中英

How do I format the text placement in a label (or other widget) in Python?

So I have a variable with a very long string for it's value. This string will be displayed to users in a new window so they can copy it and paste it into a program. So, the value of the variable is displayed in a label in a new window which pops up. The problem is, the text of the variable is all horizontal and in one line, so it disappears off the window screen, which is super annoying looking and makes it more difficult to copy. Is there a way I can get it formatted so it runs vertically with a scroll bar on the window?

I figured out that using a textbox works better - here are the websites: http://effbot.org/tkinterbook/text.htm

http://effbot.org/zone/tkinter-scrollbar-patterns.htm

and here's the code that I used:

from tkinter import * #Import tkinter module
import csv #Import csv module
from tkinter import messagebox

# These lines define the main/parent window
root = Tk()
root.title("Main Window")
root.geometry("500x500")
root.configure(bg='white')

def NewwindowButton():
    # The following three lines define the sub-window
    info_window = Toplevel(root)
    info_window.title("This is the info window")
    info_window.geometry("300x400")

    # These lines define a frame inside the window,
    # and the text box inside that frame with the 
    # 'variable_with_text' variable supplying the text.
    variable_with_text = "Here is the text..."
    info_window_frame = Frame(info_window, bg="white")  
    info_window_frame.place(relwidth=1.0, relheight=1.0)
    text_widget = Text(info_window, bg="white")
    text_widget.place(relwidth=1.0, relheight=1.0)
    text_widget.insert(INSERT, variable_with_text)

    # These lines define a scrollbar for the text window
    text_scrollbar = Scrollbar(info_window)
    text_scrollbar.pack(side=RIGHT, fill=Y)

    # These lines link the text widget and scrollbar together
    text_widget.config(yscrollcommand=text_scrollbar.set)
    text_scrollbar.config(command=text_widget.yview)

new_window_button = Button(root, text="Open new window", 
command=NewwindowButton, bg="grey")
new_window_button.pack()
root.mainloop()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM