官术网_书友最值得收藏!

Getting feedback from the user

Should you require something back from the user, Tkinter has four more message boxes for you:

  • askquestion
  • askyesno
  • askokcancel
  • askretrycancel

askquestion will allow any question to be passed in and provides Yes and No answers. These are returned to the program as the string literals "yes" and "no".

askyesno does the same, but will return 1 on Yes and nothing on No.

askokcancel provides OK and Cancel buttons to the user. OK returns 1 and Cancel nothing.

askretrycancel provides Retry and Cancel buttons. Retry returns 1 and Cancel nothing.

Despite the seemingly large number of choices, these all do pretty much the same thing. There doesn't seem to be much of a use case for askquestion over askyesno since they provide the same button choices, but askquestion will produce cleaner code thanks to the return values.

Let's see askyesno in action within our Hello World application.

Change the say_goodbye method to the following:

def say_goodbye(self):
if msgbox.askyesno("Close Window?", "Would you like to
close this window?"):
self.label_text.set("Window will close in 2 seconds")
self.after(2000, self.destroy)
else:
msgbox.showinfo("Not Closing", "Great! This window
will stay open.")

Run this application and try clicking the Say Goodbye button. You will now be asked whether you want to close the window. Give both No and Yes a try:

Our askyesno box

From the code for this function, you should see that the askyesno method can be treated like a Boolean statement. If you don't like doing this in one go, you could always use a variable such as the following:

close = msgbox.askyesno("Close Window?", "Would you like to close this window?") 
if close:
self.close()
主站蜘蛛池模板: 伊春市| 海安县| 雅安市| 建宁县| 运城市| 芦山县| 西安市| 长乐市| 陆丰市| 宜春市| 格尔木市| 丰城市| 湖口县| 阳原县| 宁强县| 西乌珠穆沁旗| 肇东市| 甘肃省| 大石桥市| 汝阳县| 荣昌县| 阿勒泰市| 蒙城县| 茂名市| 綦江县| 余干县| 昔阳县| 浦县| 揭西县| 射洪县| 东兴市| 东宁县| 安宁市| 通江县| 全南县| 安顺市| 福清市| 綦江县| 隆林| 莱西市| 九寨沟县|