web-dev-qa-db-ja.com

Tkinterの質問ダイアログボックス

Tkinterの削除ボタンに質問ダイアログボックスを追加しようとしています。現在、フォルダを押すとその内容を削除するボタンがあります。はい/いいえの確認用の質問を追加したいと思います。

import Tkinter
import tkMessageBox

top = Tkinter.Tk()
def deleteme():
    tkMessageBox.askquestion("Delete", "Are You Sure?", icon='warning')
    if 'yes':
        print "Deleted"
    else:
        print "I'm Not Deleted Yet"
B1 = Tkinter.Button(top, text = "Delete", command = deleteme)
B1.pack()
top.mainloop()

これを実行するたびに、「いいえ」を押しても「削除済み」ステートメントが表示されます。 ifステートメントをtkMessageBoxに追加できますか?

8
Jeff

問題はあなたのif-ステートメントです。ダイアログから結果を取得する必要があります(これは'yes'または'no')そしてそれと比較してください。以下のコードの2行目と3行目に注意してください。

def deleteme():
    result = tkMessageBox.askquestion("Delete", "Are You Sure?", icon='warning')
    if result == 'yes':
        print "Deleted"
    else:
        print "I'm Not Deleted Yet"

ここで、コードが機能しているように見える理由について説明します。InPythonブール値が期待されるコンテキストでは、多数の型を使用できます。たとえば、次のことができます。

arr = [10, 10]
if arr:
    print "arr is non-empty"
else:
    print "arr is empty"

同じことが文字列にも起こります。空でない文字列はTrueのように動作し、空の文字列はFalseのように動作します。したがって、if 'yes':常に実行しています。

21
JPvdMerwe

以下は、終了ウィンドウのメッセージボックスで質問し、ユーザーが[はい]を押した場合に終了するコードです。

from tkinter import  *
from tkinter import messagebox
root=Tk()
def clicked():
  label1=Label(root,text="This is text")
  label1.pack()
def popup():
  response=messagebox.askquestion("Title of message box ","Exit Programe ?", 
  icon='warning')
  print(response)
   if   response == "yes":
      b2=Button(root,text="click here to exit",command=root.quit)
      b2.pack()
  else:
    b2=Button(root,text="Thank you for selecting no for exit .")
    b2.pack()
button=Button(root,text="Button click",command=clicked)
button2=Button(root,text="Exit Programe ?",command=popup)
button.pack()
button2.pack()
root.mainloop()
0
sameer_nubia