Python Tkinter返回

2024-10-01 17:37:28 发布

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

有没有办法在按下按钮时返回某些内容?在

这是我的示例程序。一个简单的文件阅读器。因为我不能返回内容,所以保存文本内容的全局变量是正确的吗?在

from Tkinter import *
import tkFileDialog

textcontents = ''

def onopen():
    filename = tkFileDialog.askopenfilename()
    read(filename)

def onclose():
    root.destroy()

def read(file):
    global textcontents
    f = open(file, 'r')

    textcontents = f.readlines()
    text.insert(END, textcontents)

root = Tk()
root.title('Text Reader')
frame = Frame(root)
frame.pack()
text = Text(frame, width=40, height=20)
text.pack()
text.insert(END, textcontents)

menu = Menu(root)
root.config(menu=menu)

filemenu = Menu(menu)
menu.add_cascade(label="File", menu=filemenu)
filemenu.add_command(label="Open...", command=onopen)
filemenu.add_command(label="Exit", command=onclose)

mainloop()

Tags: textimportadd内容defrootfilenameframe
2条回答

Tk(inter)是基于事件的,这意味着您不返回值,而是将回调(函数)绑定到操作。在

更多信息:http://effbot.org/tkinterbook/button.htm

如果您的意思是向用户发送信号,下面是一些示例代码:

import Tkinter
import tkMessageBox

top = Tkinter.Tk()

def helloCallBack():
   tkMessageBox.showinfo( "Hello Python", "Hello World")

B = Tkinter.Button(top, text ="Hello", command = helloCallBack)

B.pack()
top.mainloop()

来源:Python - Tkinter Button tutorial

相关问题 更多 >

    热门问题