Ubuntu 18.04 LTS中提示tk未定义,如何安装tkinter?
Hey there, let’s get that annoying "tk is not defined" error sorted out for you right away. This issue happens because the Tkinter module (Python’s interface to the Tk GUI toolkit) isn’t installed on your system. Ubuntu 18.04 comes with both Python 2 and Python 3 pre-installed, so I’ll cover both scenarios below:
For Python 3 (Recommended for Modern Projects)
If you’re using Python 3 (which is the default for most new work), run these commands in your terminal to install the required package:
sudo apt update && sudo apt install python3-tk
To confirm it worked, open a Python 3 shell and run:
import tkinter tkinter._test()
A small test GUI window should pop up if everything’s installed correctly.
For Python 2 (Legacy Use Cases)
If you still need Python 2 support, use this command instead:
sudo apt update && sudo apt install python-tk
Verify the installation with a Python 2 shell:
import Tkinter Tkinter._test()
(Note the capital "T" in Tkinter for Python 2—this differs from the lowercase tkinter used in Python 3.)
Quick Troubleshooting Tip
If you still see the error after installation, double-check which Python interpreter you’re using. Sometimes multiple Python versions are installed side-by-side, so make sure you’re running the version you installed Tkinter for. For example, if you installed python3-tk, launch your script with python3 instead of just python.
内容的提问来源于stack exchange,提问作者Midhun S

