如何在tkin的输出框中输出纯文本

2024-05-23 20:43:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经把tkinter程序的“指令”写在一个.txt文件上,当按下指令按钮时,我想创建一个单独的窗口,其中的指令从文本文件复制到输出框中。在

如果有人能帮助我,我将不胜感激。 这是我迄今为止所做的,但一点也不管用。在

instructionBtn = Button(window, text="?", command=start, height = 5, width  =30,fg="black", bg="lime green", font=("Comic Sans MS", 10))
instructionBtn.grid(row=29, column=1, sticky=S)

window.mainloop()

def instruction():
    instructionwindow = Tk() #create window 
    instructionwindow.geometry("500x350")

    instructionwindow.title("Instruction")
    instructionwindow.configure(background='white')

    instructionFile=open("Instruction.txt","r")
    instruction.read


textboxOutput = Text(window, wrap="Instruction.txt", width = 150, height = 20)
textboxOutput.grid(row = 20, column = 0, columnspan=10)


instruction.mainloop() 

Tags: txttkinter指令columnwindowwidthgridrow
1条回答
网友
1楼 · 发布于 2024-05-23 20:43:13

当我想要第二个窗口时,通常一个message box就可以了,如下所示:

from Tkinter import *
from tkMessageBox import showinfo

class App:

    def __init__(self, master):

        frame = Frame(master)
        frame.pack()

        self.button = Button(frame, text="QUIT", fg="red", command=frame.quit)
        self.button.pack(side=LEFT)

        self.instr = Button(frame, text="Instruction", command=self.instruction)
        self.instr.pack(side=LEFT)

    def instruction(self):
        try:
            with open("instruction.txt") as fp:
                message = fp.read()
        except IOError:
            message = 'No instructions available'
        showinfo("Instructions", message)

root = Tk()
app = App(root)
root.mainloop()

或者,如果您喜欢OOP style

^{pr2}$

{a3}有时创建一个消息框并不足够灵活:

# template: https://stackoverflow.com/a/17470842/8747

# Use Tkinter for python 2, tkinter for python 3
import Tkinter as tk
import tkMessageBox


class Instruction(tk.Toplevel):
    def __init__(self, parent, message, *args, **kwargs):
        tk.Toplevel.__init__(self, parent, *args, **kwargs)

        self.msg = tk.Message(self, text=message)
        self.button = tk.Button(self, text="Dismiss", command=self.destroy)

        self.msg.pack()
        self.button.pack()

class MainApplication(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)
        self.parent = parent

        self.button = tk.Button(
            self, text="QUIT", fg="red", command=self.quit)

        self.instr = tk.Button(
            self, text="Instruction", command=self.instruction)

        self.button.pack(side=tk.LEFT)
        self.instr.pack(side=tk.LEFT)

    def instruction(self):
        try:
            with open("instruction.txt") as fp:
                message = fp.read()
        except IOError:
            message = 'No instruction available'

        msg = Instruction(self, message)

if __name__ == "__main__":
    root = tk.Tk()
    MainApplication(root).pack(side="top", fill="both", expand=True)
    root.mainloop()

相关问题 更多 >