Hướng dẫn tkinter python 3
Hướng dẫn này sẽ nhanh chóng giúp bạn thiết lập và chạy Tk mới nhất từ Python, Tcl, Ruby và Perl trên macOS, Windows hoặc Linux. Nó cung cấp tất cả các yếu tố cần thiết về các khái niệm Tk cốt lõi, các tiện ích khác nhau, bố cục, sự kiện và hơn thế nữa mà bạn cần cho ứng dụng của mình
Python có rất nhiều khung GUI, nhưng Tkinter là khung duy nhất được tích hợp trong thư viện chuẩn Python. Tkinter có một số điểm mạnh. Đó là nền tảng chéo, vì vậy cùng một mã hoạt động trên Windows, macOS và Linux. Các phần tử trực quan được kết xuất bằng cách sử dụng các phần tử hệ điều hành gốc, vì vậy các ứng dụng được xây dựng bằng Tkinter trông giống như chúng thuộc về nền tảng nơi chúng chạy Show
Mặc dù Tkinter được coi là khung GUI Python trên thực tế, nhưng nó không phải là không bị chỉ trích. Một lời chỉ trích đáng chú ý là GUI được xây dựng bằng Tkinter trông đã lỗi thời. Nếu bạn muốn có một giao diện hiện đại, bóng bẩy thì Tkinter có thể không phải là thứ bạn đang tìm kiếm Tuy nhiên, Tkinter nhẹ và tương đối dễ sử dụng so với các khung khác. Điều này làm cho nó trở thành một lựa chọn hấp dẫn để xây dựng các ứng dụng GUI bằng Python, đặc biệt là đối với các ứng dụng không cần ánh sáng hiện đại và ưu tiên hàng đầu là nhanh chóng xây dựng thứ gì đó có chức năng và đa nền tảng. Trong hướng dẫn này, bạn sẽ học cách
Ghi chú. Hướng dẫn này được điều chỉnh từ chương “Giao diện người dùng đồ họa” của Python Basics. Giới thiệu thực tế về Python 3 Cuốn sách sử dụng trình soạn thảo IDLE tích hợp sẵn của Python để tạo và chỉnh sửa các tệp Python cũng như tương tác với trình bao Python. Trong hướng dẫn này, các tham chiếu đến IDLE đã bị xóa để chuyển sang ngôn ngữ tổng quát hơn Phần lớn tài liệu trong hướng dẫn này không thay đổi và bạn sẽ không gặp vấn đề gì khi chạy mã ví dụ từ trình chỉnh sửa và môi trường bạn chọn Khi bạn đã thành thạo các kỹ năng này bằng cách thực hiện các bài tập ở cuối mỗi phần, bạn sẽ kết hợp mọi thứ lại với nhau bằng cách xây dựng hai ứng dụng. Đầu tiên là bộ chuyển đổi nhiệt độ và thứ hai là trình soạn thảo văn bản. Đã đến lúc đi sâu vào tìm hiểu cách xây dựng ứng dụng với Tkinter Tiền thưởng miễn phí. 5 Suy nghĩ về Làm chủ Python, một khóa học miễn phí dành cho các nhà phát triển Python cho bạn thấy lộ trình và tư duy mà bạn sẽ cần để đưa các kỹ năng Python của mình lên một tầm cao mới Lấy bài kiểm tra. Kiểm tra kiến thức của bạn với bài kiểm tra tương tác “Lập trình GUI Python với Tkinter” của chúng tôi. Sau khi hoàn thành, bạn sẽ nhận được điểm số để có thể theo dõi quá trình học tập của mình theo thời gian Lấy bài kiểm tra " Xây dựng ứng dụng GUI Python đầu tiên của bạn với TkinterYếu tố nền tảng của Tkinter GUI là cửa sổ. Windows là nơi chứa tất cả các thành phần GUI khác sống. Các phần tử GUI khác này, chẳng hạn như hộp văn bản, nhãn và nút, được gọi là tiện ích con. Widget được chứa bên trong cửa sổ Đầu tiên, tạo một cửa sổ chứa một widget duy nhất. Bắt đầu một phiên trình bao Python mới và làm theo Ghi chú. Các ví dụ mã trong hướng dẫn này đều đã được thử nghiệm trên Windows, macOS và Ubuntu Linux 20. 04 với Python phiên bản 3. 10 Nếu bạn đã cài đặt Python với bộ cài đặt chính thức có sẵn cho Windows và macOS từ python. org, thì bạn sẽ không gặp vấn đề gì khi chạy mã mẫu. Bạn có thể yên tâm bỏ qua phần còn lại của ghi chú này và tiếp tục với phần hướng dẫn Nếu bạn chưa cài đặt Python bằng trình cài đặt chính thức hoặc không có bản phân phối chính thức nào cho hệ thống của bạn, thì đây là một số mẹo để thiết lập và sử dụng Python trên macOS với Homebrew Bản phân phối Python cho macOS có sẵn trên Homebrew không đi kèm với phần phụ thuộc Tcl/Tk theo yêu cầu của Tkinter. Phiên bản hệ thống mặc định được sử dụng thay thế. Phiên bản này có thể đã lỗi thời và ngăn bạn nhập mô-đun Tkinter. Để tránh sự cố này, hãy sử dụng trình cài đặt macOS chính thức UbuntuLinux 20. 04 Để tiết kiệm dung lượng bộ nhớ, phiên bản mặc định của trình thông dịch Python được cài đặt sẵn trên Ubuntu Linux 20. 04 không hỗ trợ Tkinter. Tuy nhiên, nếu bạn muốn tiếp tục sử dụng trình thông dịch Python đi kèm với hệ điều hành của mình, thì hãy cài đặt gói sau
Thao tác này sẽ cài đặt mô-đun Python GUI Tkinter Hương vị Linux khác Nếu bạn không thể cài đặt Python hoạt động trên phiên bản Linux của mình, thì bạn có thể xây dựng Python với phiên bản Tcl/Tk chính xác từ mã nguồn. Để biết hướng dẫn từng bước về quy trình này, hãy xem Hướng dẫn thiết lập và cài đặt Python 3. Bạn cũng có thể thử sử dụng pyenv để quản lý nhiều phiên bản Python Khi trình bao Python của bạn mở, điều đầu tiên bạn cần làm là nhập mô-đun Python GUI Tkinter >>>
Một cửa sổ là một thể hiện của lớp 02 của Tkinter. Hãy tiếp tục và tạo một cửa sổ mới và gán nó cho biến 03>>>
Khi bạn thực thi đoạn mã trên, một cửa sổ mới hiện lên trên màn hình của bạn. Nó trông như thế nào phụ thuộc vào hệ điều hành của bạn Trong suốt phần còn lại của hướng dẫn này, bạn sẽ thấy ảnh chụp màn hình Windows Loại bỏ các quảng cáoThêm một tiện íchBây giờ bạn đã có một cửa sổ, bạn có thể thêm tiện ích. Sử dụng lớp 04 để thêm một số văn bản vào cửa sổ. Tạo một tiện ích 05 với văn bản 06 và gán nó cho một biến có tên là 07>>>
Cửa sổ bạn đã tạo trước đó không thay đổi. Bạn vừa tạo một tiện ích 05, nhưng bạn chưa thêm nó vào cửa sổ. Có một số cách để thêm widget vào cửa sổ. Ngay bây giờ, bạn có thể sử dụng phương pháp ________ 105 vật dụng ________ 110>>> 3Cửa sổ bây giờ trông như thế này Khi bạn đóng gói một tiện ích vào một cửa sổ, Tkinter sẽ điều chỉnh kích thước cửa sổ nhỏ nhất có thể trong khi vẫn bao gồm đầy đủ tiện ích. Bây giờ thực hiện như sau >>> 4Dường như không có gì xảy ra, nhưng lưu ý rằng không có lời nhắc mới nào xuất hiện trong trình bao 11 yêu cầu Python chạy vòng lặp sự kiện Tkinter. Phương pháp này lắng nghe các sự kiện, chẳng hạn như bấm nút hoặc nhấn phím và chặn bất kỳ mã nào chạy sau mã đó cho đến khi bạn đóng cửa sổ nơi bạn đã gọi phương thức. Hãy tiếp tục và đóng cửa sổ bạn đã tạo và bạn sẽ thấy một lời nhắc mới được hiển thị trong trình baoCảnh báo. Khi bạn làm việc với Tkinter từ REPL của Python, các bản cập nhật cho cửa sổ được áp dụng khi mỗi dòng được thực thi. Đây không phải là trường hợp khi chương trình Tkinter được thực thi từ tệp Python Nếu bạn không bao gồm 11 ở cuối chương trình trong tệp Python, thì ứng dụng Tkinter sẽ không bao giờ chạy và sẽ không có gì hiển thị. Ngoài ra, bạn có thể xây dựng giao diện người dùng của mình dần dần trong Python REPL bằng cách gọi 13 sau mỗi bước để phản ánh thay đổiTạo một cửa sổ với Tkinter chỉ mất một vài dòng mã. Nhưng các cửa sổ trống không hữu ích lắm. Trong phần tiếp theo, bạn sẽ tìm hiểu về một số tiện ích có sẵn trong Tkinter và cách bạn có thể tùy chỉnh chúng để đáp ứng nhu cầu của ứng dụng của mình Kiểm tra việc hiểu của bạnMở rộng các khối mã bên dưới để kiểm tra sự hiểu biết của bạn Tập thể dục. Tạo cửa sổ TkinterHiển thị/Ẩn Viết một tập lệnh Python đầy đủ để tạo cửa sổ Tkinter với văn bản 14Cửa sổ sẽ trông như thế này Hãy thử bài tập này ngay bây giờ Bạn có thể mở rộng khối mã bên dưới để xem giải pháp Giải pháp. Tạo cửa sổ TkinterHiển thị/Ẩn Đây là một giải pháp khả thi 9Hãy nhớ rằng mã của bạn có thể trông khác Khi bạn đã sẵn sàng, bạn có thể chuyển sang phần tiếp theo Làm việc với WidgetWidget là cốt lõi của Python GUI framework Tkinter. Chúng là những yếu tố mà qua đó người dùng tương tác với chương trình của bạn. Mỗi widget trong Tkinter được định nghĩa bởi một lớp. Dưới đây là một số vật dụng có sẵn Lớp tiện ích Mô tả 05Một tiện ích được sử dụng để hiển thị văn bản trên màn hình 16Một nút có thể chứa văn bản và có thể thực hiện một hành động khi được nhấp vào 17Một tiện ích nhập văn bản chỉ cho phép một dòng văn bản 18Một tiện ích nhập văn bản cho phép nhập văn bản nhiều dòng 19Một vùng hình chữ nhật được sử dụng để nhóm các tiện ích có liên quan hoặc cung cấp Bạn sẽ thấy cách làm việc với từng tiện ích này trong các phần sau, nhưng hãy nhớ rằng Tkinter có nhiều tiện ích hơn những tiện ích được liệt kê ở đây. Sự lựa chọn của tiện ích thậm chí còn phức tạp hơn khi bạn tính đến một bộ tiện ích theo chủ đề hoàn toàn mới. Tuy nhiên, trong phần còn lại của hướng dẫn này, bạn sẽ chỉ sử dụng các widget cổ điển của Tkinter Nếu bạn muốn tìm hiểu thêm về hai loại tiện ích này, thì bạn có thể mở rộng phần có thể thu gọn bên dưới Tiện ích cổ điển so với tiện ích theo chủ đềHiển thị/Ẩn Điều đáng chú ý là hiện tại có hai loại tiện ích mở rộng trong Tkinter
Các tiện ích cổ điển của Tkinter có khả năng tùy biến cao và đơn giản, nhưng chúng có xu hướng lỗi thời hoặc hơi xa lạ trên hầu hết các nền tảng hiện nay. Nếu bạn muốn tận dụng lợi thế của các tiện ích có giao diện tự nhiên và cảm thấy quen thuộc với người dùng của một hệ điều hành nhất định, thì bạn có thể muốn xem các tiện ích theo chủ đề Hầu hết các tiện ích theo chủ đề gần như là sự thay thế thả xuống cho các đối tác kế thừa của chúng, nhưng với giao diện hiện đại hơn. Bạn cũng có thể sử dụng một vài tiện ích hoàn toàn mới, chẳng hạn như thanh tiến trình, trước đây không có sẵn trong Tkinter. Đồng thời, bạn sẽ cần tiếp tục sử dụng một số tiện ích cổ điển không có tùy chọn thay thế theo chủ đề Ghi chú. Các widget theo chủ đề trong mô-đun 24 sử dụng giao diện gốc của hệ điều hành theo mặc định. Tuy nhiên, bạn có thể thay đổi chủ đề của chúng để có giao diện trực quan tùy chỉnh, chẳng hạn như chế độ sáng và tối. Chủ đề là tập hợp các định nghĩa kiểu có thể tái sử dụng, mà bạn có thể coi là Biểu định kiểu xếp tầng (CSS) cho TkinterLàm cho các tiện ích mới có thể sử dụng được có nghĩa là trích xuất hầu hết thông tin kiểu dáng của chúng thành các đối tượng riêng biệt. Một mặt, sự phân tách các mối quan tâm như vậy là một thuộc tính mong muốn trong thiết kế của thư viện, nhưng mặt khác, nó giới thiệu một lớp trừu tượng bổ sung, làm cho các tiện ích theo chủ đề khó tạo kiểu hơn so với các tiện ích cổ điển Khi làm việc với các widget thông thường và theo chủ đề trong Tkinter, theo thông lệ, bạn sẽ khai báo các bí danh sau cho các gói và mô-đun Tkinter >>> 0Các bí danh như thế này cho phép bạn đề cập rõ ràng đến 04 hoặc 26, chẳng hạn, trong một chương trình tùy thuộc vào nhu cầu của bạn>>> 3Tuy nhiên, đôi khi bạn có thể thấy thuận tiện hơn khi sử dụng nhập ký tự đại diện ( 27) để tự động ghi đè tất cả các tiện ích cũ bằng các tiện ích theo chủ đề nếu có thể, như vậy>>> 5Bây giờ, bạn không cần phải thêm tiền tố vào tên lớp của tiện ích với mô-đun Python tương ứng của nó. Bạn sẽ luôn tạo một tiện ích theo chủ đề miễn là tiện ích đó có sẵn hoặc bạn sẽ quay lại tiện ích cổ điển nếu không. Hai câu lệnh nhập ở trên phải được đặt theo thứ tự đã chỉ định để có hiệu lực. Do đó, nhập ký tự đại diện được coi là một thông lệ xấu, thường nên tránh trừ khi được sử dụng một cách có ý thức Để có danh sách đầy đủ các tiện ích Tkinter, hãy xem Tiện ích cơ bản và Tiện ích khác trong hướng dẫn TkDocs. Mặc dù nó mô tả các vật dụng theo chủ đề được giới thiệu trong Tcl/Tk 8. 5, hầu hết thông tin ở đó cũng nên áp dụng cho các vật dụng cổ điển Sự thật thú vị. Tkinter theo nghĩa đen là viết tắt của “giao diện Tk” vì nó là một liên kết Python hoặc giao diện lập trình cho thư viện Tk bằng ngôn ngữ kịch bản Tcl Hiện tại, hãy xem kỹ tiện ích 05Loại bỏ các quảng cáoHiển thị văn bản và hình ảnh với các widget >>> import tkinter as tk 05 05 vật dụng được sử dụng để hiển thị văn bản hoặc hình ảnh. Người dùng không thể chỉnh sửa văn bản được hiển thị bởi tiện ích 05. Nó chỉ dành cho mục đích hiển thị. Như bạn đã thấy trong ví dụ ở phần đầu của hướng dẫn này, bạn có thể tạo tiện ích con 05 bằng cách khởi tạo lớp 05 và chuyển một chuỗi tới tham số 34 0 05 tiện ích hiển thị văn bản với màu văn bản hệ thống mặc định và màu nền văn bản hệ thống mặc định. Chúng thường có màu đen và trắng tương ứng, nhưng bạn có thể thấy các màu khác nếu bạn đã thay đổi các cài đặt này trong hệ điều hành của mìnhBạn có thể kiểm soát văn bản và màu nền của 05 bằng cách sử dụng tham số 37 và 38 1Có rất nhiều tên màu hợp lệ, bao gồm
Nhiều tên màu HTML hoạt động với Tkinter. Để tham khảo đầy đủ, bao gồm các màu hệ thống dành riêng cho macOS và Windows mà chủ đề hệ thống hiện tại kiểm soát, hãy xem trang hướng dẫn sử dụng màu Bạn cũng có thể chỉ định màu bằng các giá trị RGB thập lục phân 2Thao tác này đặt nền nhãn thành màu xanh lam nhạt đẹp mắt. Các giá trị RGB thập lục phân khó hiểu hơn các màu được đặt tên, nhưng chúng cũng linh hoạt hơn. May mắn thay, có những công cụ giúp việc lấy mã màu thập lục phân tương đối dễ dàng Nếu bạn không muốn gõ 37 và 38 mọi lúc, thì bạn có thể sử dụng các tham số tốc ký 47 và 48 để đặt màu nền trước và nền sau 3Bạn cũng có thể kiểm soát chiều rộng và chiều cao của nhãn bằng tham số 49 và 50 4Đây là những gì nhãn này trông giống như trong một cửa sổ It may seem strange that the label in the window isn’t square even though the width and height are both set to 51. This is because the width and height are measured in text units. One horizontal text unit is determined by the width of the character 52, or the number zero, in the default system font. Similarly, one vertical text unit is determined by the height of the character 52Note. For width and height measurements, Tkinter uses text units, instead of something like inches, centimeters, or pixels, to ensure consistent behavior of the application across platforms Measuring units by the width of a character means that the size of a widget is relative to the default font on a user’s machine. This ensures the text fits properly in labels and buttons, no matter where the application is running Labels are great for displaying some text, but they don’t help you get input from a user. The next three widgets that you’ll learn about are all used to get user input Loại bỏ các quảng cáoDisplaying Clickable Buttons With >>> import tkinter as tk 16 Widgets 16 widgets are used to display clickable buttons. You can configure them to call a function whenever they’re clicked. You’ll cover how to call functions from button clicks in the next section. For now, take a look at how to create and style a buttonThere are many similarities between 16 and 05 widgets. In many ways, a button is just a label that you can click. The same keyword arguments that you use to create and style a 05 will work with 16 widgets. For example, the following code creates a button with a blue background and yellow text. It also sets the width and height to 60 and 61 text units, respectively 5Here’s what the button looks like in a window Pretty nifty. You can use the next two widgets to collect text input from a user Getting User Input With >>> import tkinter as tk 17 WidgetsWhen you need to get a little bit of text from a user, like a name or an email address, use an 17 widget. It’ll display a small text box that the user can type some text into. Tạo và tạo kiểu cho tiện ích con 17 hoạt động khá giống với tiện ích con 05 và 16. Ví dụ: đoạn mã sau tạo một tiện ích có nền màu xanh lam, một số văn bản màu vàng và chiều rộng là 67 đơn vị văn bản 6Tuy nhiên, điều thú vị về các widget của 17 không phải là cách tạo kiểu cho chúng. Đó là cách sử dụng chúng để nhận thông tin đầu vào từ người dùng. Có ba thao tác chính mà bạn có thể thực hiện với các tiện ích 17
Cách tốt nhất để hiểu về các vật dụng của 17 là tạo một vật dụng và tương tác với nó. Mở trình bao Python và làm theo các ví dụ trong phần này. Đầu tiên, nhập 20 và tạo một cửa sổ mới>>> 7Bây giờ hãy tạo tiện ích con 05 và 17>>> 8 05 mô tả loại văn bản nào sẽ xuất hiện trong tiện ích 17. Nó không thực thi bất kỳ loại yêu cầu nào trên 17, nhưng nó cho người dùng biết chương trình của bạn muốn họ đặt gì ở đó. Bạn cần 10 widget vào cửa sổ để chúng hiển thị>>> 9Đây là những gì trông giống như Lưu ý rằng Tkinter tự động căn giữa nhãn phía trên tiện ích con 17 trong cửa sổ. Đây là một tính năng của 10, bạn sẽ tìm hiểu thêm về tính năng này trong các phần sauNhấp vào bên trong tiện ích 17 bằng chuột và nhập 84Bây giờ bạn đã nhập một số văn bản vào tiện ích 17, nhưng văn bản đó chưa được gửi đến chương trình của bạn. Bạn có thể sử dụng 70 để truy xuất văn bản và gán nó cho một biến có tên là 87>>> 0Bạn cũng có thể xóa văn bản. Phương thức 71 này lấy một đối số số nguyên cho Python biết ký tự nào cần xóa. Ví dụ: khối mã bên dưới cho biết cách 89 xóa ký tự đầu tiên khỏi 17>>> 1Văn bản còn lại trong widget bây giờ là 91Lưu ý rằng, giống như đối tượng chuỗi Python, văn bản trong tiện ích con 17 được lập chỉ mục bắt đầu bằng 52Nếu bạn cần xóa một số ký tự khỏi 17, sau đó chuyển đối số số nguyên thứ hai cho 71 cho biết chỉ mục của ký tự nơi việc xóa sẽ dừng lại. Ví dụ: đoạn mã sau xóa bốn chữ cái đầu tiên trong 17>>> 2Văn bản còn lại bây giờ là 97 98 hoạt động giống như cắt chuỗi. Đối số đầu tiên xác định chỉ mục bắt đầu và quá trình xóa tiếp tục nhưng không bao gồm chỉ mục được chuyển làm đối số thứ hai. Sử dụng hằng số đặc biệt 99 cho đối số thứ hai của 71 để xóa tất cả văn bản trong 17>>> 3Bây giờ bạn sẽ thấy một hộp văn bản trống Ngược lại, bạn cũng có thể chèn văn bản vào tiện ích 17>>> 4Cửa sổ bây giờ trông như thế này Đối số đầu tiên cho biết vị trí chèn văn bản của 72. Nếu không có văn bản nào trong 17 thì văn bản mới sẽ luôn được chèn vào đầu tiện ích con, bất kể bạn chuyển giá trị nào làm đối số đầu tiên. Ví dụ: gọi 72 với 06 làm đối số đầu tiên thay vì 52, như bạn đã làm ở trên, sẽ tạo ra kết quả tương tựNếu 17 đã chứa một số văn bản, thì 72 sẽ chèn văn bản mới vào vị trí đã chỉ định và dịch chuyển tất cả văn bản hiện có sang bên phải>>> 5Văn bản tiện ích hiện có nội dung là 84Các tiện ích 17 rất phù hợp để thu thập một lượng nhỏ văn bản từ người dùng, nhưng vì chúng chỉ được hiển thị trên một dòng nên chúng không lý tưởng để thu thập một lượng lớn văn bản. Đó là nơi các vật dụng của 18 xuất hiệnLoại bỏ các quảng cáoNhận đầu vào của người dùng nhiều dòng với các widget >>> import tkinter as tk 18Tiện ích 18 được sử dụng để nhập văn bản, giống như tiện ích 17. The difference is that 18 widgets may contain multiple lines of text. Với tiện ích 18, người dùng có thể nhập toàn bộ đoạn văn hoặc thậm chí nhiều trang văn bản. Just like with 17 widgets, you can perform three main operations with 18 widgets
Although the method names are the same as the 17 methods, they work a bit differently. It’s time to get your hands dirty by creating a 18 widget and seeing what it can doNote. Do you still have the window from the previous section open? If so, then you can close it by executing the following >>> 6You can also close it manually by clicking the Close button In your Python shell, create a new blank window and pack a 25 widget into it>>> 7Text boxes are much larger than 17 widgets by default. Here’s what the window created above looks likeClick anywhere inside the window to activate the text box. Type in the word 27. Then press Enter and type 28 on the second line. The window should now look like this. Just like with 17 widgets, you can retrieve the text from a 18 widget using 70. However, calling 70 with no arguments doesn’t return the full text in the text box like it does for 17 widgets. It raises an exception>>> 8 34 requires at least one argument. Calling 70 with a single index returns a single character. To retrieve several characters, you need to pass a start index and an end index. Các chỉ số trong tiện ích con 18 hoạt động khác với trong tiện ích con 17. Since 18 widgets can have several lines of text, an index must contain two pieces of information
Line numbers start with 39, and character positions start with 52. To make an index, you create a string of the form 41, replacing 42 with the line number and 43 with the character number. For example, 44 represents the first character on the first line, and 45 represents the fourth character on the second lineUse the index 44 to get the first letter from the text box that you created earlier>>> 9There are five letters in the word 27, and the character number of 48 is 49, since character numbers start from 52, and the word 27 starts at the first position in the text box. Just like with Python string slices, in order to get the entire word 27 from the text box, the end index must be one more than the index of the last character to be readSo, to get the word 27 from the text box, use 44 for the first index and 55 for the second index>>> 0To get the word 28 on the second line of the text box, change the line numbers in each index to 57>>> 1To get all of the text in a text box, set the starting index in 44 and use the special 99 constant for the second index>>> 2Notice that text returned by 70 includes any newline characters. You can also see from this example that every line in a 18 widget has a newline character at the end, including the last line of text in the text box 71 is used to delete characters from a text box. It works just like 71 for 17 widgets. There are two ways to use 71
Using the single-argument version, you pass to 71 the index of a single character to be deleted. For example, the following deletes the first character, 67, from the text box>>> 3The first line of text in the window now reads 68Với phiên bản hai đối số, bạn chuyển hai chỉ mục để xóa một dải ký tự bắt đầu từ chỉ mục đầu tiên và tối đa nhưng không bao gồm chỉ mục thứ hai For example, to delete the remaining 68 on the first line of the text box, use the indices 44 and 71>>> 4Notice that the text is gone from the first line. This leaves a blank line followed the word 28 on the second lineEven though you can’t see it, there’s still a character on the first line. It’s a newline character. You can verify this using 70>>> 5If you delete that character, then the rest of the contents of the text box will shift up a line >>> 3Now, 28 is on the first line of the text boxTry to clear out the rest of the text in the text box. Set 44 as the start index and use 99 for the second index>>> 7The text box is now empty You can insert text into a text box using 72>>> 8This inserts the word 27 at the beginning of the text box, using the same 79 format used by 70 to specify the insertion positionCheck out what happens if you try to insert the word 28 on the second line>>> 9Instead of inserting the text on the second line, the text is inserted at the end of the first line If you want to insert text onto a new line, then you need to insert a newline character manually into the string being inserted >>> 30Now 28 is on the second line of the text box 72 will do one of two things
It’s usually impractical to try and keep track of what the index of the last character is. The best way to insert text at the end of a 18 widget is to pass 99 to the first parameter of 72>>> 31Don’t forget to include the newline character ( 87) at the beginning of the text if you want to put it on a new line>>> 32 05, 16, 17, and 18 widgets are just a few of the widgets available in Tkinter. There are several others, including widgets for checkboxes, radio buttons, scroll bars, and progress bars. For more information on all of the available widgets, see the Additional Widgets list in the Additional Resources sectionLoại bỏ các quảng cáoAssigning Widgets to Frames With >>> import tkinter as tk 19 WidgetsIn this tutorial, you’re going to work with only five widgets
These are the four you’ve seen so far plus the 19 widget. 19 widgets are important for organizing the layout of your widgets in an applicationBefore you get into the details about laying out the visual presentation of your widgets, take a closer look at how 19 widgets work, and how you can assign other widgets to them. The following script creates a blank 19 widget and assigns it to the main application window 33 02 packs the frame into the window so that the window sizes itself as small as possible to encompass the frame. When you run the above script, you get some seriously uninteresting outputAn empty 19 widget is practically invisible. Frames are best thought of as containers for other widgets. You can assign a widget to a frame by setting the widget’s 04 attribute 34To get a feel for how this works, write a script that creates two 19 widgets called 06 and 07. In this script, 06 contains a label with the text 09, and 07 contains the label 11. Here’s one way to do this 35Note that 06 is packed into the window before 07. The window that opens shows the label in 06 above the label in 07Now see what happens when you swap the order of 16 and 17 36The output looks like this Now 18 is on top. Since 18 is assigned to 07, it moves to wherever 07 is positionedAll four of the widget types that you’ve learned about— 05, 16, 17, and 18—have a 04 attribute that’s set when you instantiate them. That way, you can control which 19 a widget is assigned to. 19 widgets are great for organizing other widgets in a logical manner. Related widgets can be assigned to the same frame so that, if the frame is ever moved in the window, then the related widgets stay togetherNote. If you omit the 04 argument when creating a new widget instance, then it’ll be placed inside of the top-level window by defaultIn addition to grouping your widgets logically, 19 widgets can add a little flare to the visual presentation of your application. Read on to see how to create various borders for 19 widgetsLoại bỏ các quảng cáoAdjusting Frame Appearance With Reliefs 19 widgets can be configured with a 33 attribute that creates a border around the frame. You can set 33 to be any of the following values
To apply the border effect, you must set the 40 attribute to a value greater than 39. This attribute adjusts the width of the border in pixels. The best way to get a feel for what each effect looks like is to see them for yourself. Here’s a script that packs five 19 widgets into a window, each with a different value for the 33 argument 37Here’s a breakdown of this script
The window produced by the above script looks like this In this image, you can see the following effects
These effects give your Python GUI Tkinter application a bit of visual appeal Understanding Widget Naming ConventionsWhen you create a widget, you can give it any name you like, as long as it’s a valid Python identifier. It’s usually a good idea to include the name of the widget class in the variable name that you assign to the widget instance. For example, if a 05 widget is used to display a user’s name, then you might name the widget 65. An 17 widget used to collect a user’s age might be called 67Note. Sometimes, you may define a new widget without assigning it to a variable. You’ll call its 10 method directly on the same line of code>>> 38This might be helpful when you don’t intend to refer to the widget’s instance later on. Due to automatic memory management, Python would normally garbage collect such unassigned objects, but Tkinter prevents that by registering every new widget internally When you include the widget class name in the variable name, you help yourself and anyone else who needs to read your code to understand what type of widget the variable name refers to. However, using the full name of the widget class can lead to long variable names, so you may want to adopt a shorthand for referring to each widget type. For the rest of this tutorial, you’ll use the following shorthand prefixes to name widgets Widget ClassVariable Name PrefixExample 05 70 71 16 73 74 17 76 77 18 79 80 19 82 83In this section, you learned how to create a window, use widgets, and work with frames. At this point, you can make some plain windows that display messages, but you’ve yet to create a full-blown application. In the next section, you’ll learn how to control the layout of your applications using Tkinter’s powerful geometry managers Kiểm tra việc hiểu của bạnExpand the code block below for an exercise to check your understanding Exercise. Create an Entry widget and insert some textShow/Hide Write a complete script that displays an 17 widget that’s 40 text units wide and has a white background and black text. Use 72 to display text in the widget that reads 86The output window should look like this Hãy thử bài tập này ngay bây giờ Bạn có thể mở rộng khối mã bên dưới để xem giải pháp Solution. Create an Entry widget and insert some textShow/Hide There are a couple of ways to solve this exercise. Here’s one solution that uses the 48 and 47 parameters to set the 17 widget’s background and foreground colors 39This solution is great because it explicitly sets the background and foreground colors for the 17 widgetOn most systems, the default background color for an 17 widget is white, and the default foreground color is black. So, you might be able to generate the same window with the 48 and 47 parameters left out 40Hãy nhớ rằng mã của bạn có thể trông khác Khi bạn đã sẵn sàng, bạn có thể chuyển sang phần tiếp theo Loại bỏ các quảng cáoControlling Layout With Geometry ManagersUp until now, you’ve been adding widgets to windows and 19 widgets using 10, but you haven’t learned what exactly this method does. Let’s clear things up. Bố cục ứng dụng trong Tkinter được kiểm soát bằng trình quản lý hình học. While 10 is an example of a geometry manager, it isn’t the only one. Tkinter has two others
Each window or 19 in your application can use only one geometry manager. However, different frames can use different geometry managers, even if they’re assigned to a frame or window using another geometry manager. Start by taking a closer look at 10The >>> import tkinter as tk 10 Geometry ManagerThe 10 geometry manager uses a packing algorithm to place widgets in a 19 or window in a specified order. For a given widget, the packing algorithm has two primary steps
10 is powerful, but it can be difficult to visualize. The best way to get a feel for 10 is to look at some examples. See what happens when you 10 three 05 widgets into a 19 41 10 places each 19 below the previous one by default, in the order that they’re assigned to the windowEach 19 is placed at the topmost available position. Therefore, the red 19 is placed at the top of the window. Then the yellow 19 is placed just below the red one and the blue 19 just below the yellow oneThere are three invisible parcels, each containing one of the three 19 widgets. Each parcel is as wide as the window and as tall as the 19 that it contains. Because no anchor point was specified when 10 was called for each 318 they’re all centered inside of their parcels. That’s why each 19 is centered in the window 10 accepts some keyword arguments for more precisely configuring widget placement. For example, you can set the 321 keyword argument to specify in which direction the frames should fill. The options are 322 to fill in the horizontal direction, 323 to fill vertically, and 324 to fill in both directions. Here’s how you would stack the three frames so that each one fills the whole window horizontally 42Notice that the 49 is not set on any of the 19 widgets. 49 is no longer necessary because each frame sets 10 to fill horizontally, overriding any width you may setThe window produced by this script looks like this One of the nice things about filling the window with 10 is that the fill is responsive to window resizing. Try widening the window generated by the previous script to see how this works. As you widen the window, the width of the three 19 widgets grow to fill the windowNotice, though, that the 19 widgets don’t expand in the vertical directionThe 55 keyword argument of 10 specifies on which side of the window the widget should be placed. These are the available options
If you don’t set 55, then 10 will automatically use 334 and place new widgets at the top of the window, or at the topmost portion of the window that isn’t already occupied by a widget. For example, the following script places three frames side by side from left to right and expands each frame to fill the window vertically 43This time, you have to specify the 50 keyword argument on at least one of the frames to force the window to have some heightThe resulting window looks like this Just like when you set 342 to make the frames responsive when you resized the window horizontally, you can set 343 to make the frames responsive when you resize the window verticallyTo make the layout truly responsive, you can set an initial size for your frames using the 49 and 50 attributes. Then, set the 321 keyword argument of 10 to 324 and set the 349 keyword argument to 350 44When you run the above script, you’ll see a window that initially looks the same as the one you generated in the previous example. The difference is that now you can resize the window however you want, and the frames will expand and fill the window responsively Pretty cool Loại bỏ các quảng cáoThe >>> greeting = tk.Label(text="Hello, Tkinter") 97 Geometry ManagerYou can use 97 to control the precise location that a widget should occupy in a window or 19. You must provide two keyword arguments, 354 and 355, which specify the x- and y-coordinates for the top-left corner of the widget. Both 354 and 355 are measured in pixels, not text unitsKeep in mind that the origin, where 354 and 355 are both 52, is the top-left corner of the 19 or window. Vì vậy, bạn có thể coi đối số 355 của 97 là số pixel từ trên cùng của cửa sổ và đối số 354 là số pixel từ cạnh trái của cửa sổHere’s an example of how the 97 geometry manager works 45Here’s how this code works
Here’s the window that the code produces Note that if you run this code on a different operating system that uses different font sizes and styles, then the second label might become partially obscured by the window’s edge. That’s why 97 isn’t used often. In addition to this, it has two main drawbacks
One of the main challenges of cross-platform GUI development is making layouts that look good no matter which platform they’re viewed on, and 97 is a poor choice for making responsive and cross-platform layoutsThat’s not to say you should never use 97. In some cases, it might be just what you need. For example, if you’re creating a GUI interface for a map, then 97 might be the perfect choice to ensure widgets are placed at the correct distance from each other on the map 10 is usually a better choice than 97, but even 10 has some downsides. The placement of widgets depends on the order in which 10 is called, so it can be difficult to modify existing applications without fully understanding the code controlling the layout. The 98 geometry manager solves a lot of these issues, as you’ll see in the next sectionThe >>> greeting = tk.Label(text="Hello, Tkinter") 98 Geometry ManagerThe geometry manager you’ll likely use most often is 98, which provides all the power of 10 in a format that’s easier to understand and maintain 98 works by splitting a window or 19 into rows and columns. You specify the location of a widget by calling 98 and passing the row and column indices to the 394 and 395 keyword arguments, respectively. Both row and column indices start at 52, so a row index of 39 and a column index of 57 tells 98 to place a widget in the third column of the second rowThe following script creates a 3 × 3 grid of frames with 05 widgets packed into them 46Here’s what the resulting window looks like You’re using two geometry managers in this example. Each frame is attached to 03 with the 98 geometry manager 47Each 403 is attached to its master 19 with 10 48The important thing to realize here is that even though 98 is called on each 19 object, the geometry manager applies to the 03 object. Similarly, the layout of each 56 is controlled with the 10 geometry managerThe frames in the previous example are placed tightly next to one another. To add some space around each frame, you can set the padding of each cell in the grid. Padding is just some blank space that surrounds a widget and visually sets its content apart The two types of padding are external and internal padding. External padding adds some space around the outside of a grid cell. It’s controlled with two keyword arguments to 98
Both 412 and 413 are measured in pixels, not text units, so setting both of them to the same value will create the same amount of padding in both directions. Try to add some padding around the outside of the frames from the previous example 49Here’s the resulting window 10 also has 412 and 413 parameters. The following code is nearly identical to the previous code, except that you add five pixels of additional padding around each label in both the 354 and 355 directions 90The extra padding around the 05 widgets gives each cell in the grid a little bit of breathing room between the 19 border and the text in the labelĐiều đó trông khá đẹp. But if you try and expand the window in any direction, then you’ll notice that the layout isn’t very responsive The whole grid stays at the top-left corner as the window expands By using 423 and 424 on the 03 object, you can adjust how the rows and columns of the grid grow as the window is resized. Remember, the grid is attached to 03, even though you’re calling 98 on each 19 widget. Both 423 and 424 take three essential arguments
431 is set to 52 by default, which means that the column or row doesn’t expand as the window resizes. If every column or row is given a weight of 39, then they all grow at the same rate. If one column has a weight of 39 and another a weight of 57, then the second column expands at twice the rate of the first. Adjust the previous script to better handle window resizing 91 423 and 424 are placed in the body of the outer 45 loop. You could explicitly configure each column and row outside of the 45 loop, but that would require writing an additional six lines of codeOn each iteration of the loop, the 442-th column and row are configured to have a weight of 39. This ensures that the row and column expand at the same rate whenever the window is resized. The 432 argument is set to 445 for each column and 67 for each row. This ensures that the 05 widget always displays its text without chopping off any characters, even if the window size is extremely smallThe result is a grid layout that expands and contracts smoothly as the window is resized Try it yourself to get a feel for how it works. Play around with the 431 and 432 parameters to see how they affect the gridBy default, widgets are centered in their grid cells. For example, the following code creates two 05 widgets and places them in a grid with one column and two rows 92Each grid cell is 451 pixels wide and 06 pixels tall. The labels are placed in the center of each cell, as you can see in the following figureYou can change the location of each label inside of the grid cell using the 453 parameter, which accepts a string containing one or more of the following letters
The letters 454, 458, 456, and 460 come from the cardinal directions north, south, east, and west. Setting 453 to 454 on both labels in the previous code positions each label at the top-center of its grid cell 93Here’s the output You can combine multiple letters in a single string to position each label in the corner of its grid cell 94In this example, the 453 parameter of 372 is set to 470, which places the label at the top-right corner of its grid cell. 375 is positioned in the bottom-left corner by passing 472 to 453. Here’s what that looks like in the windowWhen a widget is positioned with 453, the size of the widget itself is just big enough to contain any text and other contents inside of it. It won’t fill the entire grid cell. In order to fill the grid, you can specify 475 to force the widget to fill the cell in the vertical direction, or 476 to fill the cell in the horizontal direction. Để điền vào toàn bộ ô, hãy đặt 453 thành 478. Ví dụ sau minh họa từng tùy chọn này 95Here’s what the output looks like What the above example illustrates is that the 98 geometry manager’s 453 parameter can be used to achieve the same effects as the 10 geometry manager’s 321 parameter. The correspondence between the 453 and 321 parameters is summarized in the following table 98 10 487 343 489 342 491 492 98 is a powerful geometry manager. It’s often easier to understand than 10 and is much more flexible than 97. When you’re creating new Tkinter applications, you should consider using 98 as your primary geometry managerNote. 98 offers much more flexibility than you’ve seen here. For example, you can configure cells to span multiple rows and columns. For more information, check out the Grid Geometry Manager section of the TkDocs tutorialNow that you’ve got the fundamentals of geometry managers down for the Python GUI framework Tkinter, the next step is to assign actions to buttons to bring your applications to life Loại bỏ các quảng cáoKiểm tra việc hiểu của bạnExpand the code block below for an exercise to check your understanding Exercise. Create an address entry formShow/Hide Below is an image of an address entry form made with Tkinter Write a complete script that re-creates the window. You may use any geometry manager you like Bạn có thể mở rộng khối mã bên dưới để xem giải pháp Solution. Create an address entry formShow/Hide There are many different ways to solve this exercise. If your solution generates a window identical to the one in the exercise statement, then congratulations. You’ve successfully solved the exercise. Below, you can look at two solutions that use the 98 geometry managerOne solution creates a 05 and 17 widget with the desired settings for each field 96There’s nothing wrong with this solution. It’s a bit long, but everything is very explicit. If you want to change something, then it’s clear to see exactly where to do so That said, the solution can be considerably shortened by recognizing that each 17 has the same width, and that all you need for each 05 is the text 97In this solution, a list is used to store the strings for each label in the form. They’re stored in the order that each form field should appear. Then, 903 gets both the index and string from each value in the 904 listKhi bạn đã sẵn sàng, bạn có thể chuyển sang phần tiếp theo Making Your Applications InteractiveBy now, you have a pretty good idea of how to create a window with Tkinter, add some widgets, and control the application layout. That’s great, but applications shouldn’t just look good—they actually need to do something. In this section, you’ll learn how to bring your applications to life by performing actions whenever certain events occur Using Events and Event HandlersWhen you create a Tkinter application, you must call 11 to start the event loop. During the event loop, your application checks if an event has occurred. If so, then it’ll execute some code in responseThe event loop is provided for you with Tkinter, so you don’t have to write any code that checks for events yourself. However, you do have to write the code that will be executed in response to an event. In Tkinter, you write functions called event handlers for the events that you use in your application Note. An event is any action that occurs during the event loop that might trigger some behavior in the application, such as when a key or mouse button is pressed When an event occurs, an event object is emitted, which means that an instance of a class representing the event is created. You don’t need to worry about instantiating these classes yourself. Tkinter will create instances of event classes for you automatically You’ll write your own event loop in order to better understand how Tkinter’s event loop works. That way, you can see how Tkinter’s event loop fits into your application, and which parts you need to write yourself Assume there’s a list called 906 that contains event objects. A new event object is automatically appended to 906 every time an event occurs in your program. Bạn không cần thực hiện cơ chế cập nhật này. It just automatically happens for you in this conceptual example. Using an infinite loop, you can continually check if there are any event objects in 906 98Right now, the event loop that you’ve created doesn’t do anything with 909. Let’s change that. Suppose your application needs to respond to keypresses. You need to check that 909 was generated by a user pressing a key on their keyboard, and if so, pass 909 to an event handler function for keypressesAssume that 909 has a 913 attribute set to the string 914 if the event is a keypress event object, and a 915 attribute containing the character of the key that was pressed. Create a new 916 function and update your event loop code 99When you call 11, something like the above loop is run for you. This method takes care of two parts of the loop for you
Update your event loop to use 11 instead of your own event loop 00 919 takes care of a lot for you, but there’s something missing from the above code. How does Tkinter know when to use 916? Tkinter widgets have a method called 921 for just this purposeLoại bỏ các quảng cáoUsing >>> import tkinter as tk 921To call an event handler whenever an event occurs on a widget, use 921. The event handler is said to be bound to the event because it’s called every time the event occurs. You’ll continue with the keypress example from the previous section and use 921 to bind 916 to the keypress event 01Ở đây, trình xử lý sự kiện 916 bị ràng buộc với sự kiện 927 bằng cách sử dụng 928. Bất cứ khi nào một phím được nhấn trong khi ứng dụng đang chạy, chương trình của bạn sẽ in ký tự của phím được nhấnNote. The output of the above program is not printed in the Tkinter application window. It’s printed to the standard output stream (stdout) If you run the program in IDLE, then you’ll see the output in the interactive window. If you run the program from a terminal, then you should see the output in your terminal 921 always takes at least two arguments
The event handler is bound to the widget on which 921 is called. When the event handler is called, the event object is passed to the event handler functionIn the example above, the event handler is bound to the window itself, but you can bind an event handler to any widget in your application. For example, you can bind an event handler to a 16 widget that will perform some action whenever the button is pressed 02In this example, the 934 event on the 935 widget is bound to the 936 event handler. The 934 event occurs whenever the left mouse button is pressed while the mouse is over the widget. There are other events for mouse button clicks, including 938 for the middle mouse button and 939 for the right mouse buttonNote. For a list of commonly used events, see the Event types section of the Tkinter 8. 5 reference You can bind any event handler to any kind of widget with 921, but there’s a more straightforward way to bind event handlers to button clicks using the 16 widget’s 942 attributeUsing >>> import tkinter as tk 942Every 16 widget has a 942 attribute that you can assign to a function. Whenever the button is pressed, the function is executedTake a look at an example. First, you’ll create a window with a 05 widget that holds a numeric value. You’ll put buttons on the left and right side of the label. The left button will be used to decrease the value in the 05, and the right one will increase the value. Here’s the code for the window 03Cửa sổ trông như thế này With the app layout defined, you can bring it to life by giving the buttons some commands. Start with the left button. When this button is pressed, it should decrease the value in the label by one. In order to do this, you first need to get answers to two questions
05 widgets don’t have 70 like 17 and 18 widgets do. However, you can retrieve the text from the label by accessing the 34 attribute with a dictionary-style subscript notation 04Now that you know how to get and set a label’s text, write an 955 function that increases the value in 956 by one 05 955 gets the text from 956 and converts it to an integer with 959. Then, it increases this value by one and sets the label’s 34 attribute to this new valueYou’ll also need 961 to decrease the value in 962 by one 06Put 955 and 961 in your code just after the 965 statementTo connect the buttons to the functions, assign the function to the button’s 942 attribute. You can do this when you instantiate the buttons. For example, update the two lines that instantiate the buttons to the following 07That’s all you need to do to bind the buttons to 955 and 961 and make the program functional. Try saving your changes and running the application. Click the buttons to increase and decrease the value in the center of the windowHere’s the full application code for your reference Counter Application Full Source CodeShow/Hide 08This app isn’t particularly useful, but the skills you learned here apply to every app you’ll make
In the next two sections, you’ll build more useful apps. First, you’ll build a temperature converter that converts a temperature value from Fahrenheit to Celsius. After that, you’ll build a text editor that can open, edit, and save text files Kiểm tra việc hiểu của bạnExpand the code block below for an exercise to check your understanding Exercise. Simulate rolling a six-sided dieShow/Hide Write a program that simulates rolling a six-sided die. There should be one button with the text 969. When the user clicks the button, a random integer from 39 to 971 should be displayedHint. You can generate a random number using 972 in the 973 module. If you’re not familiar with the 973 module, then check out Generating Random Data in Python (Guide) for more informationThe application window should look something like this Hãy thử bài tập này ngay bây giờ Bạn có thể mở rộng khối mã bên dưới để xem giải pháp Solution. Simulate rolling a six-sided dieShow/Hide Đây là một giải pháp khả thi 09Keep in mind that your code may look different Khi bạn đã sẵn sàng, bạn có thể chuyển sang phần tiếp theo Building a Temperature Converter (Example App)In this section, you’ll build a temperature converter application that allows the user to input temperature in degrees Fahrenheit and push a button to convert that temperature to degrees Celsius. You’ll walk through the code step by step. You can also find the full source code at the end of this section for your reference Note. To get the most out of this section, follow along in a Python shell Before you start coding, you’ll first design the app. You need three elements
You can arrange these in a grid with a single row and one column for each widget. That gets you a minimally working application, but it isn’t very user-friendly. Everything needs to have labels You’ll put a label directly to the right of the 976 widget containing the Fahrenheit symbol (℉) so that the user knows that the value 976 should be in degrees Fahrenheit. To do this, set the label text to 985, which uses Python’s named Unicode character support to display the Fahrenheit symbolYou can give 980 a little flair by setting its text to the value 987, which displays a black arrow pointing to the right. You’ll also make sure that 978 always has the Celsius symbol (℃) following the label text 989 to indicate that the result is in degrees Celsius. Here’s what the final window will look likeNow that you know what widgets you need and what the window is going to look like, you can start coding it up. First, import 20 and create a new window 30 991 sets the title of an existing window, while 992 with both arguments set to 993 makes the window have a fixed size. When you finally run this application, the window will have the text Temperature Converter in its title bar. Next, create the 976 widget with a label called 995 and assign both to a 19 widget called 997 31The user will enter the Fahrenheit value in 976, and 995 is used to label 976 with the Fahrenheit symbol. The 997 container groups 976 and 995 togetherYou want 995 to be placed directly to the right of 976. You can lay them out in 997 using the 98 geometry manager with one row and two columns 32You’ve set the 453 parameter to 456 for 976 so that it always sticks to the rightmost edge of its grid cell. You also set 453 to 460 for 995 to keep it stuck to the leftmost edge of its grid cell. Điều này đảm bảo rằng 995 luôn nằm ngay bên phải của 976Now, make the 980 and the 978 for converting the temperature entered into 976 and displaying the results 33Giống như 997, cả 980 và 978 đều được gán cho 03. Cùng với nhau, ba vật dụng này tạo thành ba ô trong lưới ứng dụng chính. Sử dụng 98 để tiếp tục và bố trí chúng ngay bây giờ 34Cuối cùng, chạy ứng dụng 35That looks great. But the button doesn’t do anything just yet. At the top of your script file, just below the 965 line, add a function called 025 36This function reads the value from 976, converts it from Fahrenheit to Celsius, and then displays the result in 978Now go down to the line where you define 980 and set its 942 parameter to 030 37That’s it. You’ve created a fully functional temperature converter app in just twenty-six lines of code. Pretty cool, right? You can expand the code block below to see the full script Temperature Converter Full Source CodeShow/Hide Here’s the full script for your reference 38It’s time to kick things up a notch. Read on to learn how to build a text editor Building a Text Editor (Example App)In this section, you’ll build a text editor application that can create, open, edit, and save text files. There are three essential elements in the application
The three widgets will be arranged so that the two buttons are on the left-hand side of the window, and the text box is on the right-hand side. The whole window should have a minimum height of 800 pixels, and 036 should have a minimum width of 800 pixels. The whole layout should be responsive so that if the window is resized, then 036 is resized as well. The width of the frame holding the buttons should not change, howeverHere’s a sketch of how the window will look You can achieve the desired layout using the 98 geometry manager. The layout contains a single row and two columns
To set the minimum sizes for the window and 036, you can set the 432 parameters of the window methods 424 and 423 to 044. To handle resizing, you can set the 431 parameters of these methods to 39In order to get both buttons into the same column, you’ll need to create a 19 widget called 048. Theo bản phác thảo, hai nút phải được xếp chồng lên nhau theo chiều dọc bên trong khung này, với 032 ở trên cùng. You can do that with either the 98 or 10 geometry manager. For now, you’ll stick with 98 since it’s a little easier to work withNow that you have a plan, you can start coding the application. The first step is to create all of the widgets you need 39Here’s a breakdown of this code
Take a look at line 6 more closely. The 432 parameter of 424 is set to 044, and 431 is set to 39 50The first argument is 52, which sets the height of the first row to 044 pixels and makes sure that the height of the row grows proportionally to the height of the window. There’s only one row in the application layout, so these settings apply to the entire windowLet’s also take a closer look at line 7. Ở đây, bạn sử dụng 423 để đặt thuộc tính 49 và 431 của cột có chỉ số lần lượt là 39 thành 044 và 39 51Remember, row and column indices are zero-based, so these settings apply only to the second column. By configuring just the second column, the text box will expand and contract naturally when the window is resized, while the column containing the buttons will remain at a fixed width Now you can work on the application layout. First, assign the two buttons to the 048 frame using the 98 geometry manager 52These two lines of code create a grid with two rows and one column in the 048 frame since both 032 and 034 have their 04 attribute set to 048. 032 is put in the first row and 034 in the second row so that 032 appears above 034 in the layout, just you planned in your sketchBoth 032 and 034 have their 453 attributes set to 476, which forces the buttons to expand horizontally in both directions and fill the entire frame. This ensures that both buttons are the same sizeYou place five pixels of padding around each button by setting the 412 and 413 parameters to 61. Only 032 has vertical padding. Since it’s on top, the vertical padding offsets the button down from the top of the window a bit and makes sure that there’s a small gap between it and 034Now that 048 is laid out and ready to go, you can set up the grid layout for the rest of the window 53These two lines of code create a grid with one row and two columns for 03. You place 048 in the first column and 036 in the second column so that 048 appears to the left of 036 in the window layoutThe 453 parameter for 048 is set to 475, which forces the whole frame to expand vertically and fill the entire height of its column. 036 fills its entire grid cell because you set its 453 parameter to 478, which forces it to expand in every directionNow that the application layout is complete, add 11 to the bottom of the program and save and run the file 54The following window is displayed That looks great. Nhưng nó chưa làm gì cả, vì vậy bạn cần bắt đầu viết lệnh cho các nút. 032 needs to show a file open dialog and allow the user to select a file. It then needs to open that file and set the text of 036 to the contents of the file. Đây là một hàm 303 thực hiện điều này 55Đây là một sự cố của chức năng này
Bây giờ bạn có thể cập nhật chương trình để 032 gọi 303 bất cứ khi nào nó được nhấp vào. Có một số điều bạn cần làm để cập nhật chương trình. Đầu tiên, nhập 304 từ 305 bằng cách thêm phần nhập sau vào đầu chương trình của bạn 56Tiếp theo, đặt thuộc tính 942 của 323 thành 324 57Lưu tệp và chạy nó để kiểm tra xem mọi thứ có hoạt động không. Sau đó thử mở một tệp văn bản Khi 032 hoạt động, đã đến lúc thực hiện chức năng cho 034. Thao tác này cần mở hộp thoại lưu tệp để người dùng có thể chọn nơi họ muốn lưu tệp. Bạn sẽ sử dụng hộp thoại 327 trong mô-đun 305 cho việc này. Chức năng này cũng cần trích xuất văn bản hiện có trong 036 và ghi văn bản này vào một tệp tại vị trí đã chọn. Đây là một chức năng chỉ làm điều này 58Here’s how this code works
Bây giờ bạn có thể cập nhật chương trình để 034 gọi 339 khi nó được nhấp vào. Một lần nữa, có một vài điều bạn cần làm để cập nhật chương trình. Đầu tiên, nhập 327 từ 305 bằng cách cập nhật phần nhập ở đầu tập lệnh của bạn, như vậy 59Cuối cùng, đặt thuộc tính 942 của 034 thành 344 00Lưu tệp và chạy nó. Bây giờ bạn đã có một trình soạn thảo văn bản tối thiểu nhưng đầy đủ chức năng You can expand the code block below to see the full script Mã nguồn đầy đủ của ứng dụng soạn thảo văn bảnHiển thị/Ẩn Here’s the full script for your reference 01Bây giờ bạn đã xây dựng hai ứng dụng GUI bằng Python và áp dụng nhiều kỹ năng mà bạn đã học được trong hướng dẫn này. Đó không phải là thành tựu nhỏ, vì vậy hãy dành thời gian để cảm thấy hài lòng về những gì bạn đã làm. Bây giờ bạn đã sẵn sàng để tự xử lý một số ứng dụng Phần kết luậnTrong hướng dẫn này, bạn đã học cách bắt đầu với lập trình Python GUI. Tkinter là một lựa chọn hấp dẫn cho khung GUI Python vì nó được tích hợp trong thư viện chuẩn Python và việc tạo các ứng dụng với khung này tương đối dễ dàng Xuyên suốt hướng dẫn này, bạn đã học được một số khái niệm quan trọng về Tkinter
Bây giờ bạn đã thành thạo nền tảng lập trình Python GUI với Tkinter, bước tiếp theo là xây dựng một số ứng dụng của riêng bạn. Bạn sẽ tạo ra cái gì? Tài nguyên bổ sungTrong hướng dẫn này, bạn chỉ chạm vào nền tảng của việc tạo các ứng dụng GUI Python bằng Tkinter. Có một số chủ đề bổ sung không được đề cập ở đây. Trong phần này, bạn sẽ tìm thấy một số tài nguyên tốt nhất hiện có để giúp bạn tiếp tục cuộc hành trình của mình Tài liệu tham khảo Tkinter Dưới đây là một số tài nguyên chính thức để kiểm tra
Tiện ích bổ sung Trong hướng dẫn này, bạn đã tìm hiểu về các tiện ích 05, 16, 17, 18 và 19. Có một số tiện ích khác trong Tkinter, tất cả đều cần thiết để xây dựng các ứng dụng trong thế giới thực. Dưới đây là một số tài nguyên để tiếp tục tìm hiểu về widget
Phân phối ứng dụng Khi bạn đã tạo một ứng dụng với Tkinter, bạn có thể muốn phân phối ứng dụng đó cho đồng nghiệp và bạn bè của mình. Dưới đây là một số hướng dẫn để giúp bạn thực hiện quy trình đó
Các khung GUI khác Tkinter không phải là lựa chọn duy nhất của bạn cho khung GUI Python. Nếu Tkinter không đáp ứng nhu cầu của dự án của bạn, thì đây là một số khuôn khổ khác để xem xét
Lấy bài kiểm tra. Kiểm tra kiến thức của bạn với bài kiểm tra tương tác “Lập trình GUI Python với Tkinter” của chúng tôi. Sau khi hoàn thành, bạn sẽ nhận được điểm số để có thể theo dõi quá trình học tập của mình theo thời gian Lấy bài kiểm tra " Đánh dấu là đã hoàn thành 🐍 Thủ thuật Python 💌 Nhận một Thủ thuật Python ngắn và hấp dẫn được gửi đến hộp thư đến của bạn vài ngày một lần. Không có thư rác bao giờ. Hủy đăng ký bất cứ lúc nào. Được quản lý bởi nhóm Real Python Gửi cho tôi thủ thuật Python » Giới thiệu về David Amos David là một nhà văn, lập trình viên và nhà toán học đam mê khám phá toán học thông qua mã » Thông tin thêm về DavidMỗi hướng dẫn tại Real Python được tạo bởi một nhóm các nhà phát triển để nó đáp ứng các tiêu chuẩn chất lượng cao của chúng tôi. Các thành viên trong nhóm đã làm việc trong hướng dẫn này là Aldren Bartosz Geir Arne Jaya Joanna kate Bậc thầy Kỹ năng Python trong thế giới thực Với quyền truy cập không giới hạn vào Python thực Tham gia với chúng tôi và có quyền truy cập vào hàng nghìn hướng dẫn, khóa học video thực hành và cộng đồng các Pythonistas chuyên gia Nâng cao kỹ năng Python của bạn » Bậc thầy Kỹ năng Python trong thế giới thực Tham gia với chúng tôi và có quyền truy cập vào hàng ngàn hướng dẫn, khóa học video thực hành và cộng đồng Pythonistas chuyên gia Nâng cao kỹ năng Python của bạn » Bạn nghĩ sao? Đánh giá bài viết này Tweet Chia sẻ Chia sẻ EmailBài học số 1 hoặc điều yêu thích mà bạn đã học được là gì? Mẹo bình luận. Những nhận xét hữu ích nhất là những nhận xét được viết với mục đích học hỏi hoặc giúp đỡ các sinh viên khác. Nhận các mẹo để đặt câu hỏi hay và nhận câu trả lời cho các câu hỏi phổ biến trong cổng thông tin hỗ trợ của chúng tôi |