Python: Bài 5. Hộp thoại

Các khóa học qua video:
Python SQL Server PHP C# Lập trình C Java HTML5-CSS3-JavaScript
Học trên YouTube <76K/tháng. Đăng ký Hội viên
Viết nhanh hơn - Học tốt hơn
Giải phóng thời gian, khai phóng năng lực

Trong bài này chúng ta sẽ học cách hiển thị các hộp thoại (Dialog) trong Tkinter.

Messagebox

Đây là kiểu hôp thoại dùng để hiển thị thông báo cho người dùng và đôi khi còn dùng để đưa ra yêu cầu chọn lựa cho người dùng.

from tkinter.ttk import Frame, Button
from tkinter import Tk, BOTH
import tkinter.messagebox as mbox

class Example(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.initUI()
  
    def initUI(self):
        self.parent.title("Message Boxes")
        self.pack()
  
        error = Button(self, text="Error", command=self.onError)
        error.grid(padx=5, pady=5)
        warning = Button(self, text="Warning", command=self.onWarn)
        warning.grid(row=1, column=0)
        question = Button(self, text="Question", command=self.onQuest)
        question.grid(row=0, column=1)
        inform = Button(self, text="Information", command=self.onInfo)
        inform.grid(row=1, column=1)
  
    def onError(self):
        mbox.showerror("Error", "Could not open file")
  
    def onWarn(self):
        mbox.showwarning("Warning", "Deprecated function call")
  
    def onQuest(self):
        mbox.askquestion("Question", "Are you sure to quit?")
       
    def onInfo(self):
        mbox.showinfo("Information", "Download completed")
  
root = Tk()
ex = Example(root)
root.geometry("300x150+300+300")
root.mainloop()

 

Trong ví dụ trên chúng ta hiển thị 4 button, mỗi button sẽ hiển thị một kiểu message box khác nhau.

import tkinter.messagebox as mbox

Để sử dụng được message box thì bạn import module tkinger.messagebox (hoặc tkMessageBox nếu bạn dùng Python phiên bản 2.x).

error = Button(self, text="Error", command=self.onError)

Ở dòng trên chúng tạo button Error, khi bấm vào button này phương thức onError() sẽ được gọi để hiển thị một message box thông báo lỗi.

def onError(self):
        mbox.showerror("Error", "Could not open file")

Để hiển thị hộp thoại thông báo lỗi thì chúng ta gọi phương thức showerror(). Ngoài thông báo lỗi thì Tkinter cung cấp cho chúng ta các kiểu messagebox khác như sau:

  • askokcancel(title, message, option)
  • askquestion(title, message, option)
  • askretrycancel(title, message, option)
  • askyesno(title, message, option)
  • showinfo(title, message, option)
  • showwarning(title, message, option)

Trong đó tham số option là tham số tùy chỉnh hộp thoại dùng để tùy chỉnh một số tính chất như chọn Icon cho hộp thoại, chọn cửa sổ cha… bạn có thể không cần quan tâm đến tham số này.

Các hộp thoại askokcancelaskretrycancel, và askyesno trả về giá trị True khi người dùng bấm vào nút “OK” hoặc “Yes“, False khi bấm vào “No” hoặc “Cancel“. Hộp thoại askquestion trả về giá trị “yes” khi bấm nút “Yes” và “no” khi bấm nút “No“.

Capture

Hộp thoại chọn màu (Color chooser)

Các hệ điều hành hay có sẵn hộp thoại chọn màu cho chúng ta sử dụng. Để hiển thị hộp thoại này chúng ta dùng module colorchooser (hoặc tkColorChooser nếu bạn dùng Python phiên bản 2.x).

from tkinter import Tk, Frame, Button, BOTH, SUNKEN
from tkinter.colorchooser import askcolor

class Example(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
  
        self.parent = parent
        self.initUI()
  
    def initUI(self):
        self.parent.title("Color chooser")
        self.pack(fill=BOTH, expand=1)
  
        self.btn = Button(self, text="Choose Color", command=self.onChoose)
        self.btn.place(x=30, y=30)
  
        self.frame = Frame(self, border=1, relief=SUNKEN, width=100, height=100)
        self.frame.place(x=160, y=30)
  
    def onChoose(self):
        (rgb, hx) = askcolor()
        self.frame.config(bg=hx)

root = Tk()
ex = Example(root)
root.geometry("300x150+300+300")
root.mainloop()

 

Trong ví dụ trên chúng ta hiển thị một button và một frame lên cửa sổ chính. Button sẽ mở một hộp thoại chọn màu, chọn màu nào thì màu đó sẽ hiện lên trên frame của chúng ta.

(rgb, hx) = askcolor()
self.frame.config(bg=hx)

Để hiển thị hộp thoại chọn màu thì chúng ta gọi đến hàm askcolor(). Hàm này sẽ trả về một tuple, bên trong tuple này có 2 phần tử là một tuple bao gồm 3 giá trị R-G-B và một giá trị màu ở dạng hexa, bạn có thể dùng hàm print(hx) bên trong phương thức onChoose() để biết giá trị hexa này. Chúng ta dùng giá tị hexa để đặt làm màu nền cho Frame.

Capture

Hộp thoại chọn file (File Dialog)

Trong ví dụ dưới đây chúng ta sẽ dùng hàm Open của module tkinter.filedialog để mở một File Dialog.
 

from tkinter import Frame, Tk, BOTH, Text, Menu, END
from tkinter.filedialog import Open

class Example(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.initUI()
  
    def initUI(self):
        self.parent.title("File dialog")
        self.pack(fill=BOTH, expand=1)
  
        menubar = Menu(self.parent)
        self.parent.config(menu=menubar)
  
        fileMenu = Menu(menubar)
        fileMenu.add_command(label="Open", command=self.onOpen)
        menubar.add_cascade(label="File", menu=fileMenu)
  
        self.txt = Text(self)
        self.txt.pack(fill=BOTH, expand=1)
  
    def onOpen(self):
        ftypes = [('Python files', '*.py'), ('All files', '*')]
        dlg = Open(self, filetypes = ftypes)
        fl = dlg.show()
        if fl != '':
            text = self.readFile(fl)
            self.txt.insert(END, text)
      
    def readFile(self, filename):
        f = open(filename, "r")
        text = f.read()
        return text
  
root = Tk()
ex = Example(root)
root.geometry("300x250+300+300")
root.mainloop()

 

Chúng ta sẽ tạo một menu cho phép mở file dialog và đọc nội dung của file được chọn vào lớp Text.

ftypes = [('Python files', '*.py'), ('All files', '*')]

 

Dòng trên là List lưu các định dạng file khác nhau để lọc file.

dlg = Open(self, filetypes = ftypes)
fl = dlg.show()

Để hiển thị file dialog thì chúng ta gọi hàm Open(). Hàm này trả về một string là đường dẫn đến file được chọn.

Capture

» Tiếp: Bài 6. Đồ họa
« Trước: Bài 4. Menu
Các khóa học qua video:
Python SQL Server PHP C# Lập trình C Java HTML5-CSS3-JavaScript
Học trên YouTube <76K/tháng. Đăng ký Hội viên
Viết nhanh hơn - Học tốt hơn
Giải phóng thời gian, khai phóng năng lực
Copied !!!