diff --git a/Lib/test/test_tkinter/test_misc.py b/Lib/test/test_tkinter/test_misc.py index 5f75b8d245b3e9..92f6829c3aa3e4 100644 --- a/Lib/test/test_tkinter/test_misc.py +++ b/Lib/test/test_tkinter/test_misc.py @@ -1,9 +1,11 @@ import collections.abc import functools +import os import platform import sys import textwrap import unittest +import warnings import weakref import tkinter from tkinter import TclError @@ -364,6 +366,24 @@ def test_getdouble(self): self.assertEqual(self.root.getdouble(3), 3.0) self.assertRaises(ValueError, self.root.getdouble, 'spam') + def test_readprofile(self): + # gh-153333: readprofile() reads the profile scripts with the source + # file's encoding (here a Latin-1 coding cookie), not the locale + # default encoding. + name = 'readprofiletest' + script = ("# -*- coding: latin-1 -*-\n" + "self.readprofile_result = 'caf\xe9'\n") + self.addCleanup(self.root.__dict__.pop, 'readprofile_result', None) + with os_helper.temp_dir() as home: + with open(os.path.join(home, '.%s.py' % name), 'wb') as f: + f.write(script.encode('latin-1')) + with os_helper.EnvironmentVarGuard() as env: + env['HOME'] = home + with warnings.catch_warnings(): + warnings.simplefilter('error', EncodingWarning) + self.root.readprofile(name, name) + self.assertEqual(self.root.readprofile_result, 'caf\xe9') + def test_getvar(self): self.root.setvar('test_var', 'hello') self.assertEqual(self.root.getvar('test_var'), 'hello') diff --git a/Lib/tkinter/__init__.py b/Lib/tkinter/__init__.py index 83d11a7695ffbe..a194a6199bc4d8 100644 --- a/Lib/tkinter/__init__.py +++ b/Lib/tkinter/__init__.py @@ -2750,11 +2750,13 @@ def readprofile(self, baseName, className): if os.path.isfile(class_tcl): self.tk.call('source', class_tcl) if os.path.isfile(class_py): - exec(open(class_py).read(), dir) + with open(class_py, 'rb') as f: + exec(f.read(), dir) if os.path.isfile(base_tcl): self.tk.call('source', base_tcl) if os.path.isfile(base_py): - exec(open(base_py).read(), dir) + with open(base_py, 'rb') as f: + exec(f.read(), dir) def report_callback_exception(self, exc, val, tb): """Report callback exception on sys.stderr. diff --git a/Misc/NEWS.d/next/Library/2026-07-08-21-15-00.gh-issue-153333.Kp3mZq.rst b/Misc/NEWS.d/next/Library/2026-07-08-21-15-00.gh-issue-153333.Kp3mZq.rst new file mode 100644 index 00000000000000..6fcbd590d0d9d3 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-07-08-21-15-00.gh-issue-153333.Kp3mZq.rst @@ -0,0 +1,3 @@ +The ``readprofile`` method of :class:`tkinter.Tk` now reads the user's +profile scripts using the encoding declared in the file, instead of the +locale encoding.