2009-06-27 62 views
8

我一直在試圖建立一個相當簡單的消息框在tkinter有「是」和「否」按鈕。當我在內部按下「YES」按鈕時,它必須轉到並將YES寫入文件。同樣,當按下「否」時,必須將NO寫入文件。我怎樣才能做到這一點?如何用tkinter創建消息框?

+4

聽起來像是不錯的家庭作業的問題,我...所以, ,你到目前爲止有什麼? – balpha 2009-06-27 08:54:52

回答

18

您可以使用Python 2.7的模塊tkMessageBox或稱爲tkinter.messagebox的Python 3的對應版本。

它看起來像askquestion()正是你想要的功能。它甚至會爲您返回字符串"yes""no"

+1

tkinter.messagebox在我的Ubuntu 12.04 python中不起作用 – Ajoy 2013-02-23 17:45:56

7

以下是如何在Python 2.7中使用消息框提出問題的方法。你需要特別的模塊tkMessageBox

from Tkinter import * 
import tkMessageBox 


root = Tk().withdraw() # hiding the main window 
var = tkMessageBox.askyesno("Title", "Your question goes here?") 

filename = "log.txt" 

f = open(filename, "w") 
f.write(str(var)) 
print str(var) + " has been written to the file " + filename 
f.close() 
8

您可以將askquestion函數的返回值賦值給一個變量,然後只需將變量寫入文件:

from tkinter import messagebox 

variable = messagebox.askquestion('title','question') 

with open('myfile.extension', 'w') as file: # option 'a' to append 
    file.write(variable + '\n')