1. 程式人生 > >python小工具 - alert彈框輸出姓名年齡、求和

python小工具 - alert彈框輸出姓名年齡、求和

sum entry 數字 之間 col import 技術分享 app button

使用python自帶的tkinter庫進行GUI編程,完成兩個功能:

(1)要求用戶輸入姓名和年齡然後打印出來

(2)要求用戶輸入一個數字,然後計算1到該數字之間的和

代碼部分:

# 導入tkinter的所有的包裏面所有的內容
from tkinter import *

import tkinter.messagebox as messagebox

# 從Frame派生一個Application類,這是所有Widget的父容器
class Application(Frame):

    def __init__(self,master=None):
        Frame.__init__(self,master)
        self.pack()
        self.createWidgets()

    def createWidgets(self):

        # 模塊1,設定用戶輸入一個字符,alert彈框輸出hello
+該字符 self.helloLabel = Label(self, text=模塊1:請輸入您的姓名及年齡,程序將會打印出來) self.helloLabel.pack() # pack()方法把Widget加入到父容器中,並實現布局。 self.nameInput = Entry(self) self.nameInput.pack() self.ageInput = Entry(self) self.ageInput.pack() self.alertButton = Button(self,text=
提交,command=self.hello) self.alertButton.pack() # 模塊2,設定用戶輸入一個數字,alert彈框計算該數字的倍數 self.helloLabel = Label(self, text=模塊2:輸入任意數字後將計算1到該數字之間的和) self.helloLabel.pack() # pack()方法把Widget加入到父容器中,並實現布局。 self.numberInput = Entry(self) self.numberInput.pack() self.alertButton
= Button(self,text=提交,command=self.sum) self.alertButton.pack() # 退出Button設定 self.quitButton = Button(self, text=退出, command=self.quit) self.quitButton.pack() def hello(self): name = self.nameInput.get() or world # 獲取用戶輸入的內容 age = self.ageInput.get() or 20 messagebox.showinfo(個人信息,姓名:%s\n年齡:%s歲 % (name,age)) # 調用用戶輸入的內容並打印出來 def sum(self): number = int(self.numberInput.get()) # 獲取用戶輸入的內容 sum = 0 for i in range(number): i += 1 sum += i messagebox.showinfo(求和結果,1到%s之間的和為%s % (number,sum)) # 調用用戶輸入的(數字 * 2)後並打印出來 # 實例化 app = Application() # 設置窗口標題: app.master.title(Hello World) # 主消息循環 app.mainloop()

執行效果:

技術分享

技術分享

python小工具 - alert彈框輸出姓名年齡、求和