From a76c85e71febf0de7bc22e0b79ce580c45ae27cc Mon Sep 17 00:00:00 2001 From: Shlomi Fish Date: Sat, 11 Jul 2015 19:52:43 +0300 Subject: [PATCH] Ran 2to3 and did some other conversions. Trying to port PySol to Python 3 - this is time consuming. --- pysol.py | 2 +- pysollib/Py2Canvas.py | 195 +++++++++++++++++++++++ pysollib/actions.py | 10 +- pysollib/app.py | 26 +-- pysollib/configobj/configobj.py | 84 +++++----- pysollib/configobj/validate.py | 16 +- pysollib/customgame.py | 2 +- pysollib/game.py | 28 ++-- pysollib/gamedb.py | 20 +-- pysollib/games/__init__.py | 128 +++++++-------- pysollib/games/acesup.py | 2 +- pysollib/games/auldlangsyne.py | 2 +- pysollib/games/camelot.py | 2 +- pysollib/games/capricieuse.py | 2 +- pysollib/games/dieboesesieben.py | 2 +- pysollib/games/diplomat.py | 4 +- pysollib/games/fortythieves.py | 2 +- pysollib/games/freecell.py | 2 +- pysollib/games/glenwood.py | 2 +- pysollib/games/golf.py | 2 +- pysollib/games/grandfathersclock.py | 2 +- pysollib/games/gypsy.py | 2 +- pysollib/games/harp.py | 2 +- pysollib/games/klondike.py | 2 +- pysollib/games/mahjongg/__init__.py | 8 +- pysollib/games/mahjongg/mahjongg.py | 28 ++-- pysollib/games/mahjongg/mahjongg1.py | 2 +- pysollib/games/mahjongg/mahjongg2.py | 2 +- pysollib/games/mahjongg/mahjongg3.py | 2 +- pysollib/games/mahjongg/shisensho.py | 12 +- pysollib/games/montecarlo.py | 2 +- pysollib/games/napoleon.py | 2 +- pysollib/games/pasdedeux.py | 2 +- pysollib/games/picturegallery.py | 2 +- pysollib/games/royalcotillion.py | 6 +- pysollib/games/special/__init__.py | 10 +- pysollib/games/special/hanoi.py | 10 +- pysollib/games/special/pegged.py | 2 +- pysollib/games/special/poker.py | 2 +- pysollib/games/special/tarock.py | 2 +- pysollib/games/sultan.py | 2 +- pysollib/games/threepeaks.py | 2 +- pysollib/games/ultra/__init__.py | 16 +- pysollib/games/ultra/dashavatara.py | 2 +- pysollib/games/ultra/hanafuda.py | 4 +- pysollib/games/ultra/hanafuda1.py | 6 +- pysollib/games/ultra/hexadeck.py | 2 +- pysollib/games/ultra/larasgame.py | 24 +-- pysollib/games/ultra/matrix.py | 2 +- pysollib/games/ultra/mughal.py | 2 +- pysollib/games/ultra/tarock.py | 2 +- pysollib/games/windmill.py | 2 +- pysollib/games/yukon.py | 2 +- pysollib/hint.py | 20 +-- pysollib/images.py | 2 +- pysollib/init.py | 16 +- pysollib/macosx/appSupport.py | 2 +- pysollib/main.py | 6 +- pysollib/mfxutil.py | 20 +-- pysollib/mygettext.py | 12 +- pysollib/options.py | 18 +-- pysollib/pysolaudio.py | 2 +- pysollib/pysolgtk/card.py | 2 +- pysollib/pysolgtk/edittextdialog.py | 2 +- pysollib/pysolgtk/fontsdialog.py | 2 +- pysollib/pysolgtk/gameinfodialog.py | 2 +- pysollib/pysolgtk/menubar.py | 28 ++-- pysollib/pysolgtk/playeroptionsdialog.py | 2 +- pysollib/pysolgtk/progressbar.py | 4 +- pysollib/pysolgtk/selectcardset.py | 10 +- pysollib/pysolgtk/selectgame.py | 12 +- pysollib/pysolgtk/selecttile.py | 10 +- pysollib/pysolgtk/soundoptionsdialog.py | 2 +- pysollib/pysolgtk/statusbar.py | 6 +- pysollib/pysolgtk/tkcanvas.py | 30 ++-- pysollib/pysolgtk/tkhtml.py | 24 +-- pysollib/pysolgtk/tkstats.py | 6 +- pysollib/pysolgtk/tkwidget.py | 2 +- pysollib/pysolgtk/tkwrap.py | 14 +- pysollib/pysolrandom.py | 42 ++--- pysollib/resource.py | 36 ++--- pysollib/stack.py | 6 +- pysollib/stats.py | 4 +- pysollib/tile/card.py | 2 +- pysollib/tile/colorsdialog.py | 26 +-- pysollib/tile/edittextdialog.py | 8 +- pysollib/tile/findcarddialog.py | 14 +- pysollib/tile/fontsdialog.py | 22 +-- pysollib/tile/gameinfodialog.py | 6 +- pysollib/tile/menubar.py | 150 ++++++++--------- pysollib/tile/playeroptionsdialog.py | 12 +- pysollib/tile/progressbar.py | 12 +- pysollib/tile/selectcardset.py | 46 +++--- pysollib/tile/selectgame.py | 28 ++-- pysollib/tile/selecttile.py | 20 +-- pysollib/tile/selecttree.py | 6 +- pysollib/tile/solverdialog.py | 20 +-- pysollib/tile/soundoptionsdialog.py | 58 +++---- pysollib/tile/statusbar.py | 14 +- pysollib/tile/timeoutsdialog.py | 18 +-- pysollib/tile/tkcanvas.py | 24 +-- pysollib/tile/tkconst.py | 26 +-- pysollib/tile/tkhtml.py | 32 ++-- pysollib/tile/tkstats.py | 32 ++-- pysollib/tile/tktree.py | 16 +- pysollib/tile/tkutil.py | 24 +-- pysollib/tile/tkwidget.py | 42 ++--- pysollib/tile/tkwrap.py | 26 +-- pysollib/tile/toolbar.py | 18 +-- pysollib/tile/ttk.py | 60 +++---- pysollib/tile/wizarddialog.py | 22 +-- pysollib/tk/card.py | 2 +- pysollib/tk/colorsdialog.py | 30 ++-- pysollib/tk/edittextdialog.py | 8 +- pysollib/tk/findcarddialog.py | 14 +- pysollib/tk/fontsdialog.py | 38 ++--- pysollib/tk/gameinfodialog.py | 16 +- pysollib/tk/menubar.py | 144 ++++++++--------- pysollib/tk/playeroptionsdialog.py | 34 ++-- pysollib/tk/progressbar.py | 24 +-- pysollib/tk/selectcardset.py | 66 ++++---- pysollib/tk/selectgame.py | 42 ++--- pysollib/tk/selecttile.py | 18 +-- pysollib/tk/selecttree.py | 6 +- pysollib/tk/solverdialog.py | 54 +++---- pysollib/tk/soundoptionsdialog.py | 72 ++++----- pysollib/tk/statusbar.py | 16 +- pysollib/tk/tabpage.py | 16 +- pysollib/tk/timeoutsdialog.py | 22 +-- pysollib/tk/tkcanvas.py | 24 +-- pysollib/tk/tkconst.py | 26 +-- pysollib/tk/tkhtml.py | 42 ++--- pysollib/tk/tkstats.py | 96 +++++------ pysollib/tk/tktree.py | 16 +- pysollib/tk/tkutil.py | 24 +-- pysollib/tk/tkwidget.py | 64 ++++---- pysollib/tk/tkwrap.py | 26 +-- pysollib/tk/toolbar.py | 30 ++-- pysollib/tk/wizarddialog.py | 36 ++--- pysollib/winsystems/__init__.py | 6 +- pysollib/winsystems/aqua.py | 6 +- pysollib/winsystems/common.py | 2 +- pysollib/winsystems/win32.py | 2 +- pysollib/winsystems/x11.py | 14 +- pysollib/wizardutil.py | 10 +- 145 files changed, 1537 insertions(+), 1340 deletions(-) create mode 100644 pysollib/Py2Canvas.py diff --git a/pysol.py b/pysol.py index 075f398d..c913e2bf 100755 --- a/pysol.py +++ b/pysol.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 ##---------------------------------------------------------------------------## ## ## PySol -- a Python Solitaire game diff --git a/pysollib/Py2Canvas.py b/pysollib/Py2Canvas.py new file mode 100644 index 00000000..6762fa83 --- /dev/null +++ b/pysollib/Py2Canvas.py @@ -0,0 +1,195 @@ +# Copied from: +# /usr/lib64/python2.7/lib-tk/Canvas.py +# +# Python 2-Licensed. +# -- Shlomi Fish + +# This module exports classes for the various canvas item types + +# NOTE: This module was an experiment and is now obsolete. +# It's best to use the Tkinter.Canvas class directly. + +from tkinter import Canvas, _cnfmerge, _flatten + +class CanvasItem: + def __init__(self, canvas, itemType, *args, **kw): + self.canvas = canvas + self.id = canvas._create(itemType, args, kw) + if not hasattr(canvas, 'items'): + canvas.items = {} + canvas.items[self.id] = self + def __str__(self): + return str(self.id) + def __repr__(self): + return '<%s, id=%d>' % (self.__class__.__name__, self.id) + def delete(self): + del self.canvas.items[self.id] + self.canvas.delete(self.id) + def __getitem__(self, key): + v = self.canvas.tk.split(self.canvas.tk.call( + self.canvas._w, 'itemconfigure', + self.id, '-' + key)) + return v[4] + cget = __getitem__ + def __setitem__(self, key, value): + self.canvas.itemconfig(self.id, {key: value}) + def keys(self): + if not hasattr(self, '_keys'): + self._keys = map(lambda x, tk=self.canvas.tk: + tk.splitlist(x)[0][1:], + self.canvas.tk.splitlist( + self.canvas._do( + 'itemconfigure', + (self.id,)))) + return self._keys + def has_key(self, key): + return key in self.keys() + def __contains__(self, key): + return key in self.keys() + def addtag(self, tag, option='withtag'): + self.canvas.addtag(tag, option, self.id) + def bbox(self): + x1, y1, x2, y2 = self.canvas.bbox(self.id) + return (x1, y1), (x2, y2) + def bind(self, sequence=None, command=None, add=None): + return self.canvas.tag_bind(self.id, sequence, command, add) + def unbind(self, sequence, funcid=None): + self.canvas.tag_unbind(self.id, sequence, funcid) + def config(self, cnf={}, **kw): + return self.canvas.itemconfig(self.id, _cnfmerge((cnf, kw))) + def coords(self, pts = ()): + flat = () + for x, y in pts: flat = flat + (x, y) + return self.canvas.coords(self.id, *flat) + def dchars(self, first, last=None): + self.canvas.dchars(self.id, first, last) + def dtag(self, ttd): + self.canvas.dtag(self.id, ttd) + def focus(self): + self.canvas.focus(self.id) + def gettags(self): + return self.canvas.gettags(self.id) + def icursor(self, index): + self.canvas.icursor(self.id, index) + def index(self, index): + return self.canvas.index(self.id, index) + def insert(self, beforethis, string): + self.canvas.insert(self.id, beforethis, string) + def lower(self, belowthis=None): + self.canvas.tag_lower(self.id, belowthis) + def move(self, xamount, yamount): + self.canvas.move(self.id, xamount, yamount) + def tkraise(self, abovethis=None): + self.canvas.tag_raise(self.id, abovethis) + raise_ = tkraise # BW compat + def scale(self, xorigin, yorigin, xscale, yscale): + self.canvas.scale(self.id, xorigin, yorigin, xscale, yscale) + def type(self): + return self.canvas.type(self.id) + +class Arc(CanvasItem): + def __init__(self, canvas, *args, **kw): + CanvasItem.__init__(self, canvas, 'arc', *args, **kw) + +class Bitmap(CanvasItem): + def __init__(self, canvas, *args, **kw): + CanvasItem.__init__(self, canvas, 'bitmap', *args, **kw) + +class ImageItem(CanvasItem): + def __init__(self, canvas, *args, **kw): + CanvasItem.__init__(self, canvas, 'image', *args, **kw) + +class Line(CanvasItem): + def __init__(self, canvas, *args, **kw): + CanvasItem.__init__(self, canvas, 'line', *args, **kw) + +class Oval(CanvasItem): + def __init__(self, canvas, *args, **kw): + CanvasItem.__init__(self, canvas, 'oval', *args, **kw) + +class Polygon(CanvasItem): + def __init__(self, canvas, *args, **kw): + CanvasItem.__init__(self, canvas, 'polygon', *args, **kw) + +class Rectangle(CanvasItem): + def __init__(self, canvas, *args, **kw): + CanvasItem.__init__(self, canvas, 'rectangle', *args, **kw) + +# XXX "Text" is taken by the Text widget... +class CanvasText(CanvasItem): + def __init__(self, canvas, *args, **kw): + CanvasItem.__init__(self, canvas, 'text', *args, **kw) + +class Window(CanvasItem): + def __init__(self, canvas, *args, **kw): + CanvasItem.__init__(self, canvas, 'window', *args, **kw) + +class Group: + def __init__(self, canvas, tag=None): + if not tag: + tag = 'Group%d' % id(self) + self.tag = self.id = tag + self.canvas = canvas + self.canvas.dtag(self.tag) + def str(self): + return self.tag + __str__ = str + def _do(self, cmd, *args): + return self.canvas._do(cmd, (self.tag,) + _flatten(args)) + def addtag_above(self, tagOrId): + self._do('addtag', 'above', tagOrId) + def addtag_all(self): + self._do('addtag', 'all') + def addtag_below(self, tagOrId): + self._do('addtag', 'below', tagOrId) + def addtag_closest(self, x, y, halo=None, start=None): + self._do('addtag', 'closest', x, y, halo, start) + def addtag_enclosed(self, x1, y1, x2, y2): + self._do('addtag', 'enclosed', x1, y1, x2, y2) + def addtag_overlapping(self, x1, y1, x2, y2): + self._do('addtag', 'overlapping', x1, y1, x2, y2) + def addtag_withtag(self, tagOrId): + self._do('addtag', 'withtag', tagOrId) + def bbox(self): + return self.canvas._getints(self._do('bbox')) + def bind(self, sequence=None, command=None, add=None): + return self.canvas.tag_bind(self.id, sequence, command, add) + def unbind(self, sequence, funcid=None): + self.canvas.tag_unbind(self.id, sequence, funcid) + def coords(self, *pts): + return self._do('coords', pts) + def dchars(self, first, last=None): + self._do('dchars', first, last) + def delete(self): + self._do('delete') + def dtag(self, tagToDelete=None): + self._do('dtag', tagToDelete) + def focus(self): + self._do('focus') + def gettags(self): + return self.canvas.tk.splitlist(self._do('gettags', self.tag)) + def icursor(self, index): + return self._do('icursor', index) + def index(self, index): + return self.canvas.tk.getint(self._do('index', index)) + def insert(self, beforeThis, string): + self._do('insert', beforeThis, string) + def config(self, cnf={}, **kw): + return self.canvas.itemconfigure(self.tag, _cnfmerge((cnf,kw))) + def lower(self, belowThis=None): + self._do('lower', belowThis) + def move(self, xAmount, yAmount): + self._do('move', xAmount, yAmount) + def tkraise(self, aboveThis=None): + self._do('raise', aboveThis) + lift = tkraise + def scale(self, xOrigin, yOrigin, xScale, yScale): + self._do('scale', xOrigin, yOrigin, xScale, yScale) + def select_adjust(self, index): + self.canvas._do('select', ('adjust', self.tag, index)) + def select_from(self, index): + self.canvas._do('select', ('from', self.tag, index)) + def select_to(self, index): + self.canvas._do('select', ('to', self.tag, index)) + def type(self): + return self._do('type') diff --git a/pysollib/actions.py b/pysollib/actions.py index 0f0421e8..bfd16df1 100644 --- a/pysollib/actions.py +++ b/pysollib/actions.py @@ -116,7 +116,7 @@ class PysolMenubar(PysolMenubarTk): def _clearMenuState(self): ms = self.menustate - for k, v in ms.__dict__.items(): + for k, v in list(ms.__dict__.items()): if isinstance(v, list): ms.__dict__[k] = [0] * len(v) else: @@ -263,7 +263,7 @@ class PysolMenubar(PysolMenubarTk): id = self.game.id if not self.app.getGameInfo(id): raise ValueError - except (ValueError, TypeError), ex: + except (ValueError, TypeError) as ex: d = MfxMessageDialog(self.top, title=_("Invalid game number"), text=_("Invalid game number\n") + str(seed), bitmap="error") @@ -497,7 +497,7 @@ class PysolMenubar(PysolMenubarTk): try: fd = open(fn, 'a') fd.write(text.encode(enc, 'replace')) - except Exception, err: + except Exception as err: d = MfxExceptionDialog(self.top, err, text=_("Error while writing to file")) else: @@ -524,7 +524,7 @@ class PysolMenubar(PysolMenubarTk): file = open(filename, "a") a = FileStatsFormatter(self.app, file) write_method(a, player) - except EnvironmentError, ex: + except EnvironmentError as ex: if file: file.close() d = MfxExceptionDialog(self.top, ex, text=_("Error while writing to file")) @@ -779,7 +779,7 @@ class PysolMenubar(PysolMenubarTk): index = self.app.audio.getMusicInfo() music = self.app.music_manager.get(index) if music: - print "playing music:", music.filename + print("playing music:", music.filename) def mIconify(self, *args): if self._cancelDrag(break_pause=False): return diff --git a/pysollib/app.py b/pysollib/app.py index afb5a2f8..a72112a0 100644 --- a/pysollib/app.py +++ b/pysollib/app.py @@ -368,7 +368,7 @@ class Application: savegames = os.path.join(config, "savegames"), maint = os.path.join(config, "maint"), # debug ) - for k, v in self.dn.__dict__.items(): + for k, v in list(self.dn.__dict__.items()): ## if os.name == "nt": ## v = os.path.normcase(v) v = os.path.normpath(v) @@ -381,7 +381,7 @@ class Application: holdgame = os.path.join(self.dn.config, "holdgame.dat"), comments = os.path.join(self.dn.config, "comments.dat"), ) - for k, v in self.dn.__dict__.items(): + for k, v in list(self.dn.__dict__.items()): if os.name == "nt": v = os.path.normcase(v) v = os.path.normpath(v) @@ -503,7 +503,7 @@ class Application: compound=self.opt.toolbar_compound) self.toolbar.show(self.opt.toolbar) if TOOLKIT == 'tk': - for w, v in self.opt.toolbar_vars.items(): + for w, v in list(self.opt.toolbar_vars.items()): self.toolbar.config(w, v) # if self.intro.progress: self.intro.progress.update(step=1) @@ -756,7 +756,7 @@ class Application: def loadImages4(self): # load all remaining images - for k, v in self.gimages.__dict__.items(): + for k, v in list(self.gimages.__dict__.items()): if isinstance(v, list): for i in range(len(v)): if isinstance(v[i], str): @@ -892,7 +892,7 @@ class Application: self.subsampled_images = simages self.updateCardset(id, update=update) r = 1 - except (Exception, TclError, UnpicklingError), ex: + except (Exception, TclError, UnpicklingError) as ex: traceback.print_exc() cs.error = 1 # restore settings @@ -1237,7 +1237,7 @@ Please select a %s type %s. def getAllUserNames(self): names = [] - for n in self.stats.games_stats.keys(): + for n in list(self.stats.games_stats.keys()): if n is None: # demo continue if self.stats.games_stats[n]: @@ -1258,7 +1258,7 @@ Please select a %s type %s. if not dir or not os.path.isdir(dir): return names = os.listdir(dir) - names = map(os.path.normcase, names) + names = list(map(os.path.normcase, names)) names.sort() for name in names: m = re.search(r"^(.+)\.py$", name) @@ -1266,7 +1266,7 @@ Please select a %s type %s. if m and os.path.isfile(n): try: loadGame(m.group(1), n) - except Exception, ex: + except Exception as ex: if DEBUG: traceback.print_exc() print_err(_("error loading plugin %s: %s") % (n, ex)) @@ -1439,10 +1439,10 @@ Please select a %s type %s. print_err('fail _readCardsetConfig: %s %s' % (d, f1)) pass - except Exception, err: + except Exception as err: ##traceback.print_exc() pass - except EnvironmentError, ex: + except EnvironmentError as ex: pass # register cardsets for obj in found: @@ -1493,7 +1493,7 @@ Please select a %s type %s. if key not in t: t[key] = 1 found.append((n, tile)) - except EnvironmentError, ex: + except EnvironmentError as ex: pass # register tiles found.sort() @@ -1517,7 +1517,7 @@ Please select a %s type %s. names = [] if dir and os.path.isdir(dir): names = os.listdir(dir) - names = map(os.path.normcase, names) + names = list(map(os.path.normcase, names)) names.sort() for name in names: if not name or not ext_re.search(name): @@ -1534,7 +1534,7 @@ Please select a %s type %s. if key not in t: t[key] = 1 found.append((n, obj)) - except EnvironmentError, ex: + except EnvironmentError as ex: pass # register songs found.sort() diff --git a/pysollib/configobj/configobj.py b/pysollib/configobj/configobj.py index 1036e0d7..5ce9cb55 100644 --- a/pysollib/configobj/configobj.py +++ b/pysollib/configobj/configobj.py @@ -16,7 +16,7 @@ # http://lists.sourceforge.net/lists/listinfo/configobj-develop # Comments, suggestions and bug reports welcome. -from __future__ import generators + import sys INTP_VER = sys.version_info[:2] @@ -89,7 +89,7 @@ BOM_SET = { } try: - from validate import VdtMissingValue + from .validate import VdtMissingValue except ImportError: VdtMissingValue = None @@ -176,7 +176,7 @@ class Builder: return m(o) def build_List(self, o): - return map(self.build, o.getChildren()) + return list(map(self.build, o.getChildren())) def build_Const(self, o): return o.value @@ -185,7 +185,7 @@ class Builder: d = {} i = iter(map(self.build, o.getChildren())) for el in i: - d[el] = i.next() + d[el] = next(i) return d def build_Tuple(self, o): @@ -203,7 +203,7 @@ class Builder: raise UnknownType('Undefined Name') def build_Add(self, o): - real, imag = map(self.build_Const, o.getChildren()) + real, imag = list(map(self.build_Const, o.getChildren())) try: real = float(real) except TypeError: @@ -320,7 +320,7 @@ class InterpolationEngine(object): This is similar to a depth-first-search algorithm. """ # Have we been here already? - if backtrail.has_key((key, section.name)): + if (key, section.name) in backtrail: # Yes - infinite loop detected raise InterpolationLoopError(key) # Place a marker on our backtrail so we won't come back here again @@ -549,9 +549,9 @@ class Section(dict): creating a new sub-section. """ if not isinstance(key, StringTypes): - raise ValueError, 'The key "%s" is not a string.' % key + raise ValueError('The key "%s" is not a string.' % key) # add the comment - if not self.comments.has_key(key): + if key not in self.comments: self.comments[key] = [] self.inline_comments[key] = '' # remove the entry from defaults @@ -559,13 +559,13 @@ class Section(dict): self.defaults.remove(key) # if isinstance(value, Section): - if not self.has_key(key): + if key not in self: self.sections.append(key) dict.__setitem__(self, key, value) elif isinstance(value, dict) and not unrepr: # First create the new depth level, # then create the section - if not self.has_key(key): + if key not in self: self.sections.append(key) new_depth = self.depth + 1 dict.__setitem__( @@ -578,7 +578,7 @@ class Section(dict): indict=value, name=key)) else: - if not self.has_key(key): + if key not in self: self.scalars.append(key) if not self.main.stringify: if isinstance(value, StringTypes): @@ -586,10 +586,10 @@ class Section(dict): elif isinstance(value, (list, tuple)): for entry in value: if not isinstance(entry, StringTypes): - raise TypeError, ( + raise TypeError( 'Value is not a string "%s".' % entry) else: - raise TypeError, 'Value is not a string "%s".' % value + raise TypeError('Value is not a string "%s".' % value) dict.__setitem__(self, key, value) def __delitem__(self, key): @@ -635,7 +635,7 @@ class Section(dict): """Pops the first (key,val)""" sequence = (self.scalars + self.sections) if not sequence: - raise KeyError, ": 'popitem(): dictionary is empty'" + raise KeyError(": 'popitem(): dictionary is empty'") key = sequence[0] val = self[key] del self[key] @@ -666,7 +666,7 @@ class Section(dict): def items(self): """ """ - return zip((self.scalars + self.sections), self.values()) + return list(zip((self.scalars + self.sections), list(self.values()))) def keys(self): """ """ @@ -678,7 +678,7 @@ class Section(dict): def iteritems(self): """ """ - return iter(self.items()) + return iter(list(self.items())) def iterkeys(self): """ """ @@ -688,7 +688,7 @@ class Section(dict): def itervalues(self): """ """ - return iter(self.values()) + return iter(list(self.values())) def __repr__(self): return '{%s}' % ', '.join([('%s: %s' % (repr(key), repr(self[key]))) @@ -744,7 +744,7 @@ class Section(dict): >>> c2 {'section1': {'option1': 'False', 'subsection': {'more_options': 'False'}}} """ - for key, val in indict.items(): + for key, val in list(indict.items()): if (key in self and isinstance(self[key], dict) and isinstance(val, dict)): self[key].merge(val) @@ -765,7 +765,7 @@ class Section(dict): elif oldkey in self.sections: the_list = self.sections else: - raise KeyError, 'Key "%s" not found.' % oldkey + raise KeyError('Key "%s" not found.' % oldkey) pos = the_list.index(oldkey) # val = self[oldkey] @@ -1144,9 +1144,9 @@ class ConfigObj(Section): Section.__init__(self, self, 0, self) # defaults = OPTION_DEFAULTS.copy() - for entry in options.keys(): - if entry not in defaults.keys(): - raise TypeError, 'Unrecognised option "%s".' % entry + for entry in list(options.keys()): + if entry not in list(defaults.keys()): + raise TypeError('Unrecognised option "%s".' % entry) # TODO: check the values too. # # Add any explicit options to the defaults @@ -1180,7 +1180,7 @@ class ConfigObj(Section): infile = open(infile).read() or [] elif self.file_error: # raise an error if the file doesn't exist - raise IOError, 'Config file not found: "%s".' % self.filename + raise IOError('Config file not found: "%s".' % self.filename) else: # file doesn't already exist if self.create_empty: @@ -1212,7 +1212,7 @@ class ConfigObj(Section): # needs splitting into lines - but needs doing *after* decoding # in case it's not an 8 bit encoding else: - raise TypeError, ('infile must be a filename,' + raise TypeError('infile must be a filename,' ' file like object, or list of lines.') # if infile: @@ -1304,7 +1304,7 @@ class ConfigObj(Section): enc = BOM_LIST[self.encoding.lower()] if enc == 'utf_16': # For UTF16 we try big endian and little endian - for BOM, (encoding, final_encoding) in BOMS.items(): + for BOM, (encoding, final_encoding) in list(BOMS.items()): if not final_encoding: # skip UTF8 continue @@ -1334,7 +1334,7 @@ class ConfigObj(Section): return self._decode(infile, self.encoding) # # No encoding specified - so we need to check for UTF8/UTF16 - for BOM, (encoding, final_encoding) in BOMS.items(): + for BOM, (encoding, final_encoding) in list(BOMS.items()): if not line.startswith(BOM): continue else: @@ -1382,7 +1382,7 @@ class ConfigObj(Section): # NOTE: Could raise a ``UnicodeDecodeError`` return infile.decode(encoding).splitlines(True) for i, line in enumerate(infile): - if not isinstance(line, unicode): + if not isinstance(line, str): # NOTE: The isinstance test here handles mixed lists of unicode/string # NOTE: But the decode will break on any non-string values # NOTE: Or could raise a ``UnicodeDecodeError`` @@ -1473,7 +1473,7 @@ class ConfigObj(Section): NestingError, infile, cur_index) # sect_name = self._unquote(sect_name) - if parent.has_key(sect_name): + if sect_name in parent: self._handle_error( 'Duplicate section name at line %s.', DuplicateError, infile, cur_index) @@ -1519,7 +1519,7 @@ class ConfigObj(Section): comment = '' try: value = unrepr(value) - except Exception, e: + except Exception as e: if type(e) == UnknownType: msg = 'Unknown name or type in value at line %s.' else: @@ -1532,7 +1532,7 @@ class ConfigObj(Section): comment = '' try: value = unrepr(value) - except Exception, e: + except Exception as e: if isinstance(e, UnknownType): msg = 'Unknown name or type in value at line %s.' else: @@ -1551,7 +1551,7 @@ class ConfigObj(Section): continue # key = self._unquote(key) - if this_section.has_key(key): + if key in this_section: self._handle_error( 'Duplicate keyword name at line %s.', DuplicateError, infile, cur_index) @@ -1653,7 +1653,7 @@ class ConfigObj(Section): if self.stringify: value = str(value) else: - raise TypeError, 'Value "%s" is not a string.' % value + raise TypeError('Value "%s" is not a string.' % value) squot = "'%s'" dquot = '"%s"' noquot = "%s" @@ -1670,7 +1670,7 @@ class ConfigObj(Section): # for normal values either single or double quotes will do elif '\n' in value: # will only happen if multiline is off - e.g. '\n' in key - raise ConfigObjError, ('Value "%s" cannot be safely quoted.' % + raise ConfigObjError('Value "%s" cannot be safely quoted.' % value) elif ((value[0] not in wspace_plus) and (value[-1] not in wspace_plus) and @@ -1678,7 +1678,7 @@ class ConfigObj(Section): quot = noquot else: if ("'" in value) and ('"' in value): - raise ConfigObjError, ( + raise ConfigObjError( 'Value "%s" cannot be safely quoted.' % value) elif '"' in value: quot = squot @@ -1689,7 +1689,7 @@ class ConfigObj(Section): else: # if value has '\n' or "'" *and* '"', it will need triple quotes if (value.find('"""') != -1) and (value.find("'''") != -1): - raise ConfigObjError, ( + raise ConfigObjError( 'Value "%s" cannot be safely quoted.' % value) if value.find('"""') == -1: quot = tdquot @@ -1787,11 +1787,11 @@ class ConfigObj(Section): raise_errors=True, file_error=True, list_values=False) - except ConfigObjError, e: + except ConfigObjError as e: # FIXME: Should these errors have a reference # to the already parsed ConfigObj ? raise ConfigspecError('Parsing configspec failed: %s' % e) - except IOError, e: + except IOError as e: raise IOError('Reading configspec failed: %s' % e) self._set_configspec_value(configspec, self) @@ -1821,7 +1821,7 @@ class ConfigObj(Section): section._cs_section_comments[entry] = configspec.comments[entry] section._cs_section_inline_comments[entry] = ( configspec.inline_comments[entry]) - if not section.has_key(entry): + if entry not in section: section[entry] = {} self._set_configspec_value(configspec[entry], section[entry]) @@ -1852,7 +1852,7 @@ class ConfigObj(Section): # section.configspec = scalars for entry in sections: - if not section.has_key(entry): + if entry not in section: section[entry] = {} self._handle_repeat(section[entry], sections[entry]) @@ -2029,7 +2029,7 @@ class ConfigObj(Section): """ if section is None: if self.configspec is None: - raise ValueError, 'No configspec supplied.' + raise ValueError('No configspec supplied.') if preserve_errors: if VdtMissingValue is None: raise ImportError('Missing validate module.') @@ -2078,7 +2078,7 @@ class ConfigObj(Section): val, missing=missing ) - except validator.baseErrorClass, e: + except validator.baseErrorClass as e: if not preserve_errors or isinstance(e, VdtMissingValue): out[entry] = False else: @@ -2262,7 +2262,7 @@ def flatten_errors(cfg, res, levels=None, results=None): if levels: levels.pop() return results - for (key, val) in res.items(): + for (key, val) in list(res.items()): if val == True: continue if isinstance(cfg.get(key), dict): diff --git a/pysollib/configobj/validate.py b/pysollib/configobj/validate.py index cb403543..5f89a4e3 100644 --- a/pysollib/configobj/validate.py +++ b/pysollib/configobj/validate.py @@ -167,7 +167,7 @@ if INTP_VER < (2, 2): raise RuntimeError("Python v.2.2 or later needed") import re -StringTypes = (str, unicode) +StringTypes = (str, str) _list_arg = re.compile(r''' @@ -289,7 +289,7 @@ def dottedQuadToNum(ip): except socket.error: # bug in inet_aton, corrected in Python 2.3 if ip.strip() == '255.255.255.255': - return 0xFFFFFFFFL + return 0xFFFFFFFF else: raise ValueError('Not a good dotted-quad IP: %s' % ip) return @@ -322,7 +322,7 @@ def numToDottedQuad(num): # no need to intercept here, 4294967295L is fine try: return socket.inet_ntoa( - struct.pack('!L', long(num))) + struct.pack('!L', int(num))) except (socket.error, struct.error, OverflowError): raise ValueError('Not a good numeric IP: %s' % num) @@ -686,10 +686,10 @@ def _is_num_param(names, values, to_float=False): for (name, val) in zip(names, values): if val is None: out_params.append(val) - elif isinstance(val, (int, long, float, StringTypes)): + elif isinstance(val, (int, float, StringTypes)): try: out_params.append(fun(val)) - except ValueError, e: + except ValueError as e: raise VdtParamError(name, val) else: raise VdtParamError(name, val) @@ -743,7 +743,7 @@ def is_integer(value, min=None, max=None): """ # print value, type(value) (min_val, max_val) = _is_num_param(('min', 'max'), (min, max)) - if not isinstance(value, (int, long, StringTypes)): + if not isinstance(value, (int, StringTypes)): raise VdtTypeError(value) if isinstance(value, StringTypes): # if it's a string - does it represent an integer ? @@ -794,7 +794,7 @@ def is_float(value, min=None, max=None): """ (min_val, max_val) = _is_num_param( ('min', 'max'), (min, max), to_float=True) - if not isinstance(value, (int, long, float, StringTypes)): + if not isinstance(value, (int, float, StringTypes)): raise VdtTypeError(value) if not isinstance(value, float): # if it's a string - does it represent a float ? @@ -1176,7 +1176,7 @@ def is_mixed_list(value, *args): raise VdtValueTooLongError(value) try: return [fun_dict[arg](val) for arg, val in zip(args, value)] - except KeyError, e: + except KeyError as e: raise VdtParamError('mixed_list', e) def is_option(value, *options): diff --git a/pysollib/customgame.py b/pysollib/customgame.py index f9f61e1f..78c31808 100644 --- a/pysollib/customgame.py +++ b/pysollib/customgame.py @@ -37,7 +37,7 @@ from pysollib.wizardutil import WizardWidgets def get_settings(ss): s = {} for w in WizardWidgets: - if isinstance(w, basestring): + if isinstance(w, str): continue if w.var_name in ss: v = ss[w.var_name] diff --git a/pysollib/game.py b/pysollib/game.py index fffb6131..5a870799 100644 --- a/pysollib/game.py +++ b/pysollib/game.py @@ -30,7 +30,7 @@ import traceback from pysollib.mygettext import _, n_ from gettext import ungettext -from cStringIO import StringIO +from io import StringIO # PySol imports from pysollib.mfxutil import Pickler, Unpickler, UnpicklingError @@ -765,7 +765,7 @@ class Game: state = self.random.getstate() self.app.gamerandom.setstate(state) # we want at least 17 digits - seed = self.app.gamerandom.randrange(10000000000000000L, + seed = self.app.gamerandom.randrange(10000000000000000, PysolRandom.MAX_SEED) self.random = PysolRandom(seed) self.random.origin = self.random.ORIGIN_RANDOM @@ -810,7 +810,7 @@ class Game: else: # new group sg[s] = [s.id] - sg = sg.values() + sg = list(sg.values()) self.sn_groups = sg ##print sg @@ -1017,13 +1017,13 @@ class Game: if self.preview: return tb, sb = self.app.toolbar, self.app.statusbar - for k, v in kw.items(): + for k, v in list(kw.items()): if k == "gamenumber": if v is None: if sb: sb.updateText(gamenumber="") #self.top.wm_title("%s - %s" % (TITLE, self.getTitleName())) continue - if isinstance(v, basestring): + if isinstance(v, str): if sb: sb.updateText(gamenumber=v) #self.top.wm_title("%s - %s %s" % (TITLE, # self.getTitleName(), v)) @@ -1057,7 +1057,7 @@ class Game: if v is None: if tb: tb.updateText(player=_("Player\n")) continue - if isinstance(v, basestring): + if isinstance(v, str): if tb: #if self.app.opt.toolbar_size: if self.app.toolbar.getSize(): @@ -1076,7 +1076,7 @@ class Game: if k == "time": if v is None: if sb: sb.updateText(time='') - if isinstance(v, basestring): + if isinstance(v, str): if sb: sb.updateText(time=v) continue if k == 'stuck': @@ -1508,7 +1508,7 @@ class Game: cards = self.cards[:] scards = [] ncards = min(10, len(cards)) - for i in xrange(ncards): + for i in range(ncards): c = self.app.miscrandom.choice(cards) scards.append(c) cards.remove(c) @@ -2342,9 +2342,9 @@ Congratulations, you did it ! if DEBUG: if not to_stack.acceptsCards( from_stack, from_stack.cards[-ncards:]): - print '*fail accepts cards*', from_stack, to_stack, ncards + print('*fail accepts cards*', from_stack, to_stack, ncards) if not from_stack.canMoveCards(from_stack.cards[-ncards:]): - print '*fail move cards*', from_stack, ncards + print('*fail move cards*', from_stack, ncards) ##assert from_stack.canMoveCards(from_stack.cards[-ncards:]) # FIXME: Pyramid assert to_stack.acceptsCards(from_stack, from_stack.cards[-ncards:]) if sleep <= 0.0: @@ -3027,7 +3027,7 @@ Congratulations, you did it ! try: game = self._loadGame(filename, self.app) game.gstats.holded = 0 - except AssertionError, ex: + except AssertionError as ex: self.updateMenus() self.setCursor(cursor=self.app.top_cursor) d = MfxMessageDialog(self.top, title=_("Load game error"), bitmap="error", @@ -3037,7 +3037,7 @@ Error while loading game. Probably the game file is damaged, but this could also be a bug you might want to report.""")) traceback.print_exc() - except UnpicklingError, ex: + except UnpicklingError as ex: self.updateMenus() self.setCursor(cursor=self.app.top_cursor) d = MfxExceptionDialog(self.top, ex, title=_("Load game error"), @@ -3073,7 +3073,7 @@ Please report this bug.""")) self.setCursor(cursor=CURSOR_WATCH) try: self._saveGame(filename, protocol) - except Exception, ex: + except Exception as ex: self.setCursor(cursor=self.app.top_cursor) d = MfxExceptionDialog(self.top, ex, title=_("Save game error"), text=_("Error while saving game")) @@ -3141,7 +3141,7 @@ in the current implementation.''') % version) game.version = version game.version_tuple = version_tuple # - initial_seed = pload(long) + initial_seed = pload(int) if initial_seed <= 32000: game.random = LCRandom31(initial_seed) else: diff --git a/pysollib/gamedb.py b/pysollib/gamedb.py index f2f6c1e3..1cb15c08 100644 --- a/pysollib/gamedb.py +++ b/pysollib/gamedb.py @@ -403,18 +403,18 @@ class GameInfo(Struct): # keyword arguments: si={}, category=0, short_name=None, altnames=(), - suits=range(4), ranks=range(13), trumps=(), + suits=list(range(4)), ranks=list(range(13)), trumps=(), rules_filename=None, ): # def to_unicode(s): - if isinstance(s, unicode): + if isinstance(s, str): return s try: - s = unicode(s, 'utf-8') - except UnicodeDecodeError, err: + s = str(s, 'utf-8') + except UnicodeDecodeError as err: print_err(err) - s = unicode(s, 'utf-8', 'ignore') + s = str(s, 'utf-8', 'ignore') return s ncards = decks * (len(suits) * len(ranks) + len(trumps)) game_flags = game_type & ~1023 @@ -429,7 +429,7 @@ class GameInfo(Struct): short_name = to_unicode(short_name) if pysollib.settings.TRANSLATE_GAME_NAMES: short_name = _(short_name) - if isinstance(altnames, basestring): + if isinstance(altnames, str): altnames = (altnames,) altnames = [to_unicode(n) for n in altnames] if pysollib.settings.TRANSLATE_GAME_NAMES: @@ -532,7 +532,7 @@ class GameManager: (gi.name, str(gi.gameclass), str(gameclass))) if 1: - for id, game in self.__all_games.items(): + for id, game in list(self.__all_games.items()): if gi.gameclass is game.gameclass: raise GameInfoException( "duplicate game class %s: %s and %s" % @@ -587,11 +587,11 @@ class GameManager: def getAllGames(self): ##return self.__all_games - return self.__games.values() + return list(self.__games.values()) def getGamesIdSortedById(self): if self.__games_by_id is None: - l = self.__games.keys() + l = list(self.__games.keys()) l.sort() self.__games_by_id = tuple(l) return self.__games_by_id @@ -599,7 +599,7 @@ class GameManager: def getGamesIdSortedByName(self): if self.__games_by_name is None: l1, l2, l3 = [], [], [] - for id, gi in self.__games.items(): + for id, gi in list(self.__games.items()): name = gi.name #.lower() l1.append((name, id)) if gi.name != gi.short_name: diff --git a/pysollib/games/__init__.py b/pysollib/games/__init__.py index 2c9a629c..1e1649d7 100644 --- a/pysollib/games/__init__.py +++ b/pysollib/games/__init__.py @@ -20,67 +20,67 @@ ## along with this program. If not, see . ## ##---------------------------------------------------------------------------## -import acesup -import algerian -import auldlangsyne -import bakersdozen -import bakersgame -import beleagueredcastle -import bisley -import braid -import bristol -import buffalobill -import calculation -import camelot -import canfield -import capricieuse -import curdsandwhey -import daddylonglegs -import dieboesesieben -import diplomat -import doublets -import eiffeltower -import fan -import fortythieves -import freecell -import glenwood -import golf -import grandduchess -import grandfathersclock -import gypsy -import harp -import headsandtails -import katzenschwanz -import klondike -import labyrinth -import larasgame -import matriarchy -import montana -import montecarlo -import napoleon -import needle -import numerica -import osmosis -import parallels -import pasdedeux -import picturegallery -import pileon -import pushpin -import pyramid -import royalcotillion -import royaleast -import sanibel -import siebenbisas -import simplex -import spider -import sthelena -import sultan -import takeaway -import terrace -import threepeaks -import tournament -import unionsquare -import wavemotion -import windmill -import yukon -import zodiac +from . import acesup +from . import algerian +from . import auldlangsyne +from . import bakersdozen +from . import bakersgame +from . import beleagueredcastle +from . import bisley +from . import braid +from . import bristol +from . import buffalobill +from . import calculation +from . import camelot +from . import canfield +from . import capricieuse +from . import curdsandwhey +from . import daddylonglegs +from . import dieboesesieben +from . import diplomat +from . import doublets +from . import eiffeltower +from . import fan +from . import fortythieves +from . import freecell +from . import glenwood +from . import golf +from . import grandduchess +from . import grandfathersclock +from . import gypsy +from . import harp +from . import headsandtails +from . import katzenschwanz +from . import klondike +from . import labyrinth +from . import larasgame +from . import matriarchy +from . import montana +from . import montecarlo +from . import napoleon +from . import needle +from . import numerica +from . import osmosis +from . import parallels +from . import pasdedeux +from . import picturegallery +from . import pileon +from . import pushpin +from . import pyramid +from . import royalcotillion +from . import royaleast +from . import sanibel +from . import siebenbisas +from . import simplex +from . import spider +from . import sthelena +from . import sultan +from . import takeaway +from . import terrace +from . import threepeaks +from . import tournament +from . import unionsquare +from . import wavemotion +from . import windmill +from . import yukon +from . import zodiac diff --git a/pysollib/games/acesup.py b/pysollib/games/acesup.py index 2588c81d..3e047bd3 100644 --- a/pysollib/games/acesup.py +++ b/pysollib/games/acesup.py @@ -34,7 +34,7 @@ from pysollib.game import Game from pysollib.layout import Layout from pysollib.hint import AbstractHint, DefaultHint, CautiousDefaultHint -from montecarlo import MonteCarlo_RowStack +from .montecarlo import MonteCarlo_RowStack # ************************************************************************ diff --git a/pysollib/games/auldlangsyne.py b/pysollib/games/auldlangsyne.py index fca8653f..af007eee 100644 --- a/pysollib/games/auldlangsyne.py +++ b/pysollib/games/auldlangsyne.py @@ -34,7 +34,7 @@ from pysollib.game import Game from pysollib.layout import Layout from pysollib.hint import AbstractHint, DefaultHint, CautiousDefaultHint -from numerica import Numerica_Hint +from .numerica import Numerica_Hint # ************************************************************************ diff --git a/pysollib/games/camelot.py b/pysollib/games/camelot.py index cd3906ce..e4b11364 100644 --- a/pysollib/games/camelot.py +++ b/pysollib/games/camelot.py @@ -35,7 +35,7 @@ from pysollib.layout import Layout from pysollib.hint import AbstractHint, DefaultHint, CautiousDefaultHint from pysollib.pysoltk import MfxCanvasText -from numerica import Numerica_Hint +from .numerica import Numerica_Hint # ************************************************************************ diff --git a/pysollib/games/capricieuse.py b/pysollib/games/capricieuse.py index b4ab5162..11d0201e 100644 --- a/pysollib/games/capricieuse.py +++ b/pysollib/games/capricieuse.py @@ -34,7 +34,7 @@ from pysollib.game import Game from pysollib.layout import Layout from pysollib.hint import AbstractHint, DefaultHint, CautiousDefaultHint -from gypsy import DieRussische_Foundation +from .gypsy import DieRussische_Foundation # ************************************************************************ diff --git a/pysollib/games/dieboesesieben.py b/pysollib/games/dieboesesieben.py index 62a2c6a2..bf50105b 100644 --- a/pysollib/games/dieboesesieben.py +++ b/pysollib/games/dieboesesieben.py @@ -34,7 +34,7 @@ from pysollib.game import Game from pysollib.layout import Layout from pysollib.hint import AbstractHint, DefaultHint, CautiousDefaultHint -from gypsy import DieKoenigsbergerin_Talon, DieRussische_Foundation +from .gypsy import DieKoenigsbergerin_Talon, DieRussische_Foundation # ************************************************************************ # * Die böse Sieben diff --git a/pysollib/games/diplomat.py b/pysollib/games/diplomat.py index 9261d7f1..16e80cdb 100644 --- a/pysollib/games/diplomat.py +++ b/pysollib/games/diplomat.py @@ -34,8 +34,8 @@ from pysollib.game import Game from pysollib.layout import Layout from pysollib.hint import AbstractHint, DefaultHint, CautiousDefaultHint -from fortythieves import FortyThieves_Hint -from spider import Spider_Hint +from .fortythieves import FortyThieves_Hint +from .spider import Spider_Hint # ************************************************************************ diff --git a/pysollib/games/fortythieves.py b/pysollib/games/fortythieves.py index e93b23a9..dd55bcf0 100644 --- a/pysollib/games/fortythieves.py +++ b/pysollib/games/fortythieves.py @@ -33,7 +33,7 @@ from pysollib.game import Game from pysollib.layout import Layout from pysollib.hint import AbstractHint, DefaultHint, CautiousDefaultHint -from gypsy import DieRussische_Foundation +from .gypsy import DieRussische_Foundation # ************************************************************************ diff --git a/pysollib/games/freecell.py b/pysollib/games/freecell.py index 0b72de97..e52d7047 100644 --- a/pysollib/games/freecell.py +++ b/pysollib/games/freecell.py @@ -36,7 +36,7 @@ from pysollib.layout import Layout from pysollib.hint import AbstractHint, DefaultHint, CautiousDefaultHint from pysollib.hint import FreeCellType_Hint, FreeCellSolverWrapper -from spider import Spider_AC_Foundation +from .spider import Spider_AC_Foundation # ************************************************************************ diff --git a/pysollib/games/glenwood.py b/pysollib/games/glenwood.py index 786978b1..3664416d 100644 --- a/pysollib/games/glenwood.py +++ b/pysollib/games/glenwood.py @@ -35,7 +35,7 @@ from pysollib.layout import Layout from pysollib.hint import AbstractHint, DefaultHint, CautiousDefaultHint from pysollib.pysoltk import MfxCanvasText -from canfield import Canfield_Hint +from .canfield import Canfield_Hint # ************************************************************************ # * Glenwood diff --git a/pysollib/games/golf.py b/pysollib/games/golf.py index a0d3ba83..8e220caf 100644 --- a/pysollib/games/golf.py +++ b/pysollib/games/golf.py @@ -1024,7 +1024,7 @@ class NapoleonLeavesMoscow(NapoleonTakesMoscow): # * Flake (2 decks) # ************************************************************************ -from pileon import FourByFour_Hint +from .pileon import FourByFour_Hint class Flake(Game): Hint_Class = FourByFour_Hint #CautiousDefaultHint diff --git a/pysollib/games/grandfathersclock.py b/pysollib/games/grandfathersclock.py index a3a113f1..76dd5ecc 100644 --- a/pysollib/games/grandfathersclock.py +++ b/pysollib/games/grandfathersclock.py @@ -443,7 +443,7 @@ class BigBen(Game): def _shuffleHook(self, cards): # move clock cards to top of the Talon (i.e. first cards to be dealt) - C, S, H, D = range(4) # suits + C, S, H, D = list(range(4)) # suits t = [(1,C), (2,H), (3,S), (4,D), (5,C), (6,H), (7,S), (8,D), (9,C), (JACK,H), (QUEEN,S), (KING,D)] clocks = [] diff --git a/pysollib/games/gypsy.py b/pysollib/games/gypsy.py index 9fdba1bb..bd99cdc3 100644 --- a/pysollib/games/gypsy.py +++ b/pysollib/games/gypsy.py @@ -36,7 +36,7 @@ from pysollib.layout import Layout from pysollib.hint import AbstractHint, DefaultHint, CautiousDefaultHint from pysollib.hint import KlondikeType_Hint, YukonType_Hint -from spider import Spider_SS_Foundation, Spider_RowStack, Spider_Hint +from .spider import Spider_SS_Foundation, Spider_RowStack, Spider_Hint # ************************************************************************ diff --git a/pysollib/games/harp.py b/pysollib/games/harp.py index a67cc52f..b874d7ca 100644 --- a/pysollib/games/harp.py +++ b/pysollib/games/harp.py @@ -36,7 +36,7 @@ from pysollib.layout import Layout from pysollib.hint import AbstractHint, DefaultHint, CautiousDefaultHint from pysollib.hint import KlondikeType_Hint -from spider import Spider_RowStack, Spider_SS_Foundation, Spider_Hint +from .spider import Spider_RowStack, Spider_SS_Foundation, Spider_Hint # ************************************************************************ diff --git a/pysollib/games/klondike.py b/pysollib/games/klondike.py index 3aa62f53..f10d98a5 100644 --- a/pysollib/games/klondike.py +++ b/pysollib/games/klondike.py @@ -39,7 +39,7 @@ from pysollib.hint import KlondikeType_Hint from pysollib.hint import FreeCellSolverWrapper from pysollib.pysoltk import MfxCanvasText -from canfield import CanfieldRush_Talon +from .canfield import CanfieldRush_Talon # ************************************************************************ diff --git a/pysollib/games/mahjongg/__init__.py b/pysollib/games/mahjongg/__init__.py index e4974a50..c62f1fe4 100644 --- a/pysollib/games/mahjongg/__init__.py +++ b/pysollib/games/mahjongg/__init__.py @@ -20,7 +20,7 @@ ## along with this program. If not, see . ## ##---------------------------------------------------------------------------## -import mahjongg1 -import mahjongg2 -import mahjongg3 -import shisensho +from . import mahjongg1 +from . import mahjongg2 +from . import mahjongg3 +from . import shisensho diff --git a/pysollib/games/mahjongg/mahjongg.py b/pysollib/games/mahjongg/mahjongg.py index 1a2ff010..0adcfdd4 100644 --- a/pysollib/games/mahjongg/mahjongg.py +++ b/pysollib/games/mahjongg/mahjongg.py @@ -48,7 +48,7 @@ def factorial(x): if x <= 1: return 1 a = 1 - for i in xrange(x): + for i in range(x): a *= (i+1) return a @@ -461,10 +461,10 @@ class AbstractMahjonggGame(Game): assert tilemap.get((level, tx, ty+1)) is stack assert tilemap.get((level, tx+1, ty+1)) is stack # - above = tuple(filter(None, above.keys())) - below = tuple(filter(None, below.keys())) - left = tuple(filter(None, left.keys())) - right = tuple(filter(None, right.keys())) + above = tuple([_f for _f in list(above.keys()) if _f]) + below = tuple([_f for _f in list(below.keys()) if _f]) + left = tuple([_f for _f in list(left.keys()) if _f]) + right = tuple([_f for _f in list(right.keys()) if _f]) ##up = tuple(filter(None, up.keys())) ##bottom = tuple(filter(None, bottom.keys())) @@ -584,7 +584,7 @@ class AbstractMahjonggGame(Game): c1 = cards[0] del cards[0] c2 = None - for i in xrange(len(cards)): + for i in range(len(cards)): if self.cardsMatch(c1, cards[i]): c2 = cards[i] del cards[i] @@ -599,7 +599,7 @@ class AbstractMahjonggGame(Game): # i = factorial(len(free_stacks))/2/factorial(len(free_stacks)-2) old_pairs = [] - for j in xrange(i): + for j in range(i): nc = new_cards[:] while True: # create uniq pair @@ -625,7 +625,7 @@ class AbstractMahjonggGame(Game): if new_cards: new_cards.reverse() return new_cards - print 'oops! can\'t create a solvable game' + print('oops! can\'t create a solvable game') return old_cards @@ -683,7 +683,7 @@ class AbstractMahjonggGame(Game): c1 = cards[0] del cards[0] c2 = None - for i in xrange(len(cards)): + for i in range(len(cards)): if self.cardsMatch(c1, cards[i]): c2 = cards[i] del cards[i] @@ -699,7 +699,7 @@ class AbstractMahjonggGame(Game): old_pairs = [] i = factorial(len(suitable_stacks))/2/factorial(len(suitable_stacks)-2) - for j in xrange(i): + for j in range(i): if iters[0] > max_iters: return None if time.time() - start_time > max_time: @@ -742,16 +742,16 @@ class AbstractMahjonggGame(Game): while True: ret = create_solvable(cards[:], new_cards) if DEBUG: - print 'create_solvable time:', time.time() - start_time + print('create_solvable time:', time.time() - start_time) if ret: ret.reverse() return ret if time.time() - start_time > max_time or \ iters[0] <= max_iters: - print 'oops! can\'t create a solvable game' + print('oops! can\'t create a solvable game') return None iters = [0] - print 'oops! can\'t create a solvable game' + print('oops! can\'t create a solvable game') return None def _mahjonggShuffle(self): @@ -1016,7 +1016,7 @@ def r(id, short_name, name=None, ncards=144, layout=None): gi = GameInfo(id, gameclass, name, GI.GT_MAHJONGG, 4*decks, 0, ##GI.SL_MOSTLY_SKILL, category=GI.GC_MAHJONGG, short_name=short_name, - suits=range(3), ranks=range(ranks), trumps=range(trumps), + suits=list(range(3)), ranks=list(range(ranks)), trumps=list(range(trumps)), si={"decks": decks, "ncards": ncards}) gi.ncards = ncards gi.rules_filename = "mahjongg.html" diff --git a/pysollib/games/mahjongg/mahjongg1.py b/pysollib/games/mahjongg/mahjongg1.py index f60e68d3..d46a2ba2 100644 --- a/pysollib/games/mahjongg/mahjongg1.py +++ b/pysollib/games/mahjongg/mahjongg1.py @@ -21,7 +21,7 @@ ## ##---------------------------------------------------------------------------## -from mahjongg import r +from .mahjongg import r # ************************************************************************ # * game definitions diff --git a/pysollib/games/mahjongg/mahjongg2.py b/pysollib/games/mahjongg/mahjongg2.py index dfbe00f8..5be0ec37 100644 --- a/pysollib/games/mahjongg/mahjongg2.py +++ b/pysollib/games/mahjongg/mahjongg2.py @@ -25,7 +25,7 @@ # http://www.kyodai.com/index.en.html # http://files.cyna.net/layouts.zip -from mahjongg import r +from .mahjongg import r # ************************************************************************ # * game definitions diff --git a/pysollib/games/mahjongg/mahjongg3.py b/pysollib/games/mahjongg/mahjongg3.py index bd687cd2..8baacadf 100644 --- a/pysollib/games/mahjongg/mahjongg3.py +++ b/pysollib/games/mahjongg/mahjongg3.py @@ -21,7 +21,7 @@ ## ##---------------------------------------------------------------------------## -from mahjongg import r +from .mahjongg import r # test #r(5991, "AAA 1", ncards=4, layout="0daa") diff --git a/pysollib/games/mahjongg/shisensho.py b/pysollib/games/mahjongg/shisensho.py index 85bad369..f453da6c 100644 --- a/pysollib/games/mahjongg/shisensho.py +++ b/pysollib/games/mahjongg/shisensho.py @@ -39,7 +39,7 @@ from pysollib.layout import Layout from pysollib.hint import AbstractHint, DefaultHint, CautiousDefaultHint from pysollib.pysoltk import MfxCanvasText, MfxCanvasLine -from mahjongg import Mahjongg_RowStack, AbstractMahjonggGame, comp_cardset +from .mahjongg import Mahjongg_RowStack, AbstractMahjonggGame, comp_cardset # ************************************************************************ @@ -113,7 +113,7 @@ class Shisen_RowStack(Mahjongg_RowStack): dx, dy = x2 - x1, y2 - y1 a = [] - for i in xrange(cols+2): + for i in range(cols+2): a.append([5]*(rows+2)) def can_move(x, y, nx, ny, direct, d, direct_chng_cnt): @@ -344,12 +344,12 @@ class AbstractShisenGame(AbstractMahjonggGame): self.check_dist = l.CW*l.CW + l.CH*l.CH # see _getClosestStack() # - self.cols = [[] for i in xrange(cols)] - cl = range(cols) + self.cols = [[] for i in range(cols)] + cl = list(range(cols)) if dx > 0: cl.reverse() for col in cl: - for row in xrange(rows): + for row in range(rows): x = l.XM + dxx + col * cardw y = l.YM + dyy + row * cardh stack = self.RowStack_Class(x, y, self) @@ -500,7 +500,7 @@ def r(id, gameclass, name, rules_filename="shisensho.html"): gi = GameInfo(id, gameclass, name, GI.GT_SHISEN_SHO, 4*decks, 0, GI.SL_MOSTLY_SKILL, category=GI.GC_MAHJONGG, short_name=name, - suits=range(3), ranks=range(ranks), trumps=range(trumps), + suits=list(range(3)), ranks=list(range(ranks)), trumps=list(range(trumps)), si={"decks": decks, "ncards": gameclass.NCARDS}) gi.ncards = gameclass.NCARDS gi.rules_filename = rules_filename diff --git a/pysollib/games/montecarlo.py b/pysollib/games/montecarlo.py index d8b95995..1a57522d 100644 --- a/pysollib/games/montecarlo.py +++ b/pysollib/games/montecarlo.py @@ -497,7 +497,7 @@ class Nestor(Game): if j < 0: break j += i*6 - k = self.random.choice(range((i+1)*6, 52)) + k = self.random.choice(list(range((i+1)*6, 52))) cards[j], cards[k] = cards[k], cards[j] cards.reverse() return cards diff --git a/pysollib/games/napoleon.py b/pysollib/games/napoleon.py index 541e693d..a6540fe4 100644 --- a/pysollib/games/napoleon.py +++ b/pysollib/games/napoleon.py @@ -37,7 +37,7 @@ from pysollib.layout import Layout from pysollib.hint import AbstractHint, DefaultHint, CautiousDefaultHint from pysollib.pysoltk import MfxCanvasText -from braid import Braid_Foundation +from .braid import Braid_Foundation # ************************************************************************ diff --git a/pysollib/games/pasdedeux.py b/pysollib/games/pasdedeux.py index 47728922..db3c9aa8 100644 --- a/pysollib/games/pasdedeux.py +++ b/pysollib/games/pasdedeux.py @@ -61,7 +61,7 @@ class PasDeDeux_Hint(AbstractHint): for r in rows: r1_d = self.getDistance(r, r.cards[-1]) column, row = r.id % 13, r.id / 13 - stack_ids = range(column, 52, 13) + range(13*row, 13*row+13) + stack_ids = list(range(column, 52, 13)) + list(range(13*row, 13*row+13)) for i in stack_ids: t = self.game.s.rows[i] if t is r: diff --git a/pysollib/games/picturegallery.py b/pysollib/games/picturegallery.py index 05384854..fa669e22 100644 --- a/pysollib/games/picturegallery.py +++ b/pysollib/games/picturegallery.py @@ -553,7 +553,7 @@ registerGame(GameInfo(7, PictureGallery, "Picture Gallery", altnames=("Die Bildgallerie", "Mod-3") )) registerGame(GameInfo(397, GreatWheel, "Great Wheel", GI.GT_2DECK_TYPE, 2, 0, GI.SL_BALANCED, - ranks=range(12) # without Kings + ranks=list(range(12)) # without Kings )) registerGame(GameInfo(398, MountOlympus, "Mount Olympus", GI.GT_2DECK_TYPE, 2, 0, GI.SL_BALANCED)) diff --git a/pysollib/games/royalcotillion.py b/pysollib/games/royalcotillion.py index d2d6f403..0869cf08 100644 --- a/pysollib/games/royalcotillion.py +++ b/pysollib/games/royalcotillion.py @@ -35,7 +35,7 @@ from pysollib.game import Game from pysollib.layout import Layout from pysollib.hint import AbstractHint, DefaultHint, CautiousDefaultHint -from unionsquare import UnionSquare_Foundation +from .unionsquare import UnionSquare_Foundation # ************************************************************************ @@ -1342,11 +1342,11 @@ registerGame(GameInfo(97, Carpet, "Carpet", GI.GT_1DECK_TYPE, 1, 0, GI.SL_MOSTLY_LUCK)) registerGame(GameInfo(391, BritishConstitution, "British Constitution", GI.GT_2DECK_TYPE, 2, 0, GI.SL_BALANCED, - ranks=range(11), # without Queens and Kings + ranks=list(range(11)), # without Queens and Kings altnames=("Constitution",) )) registerGame(GameInfo(392, NewBritishConstitution, "New British Constitution", GI.GT_2DECK_TYPE | GI.GT_ORIGINAL, 2, 0, GI.SL_BALANCED, - ranks=range(11) # without Queens and Kings + ranks=list(range(11)) # without Queens and Kings )) registerGame(GameInfo(443, Twenty, "Twenty", GI.GT_2DECK_TYPE, 2, 0, GI.SL_BALANCED)) diff --git a/pysollib/games/special/__init__.py b/pysollib/games/special/__init__.py index 5486a9c7..1af3e82f 100644 --- a/pysollib/games/special/__init__.py +++ b/pysollib/games/special/__init__.py @@ -20,8 +20,8 @@ ## along with this program. If not, see . ## ##---------------------------------------------------------------------------## -import hanoi -import memory -import pegged -import poker -import tarock +from . import hanoi +from . import memory +from . import pegged +from . import poker +from . import tarock diff --git a/pysollib/games/special/hanoi.py b/pysollib/games/special/hanoi.py index 8458dec3..f5f5542a 100644 --- a/pysollib/games/special/hanoi.py +++ b/pysollib/games/special/hanoi.py @@ -152,20 +152,20 @@ class HanoiSequence(TowerOfHanoy): # register the game registerGame(GameInfo(124, TowerOfHanoy, "Tower of Hanoy", GI.GT_PUZZLE_TYPE, 1, 0, GI.SL_SKILL, - suits=(2,), ranks=range(9))) + suits=(2,), ranks=list(range(9)))) registerGame(GameInfo(207, HanoiPuzzle4, "Hanoi Puzzle 4", GI.GT_PUZZLE_TYPE, 1, 0, GI.SL_SKILL, - suits=(2,), ranks=range(4), + suits=(2,), ranks=list(range(4)), rules_filename="hanoipuzzle.html")) registerGame(GameInfo(208, HanoiPuzzle5, "Hanoi Puzzle 5", GI.GT_PUZZLE_TYPE, 1, 0, GI.SL_SKILL, - suits=(2,), ranks=range(5), + suits=(2,), ranks=list(range(5)), rules_filename="hanoipuzzle.html")) registerGame(GameInfo(209, HanoiPuzzle6, "Hanoi Puzzle 6", GI.GT_PUZZLE_TYPE, 1, 0, GI.SL_SKILL, - suits=(2,), ranks=range(6), + suits=(2,), ranks=list(range(6)), rules_filename="hanoipuzzle.html")) registerGame(GameInfo(769, HanoiSequence, "Hanoi Sequence", GI.GT_PUZZLE_TYPE, 1, 0, GI.SL_SKILL, - suits=(2,), ranks=range(9))) + suits=(2,), ranks=list(range(9)))) diff --git a/pysollib/games/special/pegged.py b/pysollib/games/special/pegged.py index 0d47aa94..ce5230a1 100644 --- a/pysollib/games/special/pegged.py +++ b/pysollib/games/special/pegged.py @@ -247,7 +247,7 @@ def r(id, gameclass, name): gi = GameInfo(id, gameclass, name, GI.GT_PUZZLE_TYPE, 1, 0, GI.SL_SKILL, category=GI.GC_TRUMP_ONLY, - suits=(), ranks=(), trumps=range(ncards), + suits=(), ranks=(), trumps=list(range(ncards)), si = {"decks": 1, "ncards": ncards}, rules_filename = "pegged.html") registerGame(gi) diff --git a/pysollib/games/special/poker.py b/pysollib/games/special/poker.py index 8d248228..ed6082b1 100644 --- a/pysollib/games/special/poker.py +++ b/pysollib/games/special/poker.py @@ -140,7 +140,7 @@ One Pair''')) (r[3], r[3+5], r[3+10], r[3+15], r[3+20]), (r[4], r[4+5], r[4+10], r[4+15], r[4+20]), ] - self.poker_hands = map(tuple, self.poker_hands) + self.poker_hands = list(map(tuple, self.poker_hands)) # define stack-groups l.defaultStackGroups() diff --git a/pysollib/games/special/tarock.py b/pysollib/games/special/tarock.py index 3fd3b263..608e1fae 100644 --- a/pysollib/games/special/tarock.py +++ b/pysollib/games/special/tarock.py @@ -909,7 +909,7 @@ class Nasty(Wicked): def r(id, gameclass, name, game_type, decks, redeals, skill_level): game_type = game_type | GI.GT_TAROCK | GI.GT_CONTRIB | GI.GT_ORIGINAL gi = GameInfo(id, gameclass, name, game_type, decks, redeals, skill_level, - ranks=range(14), trumps=range(22)) + ranks=list(range(14)), trumps=list(range(22))) registerGame(gi) return gi diff --git a/pysollib/games/sultan.py b/pysollib/games/sultan.py index 242a1805..e0d60907 100644 --- a/pysollib/games/sultan.py +++ b/pysollib/games/sultan.py @@ -1035,7 +1035,7 @@ class Khedive(Game): x += l.XS x, y = l.XM+4*l.XS, l.YM - r = range(11) + r = list(range(11)) for i in range(5,0,-1): for j in r[i:-i]: x, y = l.XM+(j-0.5)*l.XS, l.YM+(5-i)*l.YS diff --git a/pysollib/games/threepeaks.py b/pysollib/games/threepeaks.py index bdd9c0b7..4eae5ddb 100644 --- a/pysollib/games/threepeaks.py +++ b/pysollib/games/threepeaks.py @@ -36,7 +36,7 @@ from pysollib.layout import Layout from pysollib.hint import AbstractHint, DefaultHint, CautiousDefaultHint from pysollib.pysoltk import MfxCanvasText -from golf import Golf_Waste, Golf_Hint +from .golf import Golf_Waste, Golf_Hint # ************************************************************************ diff --git a/pysollib/games/ultra/__init__.py b/pysollib/games/ultra/__init__.py index cac373cd..d31b9a2e 100644 --- a/pysollib/games/ultra/__init__.py +++ b/pysollib/games/ultra/__init__.py @@ -20,11 +20,11 @@ ## along with this program. If not, see . ## ##---------------------------------------------------------------------------## -import dashavatara -import hanafuda -import hanafuda1 -import hexadeck -import larasgame -import matrix -import mughal -import tarock +from . import dashavatara +from . import hanafuda +from . import hanafuda1 +from . import hexadeck +from . import larasgame +from . import matrix +from . import mughal +from . import tarock diff --git a/pysollib/games/ultra/dashavatara.py b/pysollib/games/ultra/dashavatara.py index 2ffe54b6..b9a46c9c 100644 --- a/pysollib/games/ultra/dashavatara.py +++ b/pysollib/games/ultra/dashavatara.py @@ -1267,7 +1267,7 @@ class Dashavatara(Game): def r(id, gameclass, name, game_type, decks, redeals, skill_level): game_type = game_type | GI.GT_DASHAVATARA_GANJIFA gi = GameInfo(id, gameclass, name, game_type, decks, redeals, skill_level, - suits=range(10), ranks=range(12)) + suits=list(range(10)), ranks=list(range(12))) registerGame(gi) return gi diff --git a/pysollib/games/ultra/hanafuda.py b/pysollib/games/ultra/hanafuda.py index ade6c4c9..05acda6e 100644 --- a/pysollib/games/ultra/hanafuda.py +++ b/pysollib/games/ultra/hanafuda.py @@ -37,7 +37,7 @@ from pysollib.layout import Layout from pysollib.hint import FreeCellType_Hint from pysollib.pysoltk import MfxCanvasText -from hanafuda_common import * +from .hanafuda_common import * # ************************************************************************ @@ -1025,7 +1025,7 @@ class Paulownia(AbstractFlowerGame): def r(id, gameclass, name, game_type, decks, redeals, skill_level): game_type = game_type | GI.GT_HANAFUDA gi = GameInfo(id, gameclass, name, game_type, decks, redeals, skill_level, - suits=range(12), ranks=range(4)) + suits=list(range(12)), ranks=list(range(4))) registerGame(gi) return gi diff --git a/pysollib/games/ultra/hanafuda1.py b/pysollib/games/ultra/hanafuda1.py index 7638ed06..b560bb24 100644 --- a/pysollib/games/ultra/hanafuda1.py +++ b/pysollib/games/ultra/hanafuda1.py @@ -37,7 +37,7 @@ from pysollib.layout import Layout from pysollib.hint import AbstractHint, DefaultHint, CautiousDefaultHint from pysollib.pysoltk import MfxCanvasText -from hanafuda_common import * +from .hanafuda_common import * # ************************************************************************ # * Paulownia @@ -590,7 +590,7 @@ class FlowerArrangement_TableauStack(Flower_OpenStack): if not self.basicAcceptsCards(from_stack, cards): return 0 # check that the base card is correct - suits = range(self.cap.mod, (self.cap.mod + 4)) + suits = list(range(self.cap.mod, (self.cap.mod + 4))) if self.cards and (self.cards[0].rank == 3 and self.cards[-1].suit in suits): return self.isHanafudaSequence([self.cards[-1], cards[0]]) @@ -693,7 +693,7 @@ class FlowerArrangement(Game): def r(id, gameclass, name, game_type, decks, redeals, skill_level): game_type = game_type | GI.GT_HANAFUDA gi = GameInfo(id, gameclass, name, game_type, decks, redeals, skill_level, - suits=range(12), ranks=range(4)) + suits=list(range(12)), ranks=list(range(4))) registerGame(gi) return gi diff --git a/pysollib/games/ultra/hexadeck.py b/pysollib/games/ultra/hexadeck.py index 1dede9c1..b889327d 100644 --- a/pysollib/games/ultra/hexadeck.py +++ b/pysollib/games/ultra/hexadeck.py @@ -1379,7 +1379,7 @@ class Snakestone(Convolution): def r(id, gameclass, name, game_type, decks, redeals, skill_level): game_type = game_type | GI.GT_HEXADECK gi = GameInfo(id, gameclass, name, game_type, decks, redeals, skill_level, - suits=range(4), ranks=range(16), trumps=range(4)) + suits=list(range(4)), ranks=list(range(16)), trumps=list(range(4))) registerGame(gi) return gi diff --git a/pysollib/games/ultra/larasgame.py b/pysollib/games/ultra/larasgame.py index dc99bca0..348e23a4 100644 --- a/pysollib/games/ultra/larasgame.py +++ b/pysollib/games/ultra/larasgame.py @@ -284,37 +284,37 @@ class DoubleDojoujisGame(DojoujisGame): # register the game registerGame(GameInfo(13001, KatrinasGame, "Katrina's Game", GI.GT_TAROCK, 2, 1, GI.SL_BALANCED, - ranks = range(14), trumps = range(22))) + ranks = list(range(14)), trumps = list(range(22)))) registerGame(GameInfo(13002, BridgetsGame, "Bridget's Game", GI.GT_HEXADECK, 2, 1, GI.SL_BALANCED, - ranks = range(16), trumps = range(4))) + ranks = list(range(16)), trumps = list(range(4)))) registerGame(GameInfo(13003, FatimehsGame, "Fatimeh's Game", GI.GT_MUGHAL_GANJIFA, 1, 2, GI.SL_BALANCED, - suits = range(8), ranks = range(12))) + suits = list(range(8)), ranks = list(range(12)))) registerGame(GameInfo(13004, KalisGame, "Kali's Game", GI.GT_DASHAVATARA_GANJIFA, 1, 2, GI.SL_BALANCED, - suits = range(10), ranks = range(12))) + suits = list(range(10)), ranks = list(range(12)))) registerGame(GameInfo(13005, DojoujisGame, "Dojouji's Game", GI.GT_HANAFUDA, 2, 0, GI.SL_BALANCED, - suits = range(12), ranks = range(4))) + suits = list(range(12)), ranks = list(range(4)))) registerGame(GameInfo(13008, RelaxedKatrinasGame, "Katrina's Game Relaxed", GI.GT_TAROCK, 2, 1, GI.SL_BALANCED, - ranks = range(14), trumps = range(22))) + ranks = list(range(14)), trumps = list(range(22)))) registerGame(GameInfo(13009, DoubleKatrinasGame, "Katrina's Game Doubled", GI.GT_TAROCK, 4, 2, GI.SL_BALANCED, - ranks = range(14), trumps = range(22))) + ranks = list(range(14)), trumps = list(range(22)))) registerGame(GameInfo(13010, DoubleBridgetsGame, "Bridget's Game Doubled", GI.GT_HEXADECK, 4, 2, GI.SL_BALANCED, - ranks = range(16), trumps = range(4))) + ranks = list(range(16)), trumps = list(range(4)))) registerGame(GameInfo(13011, RelaxedKalisGame, "Kali's Game Relaxed", GI.GT_DASHAVATARA_GANJIFA, 1, 2, GI.SL_BALANCED, - suits = range(10), ranks = range(12))) + suits = list(range(10)), ranks = list(range(12)))) registerGame(GameInfo(13012, DoubleKalisGame, "Kali's Game Doubled", GI.GT_DASHAVATARA_GANJIFA, 2, 3, GI.SL_BALANCED, - suits = range(10), ranks = range(12))) + suits = list(range(10)), ranks = list(range(12)))) registerGame(GameInfo(13013, RelaxedFatimehsGame, "Fatimeh's Game Relaxed", GI.GT_MUGHAL_GANJIFA, 1, 2, GI.SL_BALANCED, - suits = range(8), ranks = range(12))) + suits = list(range(8)), ranks = list(range(12)))) registerGame(GameInfo(13014, DoubleDojoujisGame, "Dojouji's Game Doubled", GI.GT_HANAFUDA, 4, 0, GI.SL_BALANCED, - suits = range(12), ranks = range(4))) + suits = list(range(12)), ranks = list(range(4)))) diff --git a/pysollib/games/ultra/matrix.py b/pysollib/games/ultra/matrix.py index cba686c7..0fa79704 100644 --- a/pysollib/games/ultra/matrix.py +++ b/pysollib/games/ultra/matrix.py @@ -239,7 +239,7 @@ def r(id, gameclass, short_name): gi = GameInfo(id, gameclass, name, GI.GT_MATRIX, 1, 0, GI.SL_SKILL, category=GI.GC_TRUMP_ONLY, short_name=short_name, - suits=(), ranks=(), trumps=range(ncards), + suits=(), ranks=(), trumps=list(range(ncards)), si = {"decks": 1, "ncards": ncards}) gi.ncards = ncards gi.rules_filename = "matrix.html" diff --git a/pysollib/games/ultra/mughal.py b/pysollib/games/ultra/mughal.py index b9c1ac5e..61e695aa 100644 --- a/pysollib/games/ultra/mughal.py +++ b/pysollib/games/ultra/mughal.py @@ -1146,7 +1146,7 @@ class AshtaDikapala(Game): def r(id, gameclass, name, game_type, decks, redeals, skill_level): game_type = game_type | GI.GT_MUGHAL_GANJIFA gi = GameInfo(id, gameclass, name, game_type, decks, redeals, skill_level, - suits=range(8), ranks=range(12)) + suits=list(range(8)), ranks=list(range(12))) registerGame(gi) return gi diff --git a/pysollib/games/ultra/tarock.py b/pysollib/games/ultra/tarock.py index c677f8f1..7ae7e3e7 100644 --- a/pysollib/games/ultra/tarock.py +++ b/pysollib/games/ultra/tarock.py @@ -267,7 +267,7 @@ class LeGrandeTeton(ThreePeaksNoScore): def r(id, gameclass, name, game_type, decks, redeals, skill_level): game_type = game_type | GI.GT_TAROCK | GI.GT_CONTRIB | GI.GT_ORIGINAL gi = GameInfo(id, gameclass, name, game_type, decks, redeals, skill_level, - ranks=range(14), trumps=range(22)) + ranks=list(range(14)), trumps=list(range(22))) registerGame(gi) return gi diff --git a/pysollib/games/windmill.py b/pysollib/games/windmill.py index 434c28be..11922364 100644 --- a/pysollib/games/windmill.py +++ b/pysollib/games/windmill.py @@ -34,7 +34,7 @@ from pysollib.game import Game from pysollib.layout import Layout from pysollib.hint import AbstractHint, DefaultHint, CautiousDefaultHint -from golf import BlackHole_Foundation +from .golf import BlackHole_Foundation # ************************************************************************ diff --git a/pysollib/games/yukon.py b/pysollib/games/yukon.py index c2dff463..f805bd45 100644 --- a/pysollib/games/yukon.py +++ b/pysollib/games/yukon.py @@ -39,7 +39,7 @@ from pysollib.hint import YukonType_Hint from pysollib.hint import FreeCellSolverWrapper from pysollib.pysoltk import MfxCanvasText -from spider import Spider_SS_Foundation +from .spider import Spider_SS_Foundation # ************************************************************************ diff --git a/pysollib/hint.py b/pysollib/hint.py index b5f6d1e7..19f74b86 100644 --- a/pysollib/hint.py +++ b/pysollib/hint.py @@ -828,7 +828,7 @@ class FreeCellSolver_Hint(Base_Solver_Hint): board = board + b.strip() + '\n' # if DEBUG: - print '--------------------\n', board, '--------------------' + print('--------------------\n', board, '--------------------') # args = [] ##args += ['-sam', '-p', '-opt', '--display-10-as-t'] @@ -857,7 +857,7 @@ class FreeCellSolver_Hint(Base_Solver_Hint): command = FCS_COMMAND+' '+' '.join([str(i) for i in args]) if DEBUG: - print command + print(command) kw = {'shell': True, 'stdin': subprocess.PIPE, 'stdout': subprocess.PIPE, @@ -884,7 +884,7 @@ class FreeCellSolver_Hint(Base_Solver_Hint): for s in pout: if DEBUG >= 5: - print s, + print(s, end=' ') if self.colonPrefixMatch('Iteration', s): iter = self._v @@ -904,7 +904,7 @@ class FreeCellSolver_Hint(Base_Solver_Hint): hints = [] for s in pout: if DEBUG: - print s, + print(s, end=' ') if self._determineIfSolverState(s): next m = re.match('Total number of states checked is (\d+)\.', s) @@ -963,7 +963,7 @@ class FreeCellSolver_Hint(Base_Solver_Hint): # if DEBUG: - print 'time:', time.time()-start_time + print('time:', time.time()-start_time) ##print perr.read(), self.hints = hints @@ -1004,7 +1004,7 @@ class BlackHoleSolver_Hint(Base_Solver_Hint): board += b.strip() + '\n' # if DEBUG: - print '--------------------\n', board, '--------------------' + print('--------------------\n', board, '--------------------') # args = [] ##args += ['-sam', '-p', '-opt', '--display-10-as-t'] @@ -1014,7 +1014,7 @@ class BlackHoleSolver_Hint(Base_Solver_Hint): command = self.BLACK_HOLE_SOLVER_COMMAND+' '+' '.join([str(i) for i in args]) if DEBUG: - print command + print(command) kw = {'shell': True, 'stdin': subprocess.PIPE, 'stdout': subprocess.PIPE, @@ -1037,7 +1037,7 @@ class BlackHoleSolver_Hint(Base_Solver_Hint): for s in pout: if DEBUG >= 5: - print s, + print(s, end=' ') m = re.search('^(Intractable!|Unsolved!|Solved!)\n', s) if m: @@ -1057,7 +1057,7 @@ class BlackHoleSolver_Hint(Base_Solver_Hint): hints = [] for s in pout: if DEBUG: - print s, + print(s, end=' ') m = re.match('Total number of states checked is (\d+)\.', s) if m: iter = int(m.group(1)) @@ -1087,7 +1087,7 @@ class BlackHoleSolver_Hint(Base_Solver_Hint): # if DEBUG: - print 'time:', time.time()-start_time + print('time:', time.time()-start_time) ##print perr.read(), self.hints = hints diff --git a/pysollib/images.py b/pysollib/images.py index c47de503..b3f3d35a 100644 --- a/pysollib/images.py +++ b/pysollib/images.py @@ -424,7 +424,7 @@ class Images: self._pil_shadow = {} def reset(self): - print 'Image.reset' + print('Image.reset') self.resize(1, 1) diff --git a/pysollib/init.py b/pysollib/init.py index fa0318cb..b76bc88a 100644 --- a/pysollib/init.py +++ b/pysollib/init.py @@ -61,13 +61,13 @@ def init(): ## debug if 'PYSOL_CHECK_GAMES' in os.environ or 'PYSOL_DEBUG' in os.environ: pysollib.settings.CHECK_GAMES = True - print 'PySol debugging: set CHECK_GAMES to True' + print('PySol debugging: set CHECK_GAMES to True') if 'PYSOL_DEBUG' in os.environ: try: pysollib.settings.DEBUG = int(os.environ['PYSOL_DEBUG']) except: pysollib.settings.DEBUG = 1 - print 'PySol debugging: set DEBUG to', pysollib.settings.DEBUG + print('PySol debugging: set DEBUG to', pysollib.settings.DEBUG) ## init toolkit if '--gtk' in sys.argv: @@ -82,13 +82,13 @@ def init(): pysollib.settings.USE_TILE = True sys.argv.remove('--tile') if pysollib.settings.TOOLKIT == 'tk': - import Tkinter - root = Tkinter.Tk(className=pysollib.settings.TITLE) + import tkinter + root = tkinter.Tk(className=pysollib.settings.TITLE) root.withdraw() - if Tkinter.TkVersion < 8.4: + if tkinter.TkVersion < 8.4: # we need unicode support sys.exit("%s needs Tcl/Tk 8.4 or better (you have %s)" % - (pysollib.settings.TITLE, str(Tkinter.TkVersion))) + (pysollib.settings.TITLE, str(tkinter.TkVersion))) pysollib.settings.WIN_SYSTEM = root.tk.call('tk', 'windowingsystem') if pysollib.settings.WIN_SYSTEM == 'aqua': # TkAqua displays the console automatically in application @@ -101,13 +101,13 @@ def init(): pysollib.settings.USE_TILE = False try: root.tk.eval('package require tile 0.7.8') - except Tkinter.TclError: + except tkinter.TclError: pass else: pysollib.settings.USE_TILE = True # "can't invoke event <>: application has been destroyed" #root.destroy() - Tkinter._default_root = None + tkinter._default_root = None # check FreeCell-Solver pysollib.settings.USE_FREECELL_SOLVER = False diff --git a/pysollib/macosx/appSupport.py b/pysollib/macosx/appSupport.py index 0e157a8d..7a6acdd7 100644 --- a/pysollib/macosx/appSupport.py +++ b/pysollib/macosx/appSupport.py @@ -25,7 +25,7 @@ A number of function that enhance PySol on MacOSX when it used as a normal GUI application (as opposed to an X11 application). """ import sys -from Tkinter import Menu, Text, TclError +from tkinter import Menu, Text, TclError def runningAsOSXApp(): """ Returns True iff running from the PySol.app bundle on OSX """ diff --git a/pysollib/main.py b/pysollib/main.py index 0e7b9192..a99e17cb 100644 --- a/pysollib/main.py +++ b/pysollib/main.py @@ -77,7 +77,7 @@ def parse_option(argv): "nosound", "sound-mod=", "help"]) - except getopt.GetoptError, err: + except getopt.GetoptError as err: print_err(_("%s\ntry %s --help for more information") % (err, prog_name), 0) return None @@ -107,7 +107,7 @@ def parse_option(argv): opts["sound-mod"] = i[1] if opts["help"]: - print _("""Usage: %s [OPTIONS] [FILE] + print(_("""Usage: %s [OPTIONS] [FILE] -g --game=GAMENAME start game GAMENAME -i --gameid=GAMEID --french-only @@ -118,7 +118,7 @@ def parse_option(argv): FILE - file name of a saved game MOD - one of following: pss(default), pygame, oss, win -""") % prog_name +""") % prog_name) return None if len(args) > 1: diff --git a/pysollib/mfxutil.py b/pysollib/mfxutil.py index 8652f25b..c2870498 100644 --- a/pysollib/mfxutil.py +++ b/pysollib/mfxutil.py @@ -27,12 +27,12 @@ import sys, os, time, types, locale import webbrowser try: - from cPickle import Pickler, Unpickler, UnpicklingError + from pickle import Pickler, Unpickler, UnpicklingError except ImportError: from pickle import Pickler, Unpickler, UnpicklingError try: - import thread + import _thread except: thread = None @@ -102,7 +102,7 @@ def print_err(s, level=1): ss = PACKAGE+': WARNING:' elif level == 2: ss = PACKAGE+': DEBUG WARNING:' - print >> sys.stderr, ss, s.encode(locale.getpreferredencoding()) + print(ss, s.encode(locale.getpreferredencoding()), file=sys.stderr) sys.stderr.flush() @@ -141,7 +141,7 @@ if os.name == "posix": def win32_getusername(): user = os.environ.get('USERNAME','').strip() try: - user = unicode(user, locale.getpreferredencoding()) + user = str(user, locale.getpreferredencoding()) except: user = '' return user @@ -169,7 +169,7 @@ def destruct(obj): # assist in breaking circular references if obj is not None: assert isinstance(obj, types.InstanceType) - for k in obj.__dict__.keys(): + for k in list(obj.__dict__.keys()): obj.__dict__[k] = None ##del obj.__dict__[k] @@ -191,19 +191,19 @@ class Struct: self.__dict__[key] = value def addattr(self, **kw): - for key in kw.keys(): + for key in list(kw.keys()): if hasattr(self, key): raise AttributeError(key) self.__dict__.update(kw) def update(self, dict): - for key in dict.keys(): + for key in list(dict.keys()): if key not in self.__dict__: raise AttributeError(key) self.__dict__.update(dict) def clear(self): - for key in self.__dict__.keys(): + for key in list(self.__dict__.keys()): if isinstance(key, list): self.__dict__[key] = [] elif isinstance(key, tuple): @@ -225,7 +225,7 @@ class Struct: # update keyword arguments with default arguments def kwdefault(kw, **defaults): - for k, v in defaults.items(): + for k, v in list(defaults.items()): if k not in kw: kw[k] = v @@ -238,7 +238,7 @@ class KwStruct: defaults = defaults.__dict__ if defaults: kw = kw.copy() - for k, v in defaults.items(): + for k, v in list(defaults.items()): if k not in kw: kw[k] = v self.__dict__.update(kw) diff --git a/pysollib/mygettext.py b/pysollib/mygettext.py index 0b51a7c5..efe5ad8a 100644 --- a/pysollib/mygettext.py +++ b/pysollib/mygettext.py @@ -9,8 +9,8 @@ def n_(x): def fix_gettext(): def ugettext(message): # unicoded gettext - if not isinstance(message, unicode): - message = unicode(message, 'utf-8') + if not isinstance(message, str): + message = str(message, 'utf-8') domain = gettext._current_domain try: t = gettext.translation(domain, @@ -21,10 +21,10 @@ def fix_gettext(): gettext.ugettext = ugettext def ungettext(msgid1, msgid2, n): # unicoded ngettext - if not isinstance(msgid1, unicode): - msgid1 = unicode(msgid1, 'utf-8') - if not isinstance(msgid2, unicode): - msgid2 = unicode(msgid2, 'utf-8') + if not isinstance(msgid1, str): + msgid1 = str(msgid1, 'utf-8') + if not isinstance(msgid2, str): + msgid2 = str(msgid2, 'utf-8') domain = gettext._current_domain try: t = gettext.translation(domain, diff --git a/pysollib/options.py b/pysollib/options.py index e1b725c6..721d4b37 100644 --- a/pysollib/options.py +++ b/pysollib/options.py @@ -479,7 +479,7 @@ class Options: for key, t in self.GENERAL_OPTIONS: val = getattr(self, key) if isinstance(val, str): - val = unicode(val, 'utf-8') + val = str(val, 'utf-8') config['general'][key] = val config['general']['recent_gameid'] = self.recent_gameid @@ -493,7 +493,7 @@ class Options: config['sound_samples'] = self.sound_samples # fonts - for key, val in self.fonts.items(): + for key, val in list(self.fonts.items()): if key == 'default': continue if val is None: @@ -507,7 +507,7 @@ class Options: config['timeouts'] = self.timeouts # cardsets - for key, val in self.cardset.items(): + for key, val in list(self.cardset.items()): config['cardsets'][str(key)] = val for key in ('scale_cards', 'scale_x', 'scale_y', 'auto_scale', 'preserve_aspect_ratio'): @@ -515,12 +515,12 @@ class Options: # games_geometry config['games_geometry'].clear() - for key, val in self.games_geometry.items(): + for key, val in list(self.games_geometry.items()): config['games_geometry'][str(key)] = val config['general']['game_geometry'] = self.game_geometry # offsets - for key, val in self.offsets.items(): + for key, val in list(self.offsets.items()): config['offsets'][key] = val config.write() @@ -590,10 +590,10 @@ class Options: res = config.validate(vdt) ##from pprint import pprint; pprint(res) if res is not True: - for section, data in res.items(): + for section, data in list(res.items()): if data is True: continue - for key, value in data.items(): + for key, value in list(data.items()): if value is False: print_err('config file: validation error: ' 'section: "%s", key: "%s"' % (section, key)) @@ -686,7 +686,7 @@ class Options: setattr(self, key, val) # games_geometry - for key, val in config['games_geometry'].items(): + for key, val in list(config['games_geometry'].items()): try: val = [int(i) for i in val] assert len(val) == 2 @@ -701,7 +701,7 @@ class Options: traceback.print_exc() # cards offsets - for key, val in config['offsets'].items(): + for key, val in list(config['offsets'].items()): try: val = [int(i) for i in val] assert len(val) == 2 diff --git a/pysollib/pysolaudio.py b/pysollib/pysolaudio.py index 2a83332b..ce2babfb 100644 --- a/pysollib/pysolaudio.py +++ b/pysollib/pysolaudio.py @@ -27,7 +27,7 @@ import os import traceback try: - import thread + import _thread from threading import Thread except ImportError: thread = None diff --git a/pysollib/pysolgtk/card.py b/pysollib/pysolgtk/card.py index 53cd87fa..002ca1bc 100644 --- a/pysollib/pysolgtk/card.py +++ b/pysollib/pysolgtk/card.py @@ -29,7 +29,7 @@ import gtk from pysollib.acard import AbstractCard # Toolkit imports -from tkcanvas import MfxCanvasGroup, MfxCanvasImage +from .tkcanvas import MfxCanvasGroup, MfxCanvasImage # ************************************************************************ diff --git a/pysollib/pysolgtk/edittextdialog.py b/pysollib/pysolgtk/edittextdialog.py index e64ce29f..ca305cf7 100644 --- a/pysollib/pysolgtk/edittextdialog.py +++ b/pysollib/pysolgtk/edittextdialog.py @@ -29,7 +29,7 @@ __all__ = ['EditTextDialog'] # PySol imports # Toolkit imports -from tkwidget import MfxDialog +from .tkwidget import MfxDialog # ************************************************************************ # * diff --git a/pysollib/pysolgtk/fontsdialog.py b/pysollib/pysolgtk/fontsdialog.py index e26291d5..506d7a7d 100644 --- a/pysollib/pysolgtk/fontsdialog.py +++ b/pysollib/pysolgtk/fontsdialog.py @@ -31,7 +31,7 @@ import gtk.glade # PySol imports from pysollib.mygettext import _, n_ -from tkutil import create_pango_font_desc +from .tkutil import create_pango_font_desc # ************************************************************************ diff --git a/pysollib/pysolgtk/gameinfodialog.py b/pysollib/pysolgtk/gameinfodialog.py index 20a5c36f..f52847c2 100644 --- a/pysollib/pysolgtk/gameinfodialog.py +++ b/pysollib/pysolgtk/gameinfodialog.py @@ -33,7 +33,7 @@ __all__ = ['GameInfoDialog'] ## from pysollib.gamedb import GI # Toolkit imports -from tkwidget import MfxDialog +from .tkwidget import MfxDialog # ************************************************************************ # * diff --git a/pysollib/pysolgtk/menubar.py b/pysollib/pysolgtk/menubar.py index 338ef075..f03ed5c0 100644 --- a/pysollib/pysolgtk/menubar.py +++ b/pysollib/pysolgtk/menubar.py @@ -34,13 +34,13 @@ from pysollib.gamedb import GI from pysollib.settings import TITLE # toolkit imports -from tkutil import setTransient -from tkutil import color_tk2gtk, color_gtk2tk -from soundoptionsdialog import SoundOptionsDialog -from selectcardset import SelectCardsetDialogWithPreview -from selecttile import SelectTileDialogWithPreview -from selectgame import SelectGameDialogWithPreview -from findcarddialog import connect_game_find_card_dialog, destroy_find_card_dialog +from .tkutil import setTransient +from .tkutil import color_tk2gtk, color_gtk2tk +from .soundoptionsdialog import SoundOptionsDialog +from .selectcardset import SelectCardsetDialogWithPreview +from .selecttile import SelectTileDialogWithPreview +from .selectgame import SelectGameDialogWithPreview +from .findcarddialog import connect_game_find_card_dialog, destroy_find_card_dialog def ltk2gtk(s): # label tk to gtk @@ -456,7 +456,7 @@ class PysolMenubarTk: #ui_manager.get_widget('/menubar/file/recentgames').show() #ui_manager.get_widget('/menubar/file/favoritegames').show() - games = map(self.app.gdb.get, self.app.gdb.getGamesIdSortedByName()) + games = list(map(self.app.gdb.get, self.app.gdb.getGamesIdSortedByName())) menu = ui_manager.get_widget('/menubar/select').get_submenu() self._createSelectMenu(games, menu) @@ -475,7 +475,7 @@ class PysolMenubarTk: def _getNumGames(self, games, select_data): ngames = 0 for label, select_func in select_data: - ngames += len(filter(select_func, games)) + ngames += len(list(filter(select_func, games))) return ngames def _createSubMenu(self, menu, label): @@ -520,7 +520,7 @@ class PysolMenubarTk: def _addSelectedGamesSubMenu(self, games, menu, select_data): for label, select_func in select_data: - g = filter(select_func, games) + g = list(filter(select_func, games)) if not g: continue submenu = self._createSubMenu(menu, label=label) @@ -528,7 +528,7 @@ class PysolMenubarTk: def _addPopularGamesMenu(self, games, menu): select_func = lambda gi: gi.si.game_flags & GI.GT_POPULAR - if len(filter(select_func, games)) == 0: + if len(list(filter(select_func, games))) == 0: return data = (ltk2gtk('&Popular games'), select_func) self._addSelectedGamesSubMenu(games, menu, (data, )) @@ -541,7 +541,7 @@ class PysolMenubarTk: def _addMahjonggGamesMenu(self, games, menu): select_func = lambda gi: gi.si.game_type == GI.GT_MAHJONGG - mahjongg_games = filter(select_func, games) + mahjongg_games = list(filter(select_func, games)) if len(mahjongg_games) == 0: return menu = self._createSubMenu(menu, label=ltk2gtk('&Mahjongg games')) @@ -562,7 +562,7 @@ class PysolMenubarTk: games[c].append(gi) else: games[c] = [gi] - games = games.items() + games = list(games.items()) games.sort() # g0 = [] @@ -618,7 +618,7 @@ class PysolMenubarTk: path = '/toolbar/'+path button = self.top.ui_manager.get_widget(path) if not button: - print 'WARNING: setToolbarState: not found:', path + print('WARNING: setToolbarState: not found:', path) else: button.set_sensitive(state) diff --git a/pysollib/pysolgtk/playeroptionsdialog.py b/pysollib/pysolgtk/playeroptionsdialog.py index 371f0292..b49e0688 100644 --- a/pysollib/pysolgtk/playeroptionsdialog.py +++ b/pysollib/pysolgtk/playeroptionsdialog.py @@ -30,7 +30,7 @@ import gobject, gtk from pysollib.mygettext import _, n_ # Toolkit imports -from tkwidget import MfxDialog +from .tkwidget import MfxDialog from pysollib.mfxutil import kwdefault diff --git a/pysollib/pysolgtk/progressbar.py b/pysollib/pysolgtk/progressbar.py index e151ec3f..4066978b 100644 --- a/pysollib/pysolgtk/progressbar.py +++ b/pysollib/pysolgtk/progressbar.py @@ -29,7 +29,7 @@ import gtk from gtk import gdk # Toolkit imports -from tkutil import makeToplevel, setTransient +from .tkutil import makeToplevel, setTransient # ************************************************************************ @@ -159,7 +159,7 @@ def progressbar_main(args): root.connect("delete_event", mainquit) images = None if 1: - from tkwrap import loadImage + from .tkwrap import loadImage im = loadImage(os.path.join(os.pardir, os.pardir, 'data', 'images', 'jokers', 'joker07_40_774.gif')) images = (im, im) pb = TestProgressBar(root, images=images) diff --git a/pysollib/pysolgtk/selectcardset.py b/pysollib/pysolgtk/selectcardset.py index e511b112..6679b593 100644 --- a/pysollib/pysolgtk/selectcardset.py +++ b/pysollib/pysolgtk/selectcardset.py @@ -32,10 +32,10 @@ from pysollib.resource import CSI from pysollib.mfxutil import kwdefault # Toolkit imports -from tkwidget import MfxDialog -from pysoltree import PysolTreeView -from tkcanvas import MfxCanvas, MfxCanvasImage -from tkutil import loadImage +from .tkwidget import MfxDialog +from .pysoltree import PysolTreeView +from .tkcanvas import MfxCanvas, MfxCanvasImage +from .tkutil import loadImage # ************************************************************************ @@ -118,7 +118,7 @@ class SelectCardsetDialogWithPreview(MfxDialog): manager = self.manager root_iter = store.append(None) store.set(root_iter, 0, root_label, 1, -1) - items = cardset_types.items() + items = list(cardset_types.items()) items.sort(lambda a, b: cmp(a[1], b[1])) added = False for key, label in items: diff --git a/pysollib/pysolgtk/selectgame.py b/pysollib/pysolgtk/selectgame.py index 5539d757..5192a507 100644 --- a/pysollib/pysolgtk/selectgame.py +++ b/pysollib/pysolgtk/selectgame.py @@ -38,10 +38,10 @@ from pysollib.help import help_html from pysollib.resource import CSI # Toolkit imports -from tkutil import unbind_destroy -from tkwidget import MfxDialog -from tkcanvas import MfxCanvas, MfxCanvasText -from pysoltree import PysolTreeView +from .tkutil import unbind_destroy +from .tkwidget import MfxDialog +from .tkcanvas import MfxCanvas, MfxCanvasText +from .pysoltree import PysolTreeView # ************************************************************************ @@ -211,7 +211,7 @@ class SelectGameDialogWithPreview(MfxDialog): app = self.app gdb = app.gdb - all_games = map(gdb.get, gdb.getGamesIdSortedByName()) + all_games = list(map(gdb.get, gdb.getGamesIdSortedByName())) # alter_games = gdb.getGamesTuplesSortedByAlternateName() for label, games, selecter in ( @@ -507,7 +507,7 @@ class SelectGameDialogWithPreview(MfxDialog): def done(self, button): button = button.get_data("user_data") - print 'done', button + print('done', button) if button == 0: # Ok or double click id = self.getSelected() if id: diff --git a/pysollib/pysolgtk/selecttile.py b/pysollib/pysolgtk/selecttile.py index c8281e07..5de988e6 100644 --- a/pysollib/pysolgtk/selecttile.py +++ b/pysollib/pysolgtk/selecttile.py @@ -36,10 +36,10 @@ from pysollib.mfxutil import kwdefault # Toolkit imports ## from tkutil import loadImage -from tkwidget import MfxDialog -from tkcanvas import MfxCanvas -from tkutil import setTransient -from pysoltree import PysolTreeView +from .tkwidget import MfxDialog +from .tkcanvas import MfxCanvas +from .tkutil import setTransient +from .pysoltree import PysolTreeView class SelectTileDialogWithPreview(MfxDialog): @@ -85,7 +85,7 @@ class SelectTileDialogWithPreview(MfxDialog): def rowActivated(self, w, row, col): # FIXME - print 'row-activated-event', row, col + print('row-activated-event', row, col) def getSelected(self): diff --git a/pysollib/pysolgtk/soundoptionsdialog.py b/pysollib/pysolgtk/soundoptionsdialog.py index 8437ce77..1648ce82 100644 --- a/pysollib/pysolgtk/soundoptionsdialog.py +++ b/pysollib/pysolgtk/soundoptionsdialog.py @@ -31,7 +31,7 @@ from gtk import glade from pysollib.mygettext import _, n_ # Toolkit imports -from tkwidget import MfxDialog +from .tkwidget import MfxDialog # ************************************************************************ diff --git a/pysollib/pysolgtk/statusbar.py b/pysollib/pysolgtk/statusbar.py index 5c4ffa22..300592f1 100644 --- a/pysollib/pysolgtk/statusbar.py +++ b/pysollib/pysolgtk/statusbar.py @@ -65,10 +65,10 @@ class BasicStatusbar: def updateText(self, **kw): - for k, v in kw.items(): + for k, v in list(kw.items()): label = getattr(self, k + "_label") label.pop(0) - label.push(0, unicode(v)) + label.push(0, str(v)) def config(self, name, show): # FIXME @@ -78,7 +78,7 @@ class BasicStatusbar: label = getattr(self, name + "_label") # FIXME kw['fg'] label.pop(0) - label.push(0, unicode(kw['text'])) + label.push(0, str(kw['text'])) def show(self, show=True, resize=False): diff --git a/pysollib/pysolgtk/tkcanvas.py b/pysollib/pysolgtk/tkcanvas.py index f79833ae..f5337298 100644 --- a/pysollib/pysolgtk/tkcanvas.py +++ b/pysollib/pysolgtk/tkcanvas.py @@ -51,7 +51,7 @@ except ImportError: import gnome.canvas as gnomecanvas # toolkit imports -from tkutil import anchor_tk2gtk, loadImage, bind, create_pango_font_desc +from .tkutil import anchor_tk2gtk, loadImage, bind, create_pango_font_desc # ************************************************************************ @@ -78,7 +78,7 @@ class _CanvasItem: ##~ assert isinstance(group._item, CanvasGroup) self._item.reparent(group._item) if self._group == group: - print 'addtag: new_group == old_group' + print('addtag: new_group == old_group') self._group = group def dtag(self, group): @@ -100,7 +100,7 @@ class _CanvasItem: self._item = None def lower(self, positions=None): - print 'lower', self, positions + print('lower', self, positions) return # don't need? ## if positions is None: ## pass @@ -241,7 +241,7 @@ class MfxCanvasText(_CanvasItem): x=x, y=y, anchor=anchor) if 'fill' not in kw: kw['fill'] = canvas._text_color - for k, v in kw.items(): + for k, v in list(kw.items()): self[k] = v ##~ self.text_format = None canvas._text_items.append(self) @@ -257,17 +257,17 @@ class MfxCanvasText(_CanvasItem): elif key == 'text': self._item.set(text=value) else: - raise AttributeError, key + raise AttributeError(key) def config(self, **kw): - for k, v in kw.items(): + for k, v in list(kw.items()): self[k] = v def __getitem__(self, key): if key == 'text': return self._item.get_property('text') else: - raise AttributeError, key + raise AttributeError(key) cget = __getitem__ @@ -322,7 +322,7 @@ class MfxCanvas(gnomecanvas.Canvas): def bind(self, sequence=None, func=None, add=None): assert add is None # FIXME - print 'TkCanvas bind:', sequence + print('TkCanvas bind:', sequence) return def cget(self, attr): @@ -334,8 +334,8 @@ class MfxCanvas(gnomecanvas.Canvas): return self.get_size()[0] elif attr == 'height': return self.get_size()[1] - print 'TkCanvas cget:', attr - raise AttributeError, attr + print('TkCanvas cget:', attr) + raise AttributeError(attr) def xview(self): w, h = self.get_size() @@ -353,7 +353,7 @@ class MfxCanvas(gnomecanvas.Canvas): def configure(self, **kw): height, width = -1, -1 - for k, v in kw.items(): + for k, v in list(kw.items()): if k in ('background', 'bg'): self.modify_bg(gtk.STATE_NORMAL, gdk.color_parse(v)) elif k == 'cursor': @@ -367,8 +367,8 @@ class MfxCanvas(gnomecanvas.Canvas): elif k == 'width': width = v else: - print 'TkCanvas', k, v - raise AttributeError, k + print('TkCanvas', k, v) + raise AttributeError(k) if height > 0 and width > 0: self.set_size_request(width, height) @@ -535,14 +535,14 @@ class MfxCanvas(gnomecanvas.Canvas): pass def updateAll(self): - print 'Canvas - updateAll', + print('Canvas - updateAll', end=' ') for i in self._all_items: i._item.hide() self.update_now() n = 0 for i in self._all_items: i._item.show() - print n, i + print(n, i) n += 1 self.update_now() #self.window.invalidate_rect((0, 0, 400, 400), True) diff --git a/pysollib/pysolgtk/tkhtml.py b/pysollib/pysolgtk/tkhtml.py index 6b8831e7..c39a0557 100644 --- a/pysollib/pysolgtk/tkhtml.py +++ b/pysollib/pysolgtk/tkhtml.py @@ -36,15 +36,15 @@ if __name__ == '__main__': d = os.path.abspath(os.path.join(sys.path[0], '..', '..')) sys.path.append(d) import gettext - gettext.install('pysol', d, unicode=True) + gettext.install('pysol', d, str=True) # PySol imports from pysollib.mfxutil import Struct, openURL from pysollib.settings import TITLE # Toolkit imports -from tkutil import bind, unbind_destroy, loadImage -from tkwidget import MfxMessageDialog +from .tkutil import bind, unbind_destroy, loadImage +from .tkwidget import MfxMessageDialog REMOTE_PROTOCOLS = ('ftp:', 'gopher:', 'http:', 'mailto:', 'news:', 'telnet:') @@ -70,7 +70,7 @@ class tkHTMLWriter(formatter.NullWriter): def write(self, data): - data = unicode(data) + data = str(data) self.text.insert(self.text.get_end_iter(), data, len(data)) def anchor_bgn(self, href, name, type): @@ -251,7 +251,7 @@ class HTMLViewer: vbox.pack_start(self.statusbar, fill=True, expand=False) # load images - for name, fn in self.symbols_fn.items(): + for name, fn in list(self.symbols_fn.items()): self.symbols_img[name] = self.getImage(fn) # bindings @@ -282,7 +282,7 @@ class HTMLViewer: x, y = widget.window_to_buffer_coords(gtk.TEXT_WINDOW_TEXT, x, y) tags = widget.get_iter_at_location(x, y).get_tags() is_over_anchor = False - for tag, href in self.anchor_tags.values(): + for tag, href in list(self.anchor_tags.values()): if tag in tags: is_over_anchor = True break @@ -346,7 +346,7 @@ class HTMLViewer: 'bold' : (default_font[0], size, 'bold'), } - for tag_name in self.fontmap.keys(): + for tag_name in list(self.fontmap.keys()): font = self.fontmap[tag_name] font = font[0]+' '+str(font[1]) tag = self.textbuffer.create_tag(tag_name, font=font) @@ -385,8 +385,8 @@ class HTMLViewer: if baseurl is None: baseurl = self.url if 0: - import urllib - url = urllib.pathname2url(url) + import urllib.request, urllib.parse, urllib.error + url = urllib.request.pathname2url(url) if relpath and self.url: url = urllib.basejoin(baseurl, url) else: @@ -449,14 +449,14 @@ to open the following URL: try: file = None if 0: - import urllib - file = urllib.urlopen(url) + import urllib.request, urllib.parse, urllib.error + file = urllib.request.urlopen(url) else: file, url = self.openfile(url) data = file.read() file.close() file = None - except Exception, ex: + except Exception as ex: if file: file.close() self.errorDialog(_('Unable to service request:\n') + url + '\n\n' + str(ex)) return diff --git a/pysollib/pysolgtk/tkstats.py b/pysollib/pysolgtk/tkstats.py index 86769996..751fb4c8 100644 --- a/pysollib/pysolgtk/tkstats.py +++ b/pysollib/pysolgtk/tkstats.py @@ -34,7 +34,7 @@ from pysollib.settings import TOP_TITLE, TITLE from pysollib.stats import PysolStatsFormatter # Toolkit imports -from tkwidget import MfxDialog, MfxMessageDialog +from .tkwidget import MfxDialog, MfxMessageDialog # ************************************************************************ @@ -494,8 +494,8 @@ class Game_StatsDialog: def _cmpPlayingTime(self, store, iter1, iter2): val1 = store.get_value(iter1, 4) val2 = store.get_value(iter2, 4) - t1 = map(int, val1.split(':')) - t2 = map(int, val2.split(':')) + t1 = list(map(int, val1.split(':'))) + t2 = list(map(int, val2.split(':'))) return cmp(len(t1), len(t2)) or cmp(t1, t2) def _cmpMoves(self, store, iter1, iter2): diff --git a/pysollib/pysolgtk/tkwidget.py b/pysollib/pysolgtk/tkwidget.py index 766a66a4..56e32301 100644 --- a/pysollib/pysolgtk/tkwidget.py +++ b/pysollib/pysolgtk/tkwidget.py @@ -32,7 +32,7 @@ gdk = gtk.gdk from pysollib.mygettext import _, n_ # Toolkit imports -from tkutil import makeToplevel, setTransient, wm_withdraw +from .tkutil import makeToplevel, setTransient, wm_withdraw from pysollib.mfxutil import kwdefault, KwStruct, openURL diff --git a/pysollib/pysolgtk/tkwrap.py b/pysollib/pysolgtk/tkwrap.py index 41432d1f..a3dd9d83 100644 --- a/pysollib/pysolgtk/tkwrap.py +++ b/pysollib/pysolgtk/tkwrap.py @@ -33,7 +33,7 @@ from gtk import gdk from pysollib.settings import TITLE, VERSION # Toolkit imports -from tkutil import makeToplevel, loadImage +from .tkutil import makeToplevel, loadImage # ************************************************************************ @@ -72,13 +72,13 @@ class _MfxToplevel(gtk.Window): c = self.style.bg[gtk.STATE_NORMAL] c = '#%02x%02x%02x' % (c.red/256, c.green/256, c.blue/256) return c - print "Toplevel cget:", attr + print("Toplevel cget:", attr) ##~ raise AttributeError, attr return None def configure(self, **kw): height, width = -1, -1 - for k, v in kw.items(): + for k, v in list(kw.items()): if k in ("background", "bg"): ##print "Toplevel configure: bg" pass @@ -89,8 +89,8 @@ class _MfxToplevel(gtk.Window): elif k == "width": width = v else: - print "Toplevel configure:", k, v - raise AttributeError, k + print("Toplevel configure:", k, v) + raise AttributeError(k) if height > 0 and width > 0: ##print 'configure: size:', width, height ## FIXME @@ -163,7 +163,7 @@ class _MfxToplevel(gtk.Window): pass def wm_iconbitmap(self, name): - print 'wm_iconbitmap:', name + print('wm_iconbitmap:', name) if name and name[0] == '@' and name[-4:] == '.xbm': name = name[1:-4] + '.xpm' bg = self.get_style().bg[gtk.STATE_NORMAL] @@ -191,7 +191,7 @@ class _MfxToplevel(gtk.Window): def option_get(self, *args): if args and args[0] == 'font': return self.get_style().font_desc.to_string() - print '_MfxToplevel: option_get', args + print('_MfxToplevel: option_get', args) return None def grid_columnconfigure(self, *args, **kw): diff --git a/pysollib/pysolrandom.py b/pysollib/pysolrandom.py index d674e44b..43b799ee 100644 --- a/pysollib/pysolrandom.py +++ b/pysollib/pysolrandom.py @@ -38,7 +38,7 @@ from pysollib.mfxutil import SubclassResponsibility class BasicRandom: #MAX_SEED = 0L #MAX_SEED = 0xffffffffffffffffL # 64 bits - MAX_SEED = 100000000000000000000L # 20 digits + MAX_SEED = 100000000000000000000 # 20 digits ORIGIN_UNKNOWN = 0 ORIGIN_RANDOM = 1 @@ -59,18 +59,18 @@ class BasicRandom: raise SubclassResponsibility def copy(self): - random = self.__class__(0L) + random = self.__class__(0) random.__dict__.update(self.__dict__) return random def increaseSeed(self, seed): if seed < self.MAX_SEED: - return seed + 1L - return 0L + return seed + 1 + return 0 def _getRandomSeed(self): - t = long(time.time() * 256.0) - t = (t ^ (t >> 24)) % (self.MAX_SEED + 1L) + t = int(time.time() * 256.0) + t = (t ^ (t >> 24)) % (self.MAX_SEED + 1) return t def setSeedAsStr(self, new_s): @@ -142,9 +142,9 @@ class MFXRandom(BasicRandom): return self.seed def setSeed(self, seed): - seed = long(seed) - if not (0L <= seed <= self.MAX_SEED): - raise ValueError, "seed out of range" + seed = int(seed) + if not (0 <= seed <= self.MAX_SEED): + raise ValueError("seed out of range") self.seed = seed return seed @@ -163,7 +163,7 @@ class MFXRandom(BasicRandom): # Get a random integer in the range [a, b] including both end points. def randint(self, a, b): - return a + long(self.random() * (b+1-a)) + return a + int(self.random() * (b+1-a)) def randrange(self, a, b): return self.randint(a, b-1) @@ -187,8 +187,8 @@ class MFXRandom(BasicRandom): class LCRandom64(MFXRandom): def random(self): - self.seed = (self.seed*6364136223846793005L + 1L) & self.MAX_SEED - return ((self.seed >> 21) & 0x7fffffffL) / 2147483648.0 + self.seed = (self.seed*6364136223846793005 + 1) & self.MAX_SEED + return ((self.seed >> 21) & 0x7fffffff) / 2147483648.0 # ************************************************************************ @@ -198,17 +198,17 @@ class LCRandom64(MFXRandom): # ************************************************************************ class LCRandom31(MFXRandom): - MAX_SEED = 0x7fffffffL # 31 bits + MAX_SEED = 0x7fffffff # 31 bits def str(self, seed): return "%05d" % int(seed) def random(self): - self.seed = (self.seed*214013L + 2531011L) & self.MAX_SEED + self.seed = (self.seed*214013 + 2531011) & self.MAX_SEED return (self.seed >> 16) / 32768.0 def randint(self, a, b): - self.seed = (self.seed*214013L + 2531011L) & self.MAX_SEED + self.seed = (self.seed*214013 + 2531011) & self.MAX_SEED return a + (int(self.seed >> 16) % (b+1-a)) def shuffle(self, seq): @@ -233,18 +233,18 @@ PysolRandom = MTRandom def constructRandom(s): m = re.match(r"ms(\d+)\n?\Z", s); if m: - seed = long(m.group(1)) + seed = int(m.group(1)) if 0 <= seed < (1 << 31): ret = LCRandom31(seed) ret.setSeedAsStr(s) return ret else: - raise ValueError, "ms seed out of range" + raise ValueError("ms seed out of range") s = re.sub(r"L$", "", str(s)) # cut off "L" from possible conversion to long s = re.sub(r"[\s\#\-\_\.\,]", "", s.lower()) if not s: return None - seed = long(s) + seed = int(s) if 0 <= seed < 32000: return LCRandom31(seed) return PysolRandom(seed) @@ -252,8 +252,8 @@ def constructRandom(s): # test if __name__ == '__main__': r = constructRandom('12345') - print r.randint(0, 100) - print r.random() - print type(r) + print(r.randint(0, 100)) + print(r.random()) + print(type(r)) diff --git a/pysollib/resource.py b/pysollib/resource.py index 5eda1ae2..8c21bb95 100644 --- a/pysollib/resource.py +++ b/pysollib/resource.py @@ -118,7 +118,7 @@ class ResourceManager: dir = os.path.normpath(dir) if dir and os.path.isdir(dir) and dir not in result: result.append(dir) - except EnvironmentError, ex: + except EnvironmentError as ex: pass def getSearchDirs(self, app, search, env=None): @@ -145,11 +145,11 @@ class ResourceManager: self._addDir(result, d) else: self._addDir(result, os.path.join(dir, s)) - except EnvironmentError, ex: + except EnvironmentError as ex: traceback.print_exc() pass if DEBUG >= 6: - print "getSearchDirs", env, search, "->", result + print("getSearchDirs", env, search, "->", result) return result @@ -369,7 +369,7 @@ class Cardset(Resource): ls = min(ls, 4) low_ranks, high_ranks = 1, 3 ###if self.type == 3: high_ranks = 4 - for rank in range(0, low_ranks) + range(lr-high_ranks, lr): + for rank in list(range(0, low_ranks)) + list(range(lr-high_ranks, lr)): for suit in range(ls): index = suit * len(self.ranks) + rank pnames.append(names[index % len(names)]) @@ -377,7 +377,7 @@ class Cardset(Resource): def updateCardback(self, backname=None, backindex=None): # update default back - if isinstance(backname, basestring): + if isinstance(backname, str): if backname in self.backnames: backindex = self.backnames.index(backname) if isinstance(backindex, int): @@ -385,7 +385,7 @@ class Cardset(Resource): self.backname = self.backnames[self.backindex] def saveSettings(self): - print 'saveSettings' + print('saveSettings') class CardsetManager(ResourceManager): @@ -403,42 +403,42 @@ class CardsetManager(ResourceManager): return 0 cs.si.type = s if s == CSI.TYPE_FRENCH: - cs.ranks = range(13) + cs.ranks = list(range(13)) cs.suits = "cshd" elif s == CSI.TYPE_HANAFUDA: cs.nbottoms = 15 - cs.ranks = range(4) + cs.ranks = list(range(4)) cs.suits = "abcdefghijkl" elif s == CSI.TYPE_TAROCK: cs.nbottoms = 8 - cs.ranks = range(14) + cs.ranks = list(range(14)) cs.suits = "cshd" - cs.trumps = range(22) + cs.trumps = list(range(22)) elif s == CSI.TYPE_MAHJONGG: - cs.ranks = range(10) + cs.ranks = list(range(10)) cs.suits = "abc" - cs.trumps = range(12) + cs.trumps = list(range(12)) # cs.nbottoms = 0 cs.nletters = 0 cs.nshadows = 0 elif s == CSI.TYPE_HEXADECK: cs.nbottoms = 8 - cs.ranks = range(16) + cs.ranks = list(range(16)) cs.suits = "cshd" - cs.trumps = range(4) + cs.trumps = list(range(4)) elif s == CSI.TYPE_MUGHAL_GANJIFA: cs.nbottoms = 11 - cs.ranks = range(12) + cs.ranks = list(range(12)) cs.suits = "abcdefgh" elif s == CSI.TYPE_NAVAGRAHA_GANJIFA: #???return 0 ## FIXME cs.nbottoms = 12 - cs.ranks = range(12) + cs.ranks = list(range(12)) cs.suits = "abcdefghi" elif s == CSI.TYPE_DASHAVATARA_GANJIFA: cs.nbottoms = 13 - cs.ranks = range(12) + cs.ranks = list(range(12)) cs.suits = "abcdefghij" elif s == CSI.TYPE_TRUMP_ONLY: #???return 0 ## FIXME @@ -451,7 +451,7 @@ class CardsetManager(ResourceManager): cs.nshadows = 0 cs.ranks = () cs.suits = "" - cs.trumps = range(cs.ncards) + cs.trumps = list(range(cs.ncards)) else: return 0 diff --git a/pysollib/stack.py b/pysollib/stack.py index 7238e0f3..07715a24 100644 --- a/pysollib/stack.py +++ b/pysollib/stack.py @@ -375,9 +375,9 @@ class Stack: self.can_hide_cards = self.is_visible if self.cap.max_cards < 3: self.can_hide_cards = 0 - elif filter(None, self.CARD_XOFFSET): + elif [_f for _f in self.CARD_XOFFSET if _f]: self.can_hide_cards = 0 - elif filter(None, self.CARD_YOFFSET): + elif [_f for _f in self.CARD_YOFFSET if _f]: self.can_hide_cards = 0 elif self.canvas.preview: self.can_hide_cards = 0 @@ -3003,7 +3003,7 @@ class ArbitraryStack(OpenStack): # self.cap override any call-time cap class StackWrapper: def __init__(self, stack_class, **cap): - assert isinstance(stack_class, types.ClassType) + assert isinstance(stack_class, type) assert issubclass(stack_class, Stack) self.stack_class = stack_class self.cap = cap diff --git a/pysollib/stats.py b/pysollib/stats.py index 45e5bd84..105c2801 100644 --- a/pysollib/stats.py +++ b/pysollib/stats.py @@ -303,7 +303,7 @@ class ProgressionFormatter: t[0] -= 1 lt = self.norm_time(t) marks = [lt[:3], tt[:3]] - for i in xrange(5): + for i in range(5): tt[1] -= 2 marks.append(self.norm_time(tt)[:3]) delta = 7 @@ -342,7 +342,7 @@ class ProgressionFormatter: played = 0 won = 0 text = None - for i in xrange(delta): + for i in range(delta): if marks: if ct[:3] in marks: text = time.strftime(format, ct) diff --git a/pysollib/tile/card.py b/pysollib/tile/card.py index 7d135761..fe6fdcb2 100644 --- a/pysollib/tile/card.py +++ b/pysollib/tile/card.py @@ -29,7 +29,7 @@ __all__ = ['Card'] from pysollib.acard import AbstractCard # Toolkit imports -from tkcanvas import MfxCanvasGroup, MfxCanvasImage +from .tkcanvas import MfxCanvasGroup, MfxCanvasImage # ************************************************************************ diff --git a/pysollib/tile/colorsdialog.py b/pysollib/tile/colorsdialog.py index 1d406fb2..b63f9783 100644 --- a/pysollib/tile/colorsdialog.py +++ b/pysollib/tile/colorsdialog.py @@ -24,16 +24,16 @@ __all__ = ['ColorsDialog'] # imports -import Tkinter -import ttk -from tkColorChooser import askcolor +import tkinter +from . import ttk +from tkinter.colorchooser import askcolor # PySol imports from pysollib.mfxutil import KwStruct from pysollib.mygettext import _, n_ # Toolkit imports -from tkwidget import MfxDialog +from .tkwidget import MfxDialog # ************************************************************************ # * @@ -50,21 +50,21 @@ class ColorsDialog(MfxDialog): frame.pack(expand=True, fill='both', padx=5, pady=10) frame.columnconfigure(0, weight=1) - self.text_var = Tkinter.StringVar() + self.text_var = tkinter.StringVar() self.text_var.set(app.opt.colors['text']) - self.piles_var = Tkinter.StringVar() + self.piles_var = tkinter.StringVar() self.piles_var.set(app.opt.colors['piles']) - self.cards_1_var = Tkinter.StringVar() + self.cards_1_var = tkinter.StringVar() self.cards_1_var.set(app.opt.colors['cards_1']) - self.cards_2_var = Tkinter.StringVar() + self.cards_2_var = tkinter.StringVar() self.cards_2_var.set(app.opt.colors['cards_2']) - self.samerank_1_var = Tkinter.StringVar() + self.samerank_1_var = tkinter.StringVar() self.samerank_1_var.set(app.opt.colors['samerank_1']) - self.samerank_2_var = Tkinter.StringVar() + self.samerank_2_var = tkinter.StringVar() self.samerank_2_var.set(app.opt.colors['samerank_2']) - self.hintarrow_var = Tkinter.StringVar() + self.hintarrow_var = tkinter.StringVar() self.hintarrow_var.set(app.opt.colors['hintarrow']) - self.not_matching_var = Tkinter.StringVar() + self.not_matching_var = tkinter.StringVar() self.not_matching_var.set(app.opt.colors['not_matching']) # row = 0 @@ -80,7 +80,7 @@ class ColorsDialog(MfxDialog): ): ttk.Label(frame, text=title, anchor='w', ).grid(row=row, column=0, sticky='we') - l = Tkinter.Label(frame, width=10, height=2, + l = tkinter.Label(frame, width=10, height=2, bg=var.get(), textvariable=var) l.grid(row=row, column=1, padx=5) b = ttk.Button(frame, text=_('Change...'), width=10, diff --git a/pysollib/tile/edittextdialog.py b/pysollib/tile/edittextdialog.py index 9e9e646c..053f5697 100644 --- a/pysollib/tile/edittextdialog.py +++ b/pysollib/tile/edittextdialog.py @@ -24,15 +24,15 @@ __all__ = ['EditTextDialog'] # imports -import Tkinter -import ttk +import tkinter +from . import ttk # PySol imports from pysollib.mfxutil import KwStruct from pysollib.mygettext import _, n_ # Toolkit imports -from tkwidget import MfxDialog +from .tkwidget import MfxDialog # ************************************************************************ # * @@ -46,7 +46,7 @@ class EditTextDialog(MfxDialog): top_frame, bottom_frame = self.createFrames(kw) self.createBitmaps(top_frame, kw) # - self.text_w = Tkinter.Text(top_frame, bd=1, relief="sunken", + self.text_w = tkinter.Text(top_frame, bd=1, relief="sunken", wrap="word", width=64, height=16) self.text_w.pack(side='left', fill="both", expand=True) ###self.text_w.pack(side='top', padx=kw.padx, pady=kw.pady) diff --git a/pysollib/tile/findcarddialog.py b/pysollib/tile/findcarddialog.py index e63877f6..f7316056 100644 --- a/pysollib/tile/findcarddialog.py +++ b/pysollib/tile/findcarddialog.py @@ -28,13 +28,13 @@ __all__ = ['create_find_card_dialog', # imports import os -import Tkinter +import tkinter from pysollib.mygettext import _, n_ # Toolkit imports -from tkutil import after, after_cancel -from tkutil import bind, unbind_destroy, makeImage -from tkcanvas import MfxCanvas, MfxCanvasGroup, MfxCanvasImage, MfxCanvasRectangle +from .tkutil import after, after_cancel +from .tkutil import bind, unbind_destroy, makeImage +from .tkcanvas import MfxCanvas, MfxCanvasGroup, MfxCanvasImage, MfxCanvasRectangle from pysollib.settings import TITLE @@ -46,11 +46,11 @@ from pysollib.settings import TITLE LARGE_EMBLEMS_SIZE = (38, 34) SMALL_EMBLEMS_SIZE = (31, 21) -class FindCardDialog(Tkinter.Toplevel): +class FindCardDialog(tkinter.Toplevel): CARD_IMAGES = {} # key: (rank, suit) def __init__(self, parent, game, dir, size='large'): - Tkinter.Toplevel.__init__(self) + tkinter.Toplevel.__init__(self) title = TITLE + ' - ' + _('Find card') self.title(title) self.wm_resizable(False, False) @@ -194,7 +194,7 @@ class FindCardDialog(Tkinter.Toplevel): if self.highlight_items: for i in self.highlight_items: i.delete() - Tkinter.Toplevel.destroy(self) + tkinter.Toplevel.destroy(self) diff --git a/pysollib/tile/fontsdialog.py b/pysollib/tile/fontsdialog.py index 2a297c09..ac2e681c 100644 --- a/pysollib/tile/fontsdialog.py +++ b/pysollib/tile/fontsdialog.py @@ -24,18 +24,18 @@ __all__ = ['FontsDialog'] # imports -import Tkinter -import ttk -import tkFont +import tkinter +from . import ttk +import tkinter.font # PySol imports from pysollib.mfxutil import KwStruct from pysollib.mygettext import _, n_ # Toolkit imports -from tkwidget import MfxDialog -from tkutil import bind -from tkwidget import PysolScale +from .tkwidget import MfxDialog +from .tkutil import bind +from .tkwidget import PysolScale # ************************************************************************ @@ -75,11 +75,11 @@ class FontChooserDialog(MfxDialog): raise ValueError('invalid font style: '+init_font[3]) #self.family_var = Tkinter.StringVar() - self.weight_var = Tkinter.BooleanVar() + self.weight_var = tkinter.BooleanVar() self.weight_var.set(self.font_weight == 'bold') - self.slant_var = Tkinter.BooleanVar() + self.slant_var = tkinter.BooleanVar() self.slant_var.set(self.font_slant == 'italic') - self.size_var = Tkinter.IntVar() + self.size_var = tkinter.IntVar() self.size_var.set(self.font_size) # frame = ttk.Frame(top_frame) @@ -89,7 +89,7 @@ class FontChooserDialog(MfxDialog): self.entry = ttk.Entry(frame) self.entry.grid(row=0, column=0, columnspan=2, sticky='news') self.entry.insert('end', _('abcdefghABCDEFGH')) - self.list_box = Tkinter.Listbox(frame, width=36, exportselection=False) + self.list_box = tkinter.Listbox(frame, width=36, exportselection=False) sb = ttk.Scrollbar(frame) self.list_box.configure(yscrollcommand=sb.set) sb.configure(command=self.list_box.yview) @@ -111,7 +111,7 @@ class FontChooserDialog(MfxDialog): command=self.fontupdate, variable=self.size_var) sc.grid(row=4, column=0, columnspan=2, sticky='news') # - font_families = list(tkFont.families()) + font_families = list(tkinter.font.families()) font_families.sort() selected = -1 n = 0 diff --git a/pysollib/tile/gameinfodialog.py b/pysollib/tile/gameinfodialog.py index c53af971..a336696f 100644 --- a/pysollib/tile/gameinfodialog.py +++ b/pysollib/tile/gameinfodialog.py @@ -25,7 +25,7 @@ __all__ = ['GameInfoDialog'] # imports -import ttk +from . import ttk # PySol imports from pysollib.mygettext import _, n_ @@ -33,7 +33,7 @@ from pysollib.mfxutil import KwStruct from pysollib.gamedb import GI # Toolkit imports -from tkwidget import MfxDialog +from .tkwidget import MfxDialog # ************************************************************************ # * @@ -146,7 +146,7 @@ class GameInfoDialog(MfxDialog): fs[cn] += 1 else: fs[cn] = 1 - t = '\n'.join(['%s (%d)' % (i[0], i[1]) for i in fs.items()]) + t = '\n'.join(['%s (%d)' % (i[0], i[1]) for i in list(fs.items())]) else: t = stacks.__class__.__name__ ttk.Label(frame, text=t, anchor='w', justify='left' diff --git a/pysollib/tile/menubar.py b/pysollib/tile/menubar.py index ab9f5228..bf052b34 100644 --- a/pysollib/tile/menubar.py +++ b/pysollib/tile/menubar.py @@ -25,9 +25,9 @@ __all__ = ['PysolMenubarTk'] # imports import math, os, sys, re, traceback -import Tkinter -import ttk -import tkFileDialog +import tkinter +from . import ttk +import tkinter.filedialog # PySol imports from pysollib.mygettext import _, n_ @@ -41,18 +41,18 @@ from pysollib.settings import DEBUG from pysollib.gamedb import GI # toolkit imports -from tkconst import EVENT_HANDLED, EVENT_PROPAGATE, CURSOR_WATCH, COMPOUNDS -from tkutil import bind, after_idle -from selectgame import SelectGameDialog, SelectGameDialogWithPreview -from soundoptionsdialog import SoundOptionsDialog -from selectcardset import SelectCardsetDialogWithPreview -from selecttile import SelectTileDialogWithPreview -from findcarddialog import connect_game_find_card_dialog, destroy_find_card_dialog -from solverdialog import connect_game_solver_dialog -from tkwidget import MfxMessageDialog +from .tkconst import EVENT_HANDLED, EVENT_PROPAGATE, CURSOR_WATCH, COMPOUNDS +from .tkutil import bind, after_idle +from .selectgame import SelectGameDialog, SelectGameDialogWithPreview +from .soundoptionsdialog import SoundOptionsDialog +from .selectcardset import SelectCardsetDialogWithPreview +from .selecttile import SelectTileDialogWithPreview +from .findcarddialog import connect_game_find_card_dialog, destroy_find_card_dialog +from .solverdialog import connect_game_solver_dialog +from .tkwidget import MfxMessageDialog #from toolbar import TOOLBAR_BUTTONS -from tkconst import TOOLBAR_BUTTONS +from .tkconst import TOOLBAR_BUTTONS # ************************************************************************ @@ -110,14 +110,14 @@ def createToolbarMenu(menubar, menu): # * # ************************************************************************ -class MfxMenubar(Tkinter.Menu): +class MfxMenubar(tkinter.Menu): addPath = None def __init__(self, master, **kw): self.name = kw["name"] tearoff = 0 self.n = kw["tearoff"] = int(kw.get("tearoff", tearoff)) - Tkinter.Menu.__init__(self, master, **kw) + tkinter.Menu.__init__(self, master, **kw) def labeltoname(self, label): #print label, type(label) @@ -141,7 +141,7 @@ class MfxMenubar(Tkinter.Menu): if name and self.addPath: path = str(self._w) + "." + name self.addPath(path, self, self.n, cnf.get("menu")) - Tkinter.Menu.add(self, itemType, cnf) + tkinter.Menu.add(self, itemType, cnf) self.n = self.n + 1 @@ -193,54 +193,54 @@ class PysolMenubarTk: def _createTkOpt(self): # structure to convert menu-options to Toolkit variables self.tkopt = Struct( - gameid = Tkinter.IntVar(), - gameid_popular = Tkinter.IntVar(), - comment = Tkinter.BooleanVar(), - autofaceup = Tkinter.BooleanVar(), - autodrop = Tkinter.BooleanVar(), - autodeal = Tkinter.BooleanVar(), - quickplay = Tkinter.BooleanVar(), - undo = Tkinter.BooleanVar(), - bookmarks = Tkinter.BooleanVar(), - hint = Tkinter.BooleanVar(), - shuffle = Tkinter.BooleanVar(), - highlight_piles = Tkinter.BooleanVar(), - highlight_cards = Tkinter.BooleanVar(), - highlight_samerank = Tkinter.BooleanVar(), - highlight_not_matching = Tkinter.BooleanVar(), - mahjongg_show_removed = Tkinter.BooleanVar(), - shisen_show_hint = Tkinter.BooleanVar(), - sound = Tkinter.BooleanVar(), - auto_scale = Tkinter.BooleanVar(), - cardback = Tkinter.IntVar(), - tabletile = Tkinter.IntVar(), - animations = Tkinter.IntVar(), - redeal_animation = Tkinter.BooleanVar(), - win_animation = Tkinter.BooleanVar(), - shadow = Tkinter.BooleanVar(), - shade = Tkinter.BooleanVar(), - shade_filled_stacks = Tkinter.BooleanVar(), - shrink_face_down = Tkinter.BooleanVar(), - toolbar = Tkinter.IntVar(), - toolbar_style = Tkinter.StringVar(), - toolbar_relief = Tkinter.StringVar(), - toolbar_compound = Tkinter.StringVar(), - toolbar_size = Tkinter.IntVar(), - statusbar = Tkinter.BooleanVar(), - num_cards = Tkinter.BooleanVar(), - helpbar = Tkinter.BooleanVar(), - save_games_geometry = Tkinter.BooleanVar(), - splashscreen = Tkinter.BooleanVar(), - demo_logo = Tkinter.BooleanVar(), - mouse_type = Tkinter.StringVar(), - mouse_undo = Tkinter.BooleanVar(), - negative_bottom = Tkinter.BooleanVar(), - pause = Tkinter.BooleanVar(), - theme = Tkinter.StringVar(), + gameid = tkinter.IntVar(), + gameid_popular = tkinter.IntVar(), + comment = tkinter.BooleanVar(), + autofaceup = tkinter.BooleanVar(), + autodrop = tkinter.BooleanVar(), + autodeal = tkinter.BooleanVar(), + quickplay = tkinter.BooleanVar(), + undo = tkinter.BooleanVar(), + bookmarks = tkinter.BooleanVar(), + hint = tkinter.BooleanVar(), + shuffle = tkinter.BooleanVar(), + highlight_piles = tkinter.BooleanVar(), + highlight_cards = tkinter.BooleanVar(), + highlight_samerank = tkinter.BooleanVar(), + highlight_not_matching = tkinter.BooleanVar(), + mahjongg_show_removed = tkinter.BooleanVar(), + shisen_show_hint = tkinter.BooleanVar(), + sound = tkinter.BooleanVar(), + auto_scale = tkinter.BooleanVar(), + cardback = tkinter.IntVar(), + tabletile = tkinter.IntVar(), + animations = tkinter.IntVar(), + redeal_animation = tkinter.BooleanVar(), + win_animation = tkinter.BooleanVar(), + shadow = tkinter.BooleanVar(), + shade = tkinter.BooleanVar(), + shade_filled_stacks = tkinter.BooleanVar(), + shrink_face_down = tkinter.BooleanVar(), + toolbar = tkinter.IntVar(), + toolbar_style = tkinter.StringVar(), + toolbar_relief = tkinter.StringVar(), + toolbar_compound = tkinter.StringVar(), + toolbar_size = tkinter.IntVar(), + statusbar = tkinter.BooleanVar(), + num_cards = tkinter.BooleanVar(), + helpbar = tkinter.BooleanVar(), + save_games_geometry = tkinter.BooleanVar(), + splashscreen = tkinter.BooleanVar(), + demo_logo = tkinter.BooleanVar(), + mouse_type = tkinter.StringVar(), + mouse_undo = tkinter.BooleanVar(), + negative_bottom = tkinter.BooleanVar(), + pause = tkinter.BooleanVar(), + theme = tkinter.StringVar(), toolbar_vars = {}, ) for w in TOOLBAR_BUTTONS: - self.tkopt.toolbar_vars[w] = Tkinter.BooleanVar() + self.tkopt.toolbar_vars[w] = tkinter.BooleanVar() def _setOptions(self): tkopt, opt = self.tkopt, self.app.opt @@ -631,7 +631,7 @@ class PysolMenubarTk: def _addSelectGameMenu(self, menu): #games = map(self.app.gdb.get, self.app.gdb.getGamesIdSortedByShortName()) - games = map(self.app.gdb.get, self.app.gdb.getGamesIdSortedByName()) + games = list(map(self.app.gdb.get, self.app.gdb.getGamesIdSortedByName())) ##games = tuple(games) ###menu = MfxMenu(menu, label="Select &game") m = "Ctrl-" @@ -670,7 +670,7 @@ class PysolMenubarTk: if label is None: need_sep = 1 continue - g = filter(select_func, games) + g = list(filter(select_func, games)) if not g: continue if need_sep: @@ -682,12 +682,12 @@ class PysolMenubarTk: def _getNumGames(self, games, select_data): ngames = 0 for label, select_func in select_data: - ngames += len(filter(select_func, games)) + ngames += len(list(filter(select_func, games))) return ngames def _addSelectMahjonggGameSubMenu(self, games, menu, command, variable): select_func = lambda gi: gi.si.game_type == GI.GT_MAHJONGG - mahjongg_games = filter(select_func, games) + mahjongg_games = list(filter(select_func, games)) if len(mahjongg_games) == 0: return # @@ -711,7 +711,7 @@ class PysolMenubarTk: games[c].append(gi) else: games[c] = [gi] - games = games.items() + games = list(games.items()) games.sort() g0 = [] c0 = c1 = games[0][0] @@ -727,7 +727,7 @@ class PysolMenubarTk: def _addSelectPopularGameSubMenu(self, games, menu, command, variable): select_func = lambda gi: gi.si.game_flags & GI.GT_POPULAR - if len(filter(select_func, games)) == 0: + if len(list(filter(select_func, games))) == 0: return data = (n_("&Popular games"), select_func) self._addSelectGameSubMenu(games, menu, (data, ), @@ -760,7 +760,7 @@ class PysolMenubarTk: def _addSelectCustomGameSubMenu(self, games, menu, command, variable): submenu = MfxMenu(menu, label=n_("&Custom games")) select_func = lambda gi: gi.si.game_type == GI.GT_CUSTOM - games = filter(select_func, games) + games = list(filter(select_func, games)) self.updateGamesMenu(submenu, games) def _addSelectAllGameSubMenu(self, games, menu, command, variable): @@ -991,7 +991,7 @@ class PysolMenubarTk: idir, ifile = "", "" if not idir: idir = self.app.dn.savegames - d = tkFileDialog.Open() + d = tkinter.filedialog.Open() filename = d.show(filetypes=self.FILETYPES, defaultextension=self.DEFAULTEXTENSION, initialdir=idir, initialfile=ifile) @@ -1019,7 +1019,7 @@ class PysolMenubarTk: if not idir: idir = self.app.dn.savegames ##print self.game.filename, ifile - d = tkFileDialog.SaveAs() + d = tkinter.filedialog.SaveAs() filename = d.show(filetypes=self.FILETYPES, defaultextension=self.DEFAULTEXTENSION, initialdir=idir, initialfile=ifile) @@ -1418,7 +1418,7 @@ the next time you restart """)+TITLE, def wizardDialog(self, edit=False): from pysollib.wizardutil import write_game, reset_wizard - from wizarddialog import WizardDialog + from .wizarddialog import WizardDialog if edit: reset_wizard(self.game) @@ -1431,7 +1431,7 @@ the next time you restart """)+TITLE, gameid = write_game(self.app, game=self.game) else: gameid = write_game(self.app) - except Exception, err: + except Exception as err: if DEBUG: traceback.print_exc() d = MfxMessageDialog(self.top, title=_('Save game error'), @@ -1446,9 +1446,9 @@ Error while saving game. if SELECT_GAME_MENU: menu = self.__menupath[".menubar.select.customgames"][2] select_func = lambda gi: gi.si.game_type == GI.GT_CUSTOM - games = map(self.app.gdb.get, - self.app.gdb.getGamesIdSortedByName()) - games = filter(select_func, games) + games = list(map(self.app.gdb.get, + self.app.gdb.getGamesIdSortedByName())) + games = list(filter(select_func, games)) self.updateGamesMenu(menu, games) self.tkopt.gameid.set(gameid) diff --git a/pysollib/tile/playeroptionsdialog.py b/pysollib/tile/playeroptionsdialog.py index c39817a9..7503c6c5 100644 --- a/pysollib/tile/playeroptionsdialog.py +++ b/pysollib/tile/playeroptionsdialog.py @@ -24,15 +24,15 @@ __all__ = ['PlayerOptionsDialog'] # imports -import Tkinter -import ttk +import tkinter +from . import ttk # PySol imports from pysollib.mygettext import _, n_ from pysollib.mfxutil import KwStruct # Toolkit imports -from tkwidget import MfxDialog +from .tkwidget import MfxDialog # ************************************************************************ @@ -47,11 +47,11 @@ class PlayerOptionsDialog(MfxDialog): self.createBitmaps(top_frame, kw) self.app = app # - self.update_stats_var = Tkinter.BooleanVar() + self.update_stats_var = tkinter.BooleanVar() self.update_stats_var.set(app.opt.update_player_stats != 0) - self.confirm_var = Tkinter.BooleanVar() + self.confirm_var = tkinter.BooleanVar() self.confirm_var.set(app.opt.confirm != 0) - self.win_animation_var = Tkinter.BooleanVar() + self.win_animation_var = tkinter.BooleanVar() self.win_animation_var.set(app.opt.win_animation != 0) # frame = ttk.Frame(top_frame) diff --git a/pysollib/tile/progressbar.py b/pysollib/tile/progressbar.py index 024f88b2..5d9b10fa 100644 --- a/pysollib/tile/progressbar.py +++ b/pysollib/tile/progressbar.py @@ -24,12 +24,12 @@ __all__ = ['PysolProgressBar'] # imports -import Tkinter -import ttk +import tkinter +from . import ttk # Toolkit imports -from tkconst import EVENT_HANDLED -from tkutil import makeToplevel, setTransient +from .tkconst import EVENT_HANDLED +from .tkutil import makeToplevel, setTransient # ************************************************************************ @@ -119,8 +119,8 @@ class TestProgressBar: self.progress.frame.after(30, self.update) def progressbar_main(args): - from tkutil import wm_withdraw - tk = Tkinter.Tk() + from .tkutil import wm_withdraw + tk = tkinter.Tk() wm_withdraw(tk) pb = TestProgressBar(tk) tk.mainloop() diff --git a/pysollib/tile/selectcardset.py b/pysollib/tile/selectcardset.py index 8da02b0c..389aa7dc 100644 --- a/pysollib/tile/selectcardset.py +++ b/pysollib/tile/selectcardset.py @@ -26,8 +26,8 @@ __all__ = ['SelectCardsetDialogWithPreview'] # imports import os import traceback -import Tkinter -import ttk +import tkinter +from . import ttk # PySol imports from pysollib.mygettext import _, n_ @@ -36,11 +36,11 @@ from pysollib.util import CARDSET from pysollib.resource import CSI # Toolkit imports -from tkutil import loadImage -from tkwidget import MfxDialog, MfxScrolledCanvas, PysolScale -from tkcanvas import MfxCanvasImage -from selecttree import SelectDialogTreeLeaf, SelectDialogTreeNode -from selecttree import SelectDialogTreeData, SelectDialogTreeCanvas +from .tkutil import loadImage +from .tkwidget import MfxDialog, MfxScrolledCanvas, PysolScale +from .tkcanvas import MfxCanvasImage +from .selecttree import SelectDialogTreeLeaf, SelectDialogTreeNode +from .selecttree import SelectDialogTreeData, SelectDialogTreeCanvas # ************************************************************************ @@ -73,7 +73,7 @@ class SelectCardsetData(SelectDialogTreeData): self.no_contents = [ SelectCardsetLeaf(None, None, _("(no cardsets)"), key=None), ] # select_by_type = None - items = CSI.TYPE.items() + items = list(CSI.TYPE.items()) items.sort(lambda a, b: cmp(a[1], b[1])) nodes = [] for key, name in items: @@ -83,7 +83,7 @@ class SelectCardsetData(SelectDialogTreeData): select_by_type = SelectCardsetNode(None, _("by Type"), tuple(nodes), expanded=1) # select_by_style = None - items = CSI.STYLE.items() + items = list(CSI.STYLE.items()) items.sort(lambda a, b: cmp(a[1], b[1])) nodes = [] for key, name in items: @@ -94,7 +94,7 @@ class SelectCardsetData(SelectDialogTreeData): select_by_style = SelectCardsetNode(None, _("by Style"), tuple(nodes)) # select_by_nationality = None - items = CSI.NATIONALITY.items() + items = list(CSI.NATIONALITY.items()) items.sort(lambda a, b: cmp(a[1], b[1])) nodes = [] for key, name in items: @@ -105,7 +105,7 @@ class SelectCardsetData(SelectDialogTreeData): select_by_nationality = SelectCardsetNode(None, _("by Nationality"), tuple(nodes)) # select_by_date = None - items = CSI.DATE.items() + items = list(CSI.DATE.items()) items.sort(lambda a, b: cmp(a[1], b[1])) nodes = [] for key, name in items: @@ -115,7 +115,7 @@ class SelectCardsetData(SelectDialogTreeData): nodes.append(SelectCardsetNode(None, _("Uncategorized"), lambda cs: not cs.si.dates)) select_by_date = SelectCardsetNode(None, _("by Date"), tuple(nodes)) # - self.rootnodes = filter(None, ( + self.rootnodes = [_f for _f in ( SelectCardsetNode(None, _("All Cardsets"), lambda cs: 1, expanded=len(self.all_objects)<=12), SelectCardsetNode(None, _("by Size"), ( SelectCardsetNode(None, _("Tiny cardsets"), lambda cs: cs.si.size == CSI.SIZE_TINY), @@ -128,7 +128,7 @@ class SelectCardsetData(SelectDialogTreeData): select_by_style, select_by_date, select_by_nationality, - )) + ) if _f] class SelectCardsetByTypeData(SelectDialogTreeData): @@ -137,7 +137,7 @@ class SelectCardsetByTypeData(SelectDialogTreeData): self.all_objects = manager.getAllSortedByName() self.no_contents = [ SelectCardsetLeaf(None, None, _("(no cardsets)"), key=None), ] # - items = CSI.TYPE.items() + items = list(CSI.TYPE.items()) items.sort(lambda a, b: cmp(a[1], b[1])) nodes = [] for key, name in items: @@ -145,9 +145,9 @@ class SelectCardsetByTypeData(SelectDialogTreeData): nodes.append(SelectCardsetNode(None, name, lambda cs, key=key: key == cs.si.type)) select_by_type = SelectCardsetNode(None, _("by Type"), tuple(nodes), expanded=1) # - self.rootnodes = filter(None, ( + self.rootnodes = [_f for _f in ( select_by_type, - )) + ) if _f] # ************************************************************************ @@ -207,7 +207,7 @@ class SelectCardsetDialogWithPreview(MfxDialog): padx=padx, pady=pady) if USE_PIL: # - var = Tkinter.DoubleVar() + var = tkinter.DoubleVar() var.set(app.opt.scale_x) self.scale_x = PysolScale( left_frame, label=_('Scale X:'), @@ -217,7 +217,7 @@ class SelectCardsetDialogWithPreview(MfxDialog): command=self._updateScale) self.scale_x.grid(row=1, column=0, sticky='ew', padx=padx, pady=pady) # - var = Tkinter.DoubleVar() + var = tkinter.DoubleVar() var.set(app.opt.scale_y) self.scale_y = PysolScale( left_frame, label=_('Scale Y:'), @@ -227,7 +227,7 @@ class SelectCardsetDialogWithPreview(MfxDialog): command=self._updateScale) self.scale_y.grid(row=2, column=0, sticky='ew', padx=padx, pady=pady) # - self.auto_scale = Tkinter.BooleanVar() + self.auto_scale = tkinter.BooleanVar() self.auto_scale.set(app.opt.auto_scale) check = ttk.Checkbutton( left_frame, text=_('Auto scaling'), @@ -238,7 +238,7 @@ class SelectCardsetDialogWithPreview(MfxDialog): check.grid(row=3, column=0, columnspan=2, sticky='ew', padx=padx, pady=pady) # - self.preserve_aspect = Tkinter.BooleanVar() + self.preserve_aspect = tkinter.BooleanVar() self.preserve_aspect.set(app.opt.preserve_aspect_ratio) self.aspect_check = ttk.Checkbutton( left_frame, text=_('Preserve aspect ratio'), @@ -452,7 +452,7 @@ class CardsetInfoDialog(MfxDialog): settings_frame.grid(row=row, column=0, columnspan=2, sticky='ew', padx=0, pady=5, ipadx=5, ipady=5) row += 1 - var = Tkinter.IntVar() + var = tkinter.IntVar() self.x_offset = PysolScale( settings_frame, label=_('X offset:'), from_=5, to=40, resolution=1, @@ -462,7 +462,7 @@ class CardsetInfoDialog(MfxDialog): ) self.x_offset.grid(row=0, column=0, sticky='ew', padx=padx, pady=pady) - var = Tkinter.IntVar() + var = tkinter.IntVar() self.y_offset = PysolScale( settings_frame, label=_('Y offset:'), from_=5, to=40, resolution=1, @@ -476,7 +476,7 @@ class CardsetInfoDialog(MfxDialog): ##bg = top_frame["bg"] bg = 'white' - text_w = Tkinter.Text(frame, bd=1, relief="sunken", wrap="word", + text_w = tkinter.Text(frame, bd=1, relief="sunken", wrap="word", padx=4, width=64, height=16, bg=bg) text_w.grid(row=row, column=0, sticky='nsew') sb = ttk.Scrollbar(frame) diff --git a/pysollib/tile/selectgame.py b/pysollib/tile/selectgame.py index 825e38f5..2bd692ee 100644 --- a/pysollib/tile/selectgame.py +++ b/pysollib/tile/selectgame.py @@ -24,8 +24,8 @@ # imports import os -import ttk -from UserList import UserList +from . import ttk +from collections import UserList # PySol imports from pysollib.mygettext import _, n_ @@ -35,10 +35,10 @@ from pysollib.gamedb import GI from pysollib.resource import CSI # Toolkit imports -from tkutil import unbind_destroy -from tkwidget import MfxDialog, MfxScrolledCanvas -from selecttree import SelectDialogTreeLeaf, SelectDialogTreeNode -from selecttree import SelectDialogTreeData, SelectDialogTreeCanvas +from .tkutil import unbind_destroy +from .tkwidget import MfxDialog, MfxScrolledCanvas +from .selecttree import SelectDialogTreeLeaf, SelectDialogTreeNode +from .selecttree import SelectDialogTreeData, SelectDialogTreeCanvas # ************************************************************************ @@ -80,7 +80,7 @@ class SelectGameNode(SelectDialogTreeNode): class SelectGameData(SelectDialogTreeData): def __init__(self, app): SelectDialogTreeData.__init__(self) - self.all_games_gi = map(app.gdb.get, app.gdb.getGamesIdSortedByName()) + self.all_games_gi = list(map(app.gdb.get, app.gdb.getGamesIdSortedByName())) self.no_games = [ SelectGameLeaf(None, None, _("(no games)"), None), ] # s_by_type = s_oriental = s_special = s_original = s_contrib = s_mahjongg = None @@ -93,13 +93,13 @@ class SelectGameData(SelectDialogTreeData): ): gg = [] for name, select_func in data: - if name is None or not filter(select_func, self.all_games_gi): + if name is None or not list(filter(select_func, self.all_games_gi)): continue gg.append(SelectGameNode(None, _(name), select_func)) g.append(gg) select_mahjongg_game = lambda gi: gi.si.game_type == GI.GT_MAHJONGG gg = None - if filter(select_mahjongg_game, self.all_games_gi): + if list(filter(select_mahjongg_game, self.all_games_gi)): gg = SelectGameNode(None, _("Mahjongg Games"), select_mahjongg_game) g.append(gg) @@ -123,7 +123,7 @@ class SelectGameData(SelectDialogTreeData): s_by_compatibility, gg = None, [] for name, games in GI.GAMES_BY_COMPATIBILITY: select_func = lambda gi, games=games: gi.id in games - if name is None or not filter(select_func, self.all_games_gi): + if name is None or not list(filter(select_func, self.all_games_gi)): continue gg.append(SelectGameNode(None, name, select_func)) if 1 and gg: @@ -133,7 +133,7 @@ class SelectGameData(SelectDialogTreeData): s_by_pysol_version, gg = None, [] for name, games in GI.GAMES_BY_PYSOL_VERSION: select_func = lambda gi, games=games: gi.id in games - if name is None or not filter(select_func, self.all_games_gi): + if name is None or not list(filter(select_func, self.all_games_gi)): continue name = _("New games in v. ") + name gg.append(SelectGameNode(None, name, select_func)) @@ -143,7 +143,7 @@ class SelectGameData(SelectDialogTreeData): s_by_inventors, gg = None, [] for name, games in GI.GAMES_BY_INVENTORS: select_func = lambda gi, games=games: gi.id in games - if name is None or not filter(select_func, self.all_games_gi): + if name is None or not list(filter(select_func, self.all_games_gi)): continue gg.append(SelectGameNode(None, name, select_func)) if 1 and gg: @@ -152,7 +152,7 @@ class SelectGameData(SelectDialogTreeData): # ul_alternate_names = UserList(list(app.gdb.getGamesTuplesSortedByAlternateName())) # - self.rootnodes = filter(None, ( + self.rootnodes = [_f for _f in ( SelectGameNode(None, _("All Games"), None, expanded=0), SelectGameNode(None, _("Alternate Names"), ul_alternate_names), SelectGameNode(None, _("Popular Games"), @@ -238,7 +238,7 @@ class SelectGameData(SelectDialogTreeData): )), s_original, s_contrib, - )) + ) if _f] # ************************************************************************ diff --git a/pysollib/tile/selecttile.py b/pysollib/tile/selecttile.py index a1861a85..35fb6fa1 100644 --- a/pysollib/tile/selecttile.py +++ b/pysollib/tile/selecttile.py @@ -23,18 +23,18 @@ # imports -import Tkinter -import ttk -import tkColorChooser +import tkinter +from . import ttk +import tkinter.colorchooser # PySol imports from pysollib.mygettext import _, n_ from pysollib.mfxutil import KwStruct # Toolkit imports -from tkwidget import MfxDialog, MfxScrolledCanvas -from selecttree import SelectDialogTreeLeaf, SelectDialogTreeNode -from selecttree import SelectDialogTreeData, SelectDialogTreeCanvas +from .tkwidget import MfxDialog, MfxScrolledCanvas +from .selecttree import SelectDialogTreeLeaf, SelectDialogTreeNode +from .selecttree import SelectDialogTreeData, SelectDialogTreeCanvas # ************************************************************************ @@ -158,17 +158,17 @@ class SelectTileDialogWithPreview(MfxDialog): def mDone(self, button): if button == 0: # "OK" or double click - if isinstance(self.tree.selection_key, basestring): + if isinstance(self.tree.selection_key, str): self.key = str(self.tree.selection_key) else: self.key = self.tree.selection_key self.tree.n_expansions = 1 # save xyview in any case if button == 10: # "Solid color..." try: - c = tkColorChooser.askcolor(master=self.top, + c = tkinter.colorchooser.askcolor(master=self.top, initialcolor=self.table_color, title=_("Select table color")) - except Tkinter.TclError: + except tkinter.TclError: pass else: if c and c[1]: @@ -185,7 +185,7 @@ class SelectTileDialogWithPreview(MfxDialog): return canvas = self.preview.canvas canvas.deleteAllItems() - if isinstance(key, basestring): + if isinstance(key, str): # solid color canvas.config(bg=key) canvas.setTile(None) diff --git a/pysollib/tile/selecttree.py b/pysollib/tile/selecttree.py index 0ce9dd9b..47aeafaf 100644 --- a/pysollib/tile/selecttree.py +++ b/pysollib/tile/selecttree.py @@ -24,10 +24,10 @@ __all__ = ['SelectDialogTreeData'] # imports -import tkFont +import tkinter.font # Toolkit imports -from tktree import MfxTreeLeaf, MfxTreeNode, MfxTreeInCanvas +from .tktree import MfxTreeLeaf, MfxTreeNode, MfxTreeInCanvas # ************************************************************************ @@ -110,7 +110,7 @@ class SelectDialogTreeCanvas(MfxTreeInCanvas): self.style.height = 14 # height of symbol if font: self.style.font = font - f = tkFont.Font(parent, font) + f = tkinter.font.Font(parent, font) h = f.metrics()["linespace"] self.style.disty = max(self.style.width, h) diff --git a/pysollib/tile/solverdialog.py b/pysollib/tile/solverdialog.py index 6d365ea1..7eea8a93 100644 --- a/pysollib/tile/solverdialog.py +++ b/pysollib/tile/solverdialog.py @@ -30,8 +30,8 @@ __all__ = [ ] # imports -import Tkinter -import ttk +import tkinter +from . import ttk # PySol imports from pysollib.mygettext import _, n_ @@ -39,9 +39,9 @@ from pysollib.settings import TITLE from pysollib.mfxutil import KwStruct # Toolkit imports -from tkconst import EVENT_HANDLED -from tkwidget import MfxDialog -from tkwidget import PysolCombo +from .tkconst import EVENT_HANDLED +from .tkwidget import MfxDialog +from .tkwidget import PysolCombo # ************************************************************************ @@ -104,27 +104,27 @@ class SolverDialog(MfxDialog): # row += 1 - self.max_iters_var = Tkinter.IntVar() + self.max_iters_var = tkinter.IntVar() self.max_iters_var.set(10e4) ttk.Label(frame, text=_('Max iterations:'), anchor='w' ).grid(row=row, column=0, sticky='ew', padx=2, pady=2) - spin = Tkinter.Spinbox(frame, bg='white', from_=1000, to=10e6, + spin = tkinter.Spinbox(frame, bg='white', from_=1000, to=10e6, increment=1000, textvariable=self.max_iters_var) spin.grid(row=row, column=1, sticky='w', padx=2, pady=2) # row += 1 - self.max_depth_var = Tkinter.IntVar() + self.max_depth_var = tkinter.IntVar() self.max_depth_var.set(1000) ttk.Label(frame, text=_('Max depth:'), anchor='w' ).grid(row=row, column=0, sticky='ew', padx=2, pady=2) - spin = Tkinter.Spinbox(frame, bg='white', from_=100, to=10000, + spin = tkinter.Spinbox(frame, bg='white', from_=100, to=10000, increment=100, textvariable=self.max_depth_var) spin.grid(row=row, column=1, sticky='w', padx=2, pady=2) # row += 1 - self.progress_var = Tkinter.BooleanVar() + self.progress_var = tkinter.BooleanVar() self.progress_var.set(True) w = ttk.Checkbutton(frame, variable=self.progress_var, text=_('Show progress')) diff --git a/pysollib/tile/soundoptionsdialog.py b/pysollib/tile/soundoptionsdialog.py index e6c4bb19..7b1d8f5f 100644 --- a/pysollib/tile/soundoptionsdialog.py +++ b/pysollib/tile/soundoptionsdialog.py @@ -25,8 +25,8 @@ __all__ = ['SoundOptionsDialog'] # imports import os -import Tkinter -import ttk +import tkinter +from . import ttk # PySol imports from pysollib.mygettext import _, n_ @@ -35,9 +35,9 @@ from pysollib.settings import TITLE from pysollib.pysolaudio import pysolsoundserver # Toolkit imports -from tkconst import EVENT_HANDLED -from tkwidget import MfxDialog, MfxMessageDialog -from tkwidget import PysolScale +from .tkconst import EVENT_HANDLED +from .tkwidget import MfxDialog, MfxMessageDialog +from .tkwidget import PysolScale # ************************************************************************ @@ -54,42 +54,42 @@ class SoundOptionsDialog(MfxDialog): self.createBitmaps(top_frame, kw) # self.saved_opt = app.opt.copy() - self.sound = Tkinter.BooleanVar() + self.sound = tkinter.BooleanVar() self.sound.set(app.opt.sound != 0) - self.sound_mode = Tkinter.BooleanVar() + self.sound_mode = tkinter.BooleanVar() self.sound_mode.set(app.opt.sound_mode != 0) - self.sample_volume = Tkinter.IntVar() + self.sample_volume = tkinter.IntVar() self.sample_volume.set(app.opt.sound_sample_volume) - self.music_volume = Tkinter.IntVar() + self.music_volume = tkinter.IntVar() self.music_volume.set(app.opt.sound_music_volume) self.samples = [ - ('areyousure', _('Are You Sure'), Tkinter.BooleanVar()), + ('areyousure', _('Are You Sure'), tkinter.BooleanVar()), - ('deal', _('Deal'), Tkinter.BooleanVar()), - ('dealwaste', _('Deal waste'), Tkinter.BooleanVar()), + ('deal', _('Deal'), tkinter.BooleanVar()), + ('dealwaste', _('Deal waste'), tkinter.BooleanVar()), - ('turnwaste', _('Turn waste'), Tkinter.BooleanVar()), - ('startdrag', _('Start drag'), Tkinter.BooleanVar()), + ('turnwaste', _('Turn waste'), tkinter.BooleanVar()), + ('startdrag', _('Start drag'), tkinter.BooleanVar()), - ('drop', _('Drop'), Tkinter.BooleanVar()), - ('droppair', _('Drop pair'), Tkinter.BooleanVar()), - ('autodrop', _('Auto drop'), Tkinter.BooleanVar()), + ('drop', _('Drop'), tkinter.BooleanVar()), + ('droppair', _('Drop pair'), tkinter.BooleanVar()), + ('autodrop', _('Auto drop'), tkinter.BooleanVar()), - ('flip', _('Flip'), Tkinter.BooleanVar()), - ('autoflip', _('Auto flip'), Tkinter.BooleanVar()), - ('move', _('Move'), Tkinter.BooleanVar()), - ('nomove', _('No move'), Tkinter.BooleanVar()), + ('flip', _('Flip'), tkinter.BooleanVar()), + ('autoflip', _('Auto flip'), tkinter.BooleanVar()), + ('move', _('Move'), tkinter.BooleanVar()), + ('nomove', _('No move'), tkinter.BooleanVar()), - ('undo', _('Undo'), Tkinter.BooleanVar()), - ('redo', _('Redo'), Tkinter.BooleanVar()), + ('undo', _('Undo'), tkinter.BooleanVar()), + ('redo', _('Redo'), tkinter.BooleanVar()), - ('autopilotlost', _('Autopilot lost'), Tkinter.BooleanVar()), - ('autopilotwon', _('Autopilot won'), Tkinter.BooleanVar()), + ('autopilotlost', _('Autopilot lost'), tkinter.BooleanVar()), + ('autopilotwon', _('Autopilot won'), tkinter.BooleanVar()), - ('gamefinished', _('Game finished'), Tkinter.BooleanVar()), - ('gamelost', _('Game lost'), Tkinter.BooleanVar()), - ('gamewon', _('Game won'), Tkinter.BooleanVar()), - ('gameperfect', _('Perfect game'), Tkinter.BooleanVar()), + ('gamefinished', _('Game finished'), tkinter.BooleanVar()), + ('gamelost', _('Game lost'), tkinter.BooleanVar()), + ('gamewon', _('Game won'), tkinter.BooleanVar()), + ('gameperfect', _('Perfect game'), tkinter.BooleanVar()), ] # diff --git a/pysollib/tile/statusbar.py b/pysollib/tile/statusbar.py index 41590932..4330fb53 100644 --- a/pysollib/tile/statusbar.py +++ b/pysollib/tile/statusbar.py @@ -26,20 +26,20 @@ __all__ = ['PysolStatusbar', # imports import os, sys -import Tkinter -import ttk +import tkinter +from . import ttk from pysollib.mygettext import _, n_ if __name__ == '__main__': d = os.path.abspath(os.path.join(sys.path[0], os.pardir, os.pardir)) sys.path.append(d) import gettext - gettext.install('pysol', d, unicode=True) + gettext.install('pysol', d, str=True) # PySol imports # Toolkit imports -from tkwidget import MfxTooltip +from .tkwidget import MfxTooltip # ************************************************************************ # * @@ -96,9 +96,9 @@ class MfxStatusbar: # def updateText(self, **kw): - for k, v in kw.items(): + for k, v in list(kw.items()): label = getattr(self, k + '_label') - text = unicode(v) + text = str(v) width = label['width'] if width and len(text) > width: label['width'] = len(text) @@ -193,7 +193,7 @@ class TestStatusbar(PysolStatusbar): self.updateText(info='Some info text.') def statusbar_main(args): - tk = Tkinter.Tk() + tk = tkinter.Tk() statusbar = TestStatusbar(tk, args) tk.mainloop() return 0 diff --git a/pysollib/tile/timeoutsdialog.py b/pysollib/tile/timeoutsdialog.py index 5212b92c..c5abda1c 100644 --- a/pysollib/tile/timeoutsdialog.py +++ b/pysollib/tile/timeoutsdialog.py @@ -24,15 +24,15 @@ __all__ = ['TimeoutsDialog'] # imports -import Tkinter -import ttk +import tkinter +from . import ttk # PySol imports from pysollib.mygettext import _, n_ from pysollib.mfxutil import KwStruct # Toolkit imports -from tkwidget import MfxDialog, PysolScale +from .tkwidget import MfxDialog, PysolScale # ************************************************************************ @@ -50,17 +50,17 @@ class TimeoutsDialog(MfxDialog): frame.pack(expand=True, fill='both', padx=5, pady=10) frame.columnconfigure(0, weight=1) - self.demo_sleep_var = Tkinter.DoubleVar() + self.demo_sleep_var = tkinter.DoubleVar() self.demo_sleep_var.set(app.opt.timeouts['demo']) - self.hint_sleep_var = Tkinter.DoubleVar() + self.hint_sleep_var = tkinter.DoubleVar() self.hint_sleep_var.set(app.opt.timeouts['hint']) - self.raise_card_sleep_var = Tkinter.DoubleVar() + self.raise_card_sleep_var = tkinter.DoubleVar() self.raise_card_sleep_var.set(app.opt.timeouts['raise_card']) - self.highlight_piles_sleep_var = Tkinter.DoubleVar() + self.highlight_piles_sleep_var = tkinter.DoubleVar() self.highlight_piles_sleep_var.set(app.opt.timeouts['highlight_piles']) - self.highlight_cards_sleep_var = Tkinter.DoubleVar() + self.highlight_cards_sleep_var = tkinter.DoubleVar() self.highlight_cards_sleep_var.set(app.opt.timeouts['highlight_cards']) - self.highlight_samerank_sleep_var = Tkinter.DoubleVar() + self.highlight_samerank_sleep_var = tkinter.DoubleVar() self.highlight_samerank_sleep_var.set(app.opt.timeouts['highlight_samerank']) # lframe = ttk.LabelFrame(frame, text=_('Set delays in seconds'), diff --git a/pysollib/tile/tkcanvas.py b/pysollib/tile/tkcanvas.py index 6ae4084a..54d5fffe 100644 --- a/pysollib/tile/tkcanvas.py +++ b/pysollib/tile/tkcanvas.py @@ -29,14 +29,14 @@ __all__ = ['MfxCanvasGroup', 'MfxCanvas'] # imports -import Tkinter -import Canvas +import tkinter +import pysollib.Py2Canvas as Canvas # PySol imports from pysollib.mfxutil import Image, ImageTk # Toolkit imports -from tkutil import bind, unbind_destroy, loadImage +from .tkutil import bind, unbind_destroy, loadImage # ************************************************************************ @@ -118,9 +118,9 @@ class MfxCanvasText(Canvas.CanvasText): # * canvas # ************************************************************************ -class MfxCanvas(Tkinter.Canvas): +class MfxCanvas(tkinter.Canvas): def __init__(self, *args, **kw): - Tkinter.Canvas.__init__(self, *args, **kw) + tkinter.Canvas.__init__(self, *args, **kw) self.preview = 0 self.busy = False # this is also used by lib-tk/Canvas.py @@ -208,11 +208,11 @@ class MfxCanvas(Tkinter.Canvas): # def _x_create(self, itemType, *args, **kw): - return Tkinter.Canvas._create(self, itemType, args, kw) + return tkinter.Canvas._create(self, itemType, args, kw) def _create(self, itemType, args, kw): ##print "_create:", itemType, args, kw - id = Tkinter.Canvas._create(self, itemType, args, kw) + id = tkinter.Canvas._create(self, itemType, args, kw) if self.__tops: self.tk.call(self._w, "lower", id, self.__tops[0]) return id @@ -263,7 +263,7 @@ class MfxCanvas(Tkinter.Canvas): # delete all CanvasItems, but keep the background and top tiles def deleteAllItems(self): self._text_items = [] - for id in self.items.keys(): + for id in list(self.items.keys()): assert id not in self.__tiles # because the tile is created by id unbind_destroy(self.items[id]) self.items[id].delete() @@ -338,7 +338,7 @@ class MfxCanvas(Tkinter.Canvas): try: if image and isinstance(image, str): image = loadImage(file=image) - except Tkinter.TclError: + except tkinter.TclError: return 0 if len(self.__tops) == 1 and image is self.__tops[0]: return 1 @@ -370,11 +370,11 @@ class MfxCanvas(Tkinter.Canvas): # def hideAllItems(self): - for item in self.items.values(): + for item in list(self.items.values()): item.config(state='hidden') def showAllItems(self): - for item in self.items.values(): + for item in list(self.items.values()): item.config(state='normal') @@ -390,7 +390,7 @@ class MfxCanvas(Tkinter.Canvas): return funcid def _substitute(self, *args): - e = Tkinter.Event() + e = tkinter.Event() try: # Tk changed behavior in 8.4.2, returning "??" rather more often. e.x = int(args[0]) diff --git a/pysollib/tile/tkconst.py b/pysollib/tile/tkconst.py index e844ccee..feffb597 100644 --- a/pysollib/tile/tkconst.py +++ b/pysollib/tile/tkconst.py @@ -39,7 +39,7 @@ __all__ = ['EVENT_HANDLED', ] # imports -import Tkinter +import tkinter from pysollib.mygettext import _, n_ @@ -54,23 +54,23 @@ CURSOR_DRAG = "hand1" CURSOR_WATCH = "watch" CURSOR_DOWN_ARROW = 'sb_down_arrow' -ANCHOR_CENTER = Tkinter.CENTER -ANCHOR_N = Tkinter.N -ANCHOR_NW = Tkinter.NW -ANCHOR_NE = Tkinter.NE -ANCHOR_S = Tkinter.S -ANCHOR_SW = Tkinter.SW -ANCHOR_SE = Tkinter.SE -ANCHOR_W = Tkinter.W -ANCHOR_E = Tkinter.E +ANCHOR_CENTER = tkinter.CENTER +ANCHOR_N = tkinter.N +ANCHOR_NW = tkinter.NW +ANCHOR_NE = tkinter.NE +ANCHOR_S = tkinter.S +ANCHOR_SW = tkinter.SW +ANCHOR_SE = tkinter.SE +ANCHOR_W = tkinter.W +ANCHOR_E = tkinter.E COMPOUNDS = ( ##(Tkinter.BOTTOM, 'bottom'), ##(Tkinter.CENTER, 'center'), ##(Tkinter.RIGHT, 'right'), - (Tkinter.NONE, n_('Icons only')), - (Tkinter.TOP, n_('Text below icons')), - (Tkinter.LEFT, n_('Text beside icons')), + (tkinter.NONE, n_('Icons only')), + (tkinter.TOP, n_('Text below icons')), + (tkinter.LEFT, n_('Text beside icons')), ('text', n_('Text only')), ) diff --git a/pysollib/tile/tkhtml.py b/pysollib/tile/tkhtml.py index 381df3e6..d5f3c383 100644 --- a/pysollib/tile/tkhtml.py +++ b/pysollib/tile/tkhtml.py @@ -26,14 +26,14 @@ __all__ = ['HTMLViewer'] # imports import os, sys import htmllib, formatter -import Tkinter -import ttk +import tkinter +from . import ttk if __name__ == '__main__': d = os.path.abspath(os.path.join(sys.path[0], '..', '..')) sys.path.append(d) import gettext - gettext.install('pysol', d, unicode=True) + gettext.install('pysol', d, str=True) # PySol imports from pysollib.mygettext import _, n_ @@ -41,9 +41,9 @@ from pysollib.mfxutil import Struct, openURL from pysollib.settings import TITLE # Toolkit imports -from tkutil import bind, unbind_destroy -from tkwidget import MfxMessageDialog -from statusbar import HtmlStatusbar +from .tkutil import bind, unbind_destroy +from .tkwidget import MfxMessageDialog +from .statusbar import HtmlStatusbar REMOTE_PROTOCOLS = ("ftp:", "gopher:", "http:", "mailto:", "news:", "telnet:") @@ -83,7 +83,7 @@ class tkHTMLWriter(formatter.NullWriter): } self.text.config(cursor=self.viewer.defcursor, font=font) - for f in self.fontmap.keys(): + for f in list(self.fontmap.keys()): self.text.tag_config(f, font=self.fontmap[f]) self.anchor = None @@ -266,7 +266,7 @@ class HTMLViewer: sticky='nsew', padx=1, pady=1) vbar = ttk.Scrollbar(text_frame) vbar.pack(side='right', fill='y') - self.text = Tkinter.Text(text_frame, + self.text = tkinter.Text(text_frame, fg='black', bg='white', bd=1, relief='sunken', cursor=self.defcursor, @@ -282,7 +282,7 @@ class HTMLViewer: frame.rowconfigure(1, weight=1) # load images - for name, fn in self.symbols_fn.items(): + for name, fn in list(self.symbols_fn.items()): self.symbols_img[name] = self.getImage(fn) self.initBindings() @@ -332,8 +332,8 @@ class HTMLViewer: if baseurl is None: baseurl = self.url if 0: - import urllib - url = urllib.pathname2url(url) + import urllib.request, urllib.parse, urllib.error + url = urllib.request.pathname2url(url) if relpath and self.url: url = urllib.basejoin(baseurl, url) else: @@ -393,14 +393,14 @@ to open the following URL: try: file = None if 0: - import urllib - file = urllib.urlopen(url) + import urllib.request, urllib.parse, urllib.error + file = urllib.request.urlopen(url) else: file, url = self.openfile(url) data = file.read() file.close() file = None - except Exception, ex: + except Exception as ex: if file: file.close() self.errorDialog(_("Unable to service request:\n") + url + "\n\n" + str(ex)) return @@ -498,7 +498,7 @@ to open the following URL: if fn in self.images: return self.images[fn] try: - img = Tkinter.PhotoImage(master=self.parent, file=fn) + img = tkinter.PhotoImage(master=self.parent, file=fn) except: img = None self.images[fn] = img @@ -522,7 +522,7 @@ def tkhtml_main(args): url = args[1] except: url = os.path.join(os.pardir, os.pardir, "data", "html", "index.html") - top = Tkinter.Tk() + top = tkinter.Tk() top.tk.call("package", "require", "tile") top.wm_minsize(400, 200) viewer = HTMLViewer(top) diff --git a/pysollib/tile/tkstats.py b/pysollib/tile/tkstats.py index 1f77d3fb..caf39fca 100644 --- a/pysollib/tile/tkstats.py +++ b/pysollib/tile/tkstats.py @@ -33,9 +33,9 @@ __all__ = ['SingleGame_StatsDialog', # imports import os import time -import Tkinter -import ttk -import tkFont +import tkinter +from . import ttk +import tkinter.font # PySol imports from pysollib.mygettext import _, n_ @@ -46,8 +46,8 @@ from pysollib.stats import PysolStatsFormatter, ProgressionFormatter from pysollib.settings import TOP_TITLE # Toolkit imports -from tkutil import bind, unbind_destroy, loadImage -from tkwidget import MfxDialog, MfxMessageDialog +from .tkutil import bind, unbind_destroy, loadImage +from .tkwidget import MfxDialog, MfxMessageDialog # ************************************************************************ @@ -64,11 +64,11 @@ class StatsDialog(MfxDialog): MfxDialog.__init__(self, parent, title, kw.resizable, kw.default) self.font = app.getFont('default') - self.tkfont = tkFont.Font(parent, self.font) + self.tkfont = tkinter.font.Font(parent, self.font) self.font_metrics = self.tkfont.metrics() style = ttk.Style(parent) heading_font = style.lookup('Heading', 'font') # treeview heading - self.heading_tkfont = tkFont.Font(parent, heading_font) + self.heading_tkfont = tkinter.font.Font(parent, heading_font) self.selected_game = None @@ -230,7 +230,7 @@ class SingleGameFrame(ttk.Frame): self.fg = fg # w, h = self.tab_x[-1], max(self.tab_y[-1], self.oval_height+40) - c = Tkinter.Canvas(frame, width=w, height=h, + c = tkinter.Canvas(frame, width=w, height=h, bg=bg, highlightthickness=0) c.pack(fill='both', expand=True) self.canvas = c @@ -507,10 +507,10 @@ class LogDialog(MfxDialog): def __init__(self, parent, title, app, player, **kw): self.font = app.getFont('default') - self.tkfont = tkFont.Font(parent, self.font) + self.tkfont = tkinter.font.Font(parent, self.font) style = ttk.Style(parent) heading_font = style.lookup('Heading', 'font') # treeview heading - self.heading_tkfont = tkFont.Font(parent, heading_font) + self.heading_tkfont = tkinter.font.Font(parent, heading_font) self.font_metrics = self.tkfont.metrics() self.CHAR_H = self.font_metrics['linespace'] @@ -871,7 +871,7 @@ class ProgressionFrame(ttk.Frame): self.won_color = '#00dc28' self.percent_color = 'blue' # create canvas - self.canvas = canvas = Tkinter.Canvas(frame, bg='#dfe8ff', bd=0, + self.canvas = canvas = tkinter.Canvas(frame, bg='#dfe8ff', bd=0, highlightthickness=1, highlightbackground='black', width=self.canvas_width, @@ -881,7 +881,7 @@ class ProgressionFrame(ttk.Frame): # right frame right_frame = ttk.Frame(frame) right_frame.pack(side='left', fill='x', padx=5) - self.all_games_variable = var = Tkinter.StringVar() + self.all_games_variable = var = tkinter.StringVar() var.set('all') b = ttk.Radiobutton(right_frame, text=_('All games'), variable=var, value='all', @@ -893,7 +893,7 @@ class ProgressionFrame(ttk.Frame): b.pack(fill='x', expand=True, padx=3, pady=1) label_frame = ttk.LabelFrame(right_frame, text=_('Statistics for')) label_frame.pack(side='top', fill='x', pady=10) - self.variable = var = Tkinter.StringVar() + self.variable = var = tkinter.StringVar() var.set('week') for v, t in ( ('week', _('Last 7 days')), @@ -906,19 +906,19 @@ class ProgressionFrame(ttk.Frame): b.pack(fill='x', expand=True, padx=3, pady=1) label_frame = ttk.LabelFrame(right_frame, text=_('Show graphs')) label_frame.pack(side='top', fill='x') - self.played_graph_var = Tkinter.BooleanVar() + self.played_graph_var = tkinter.BooleanVar() self.played_graph_var.set(True) b = ttk.Checkbutton(label_frame, text=_('Played'), command=self.updateGraph, variable=self.played_graph_var) b.pack(fill='x', expand=True, padx=3, pady=1) - self.won_graph_var = Tkinter.BooleanVar() + self.won_graph_var = tkinter.BooleanVar() self.won_graph_var.set(True) b = ttk.Checkbutton(label_frame, text=_('Won'), command=self.updateGraph, variable=self.won_graph_var) b.pack(fill='x', expand=True, padx=3, pady=1) - self.percent_graph_var = Tkinter.BooleanVar() + self.percent_graph_var = tkinter.BooleanVar() self.percent_graph_var.set(True) b = ttk.Checkbutton(label_frame, text=_('% won'), command=self.updateGraph, diff --git a/pysollib/tile/tktree.py b/pysollib/tile/tktree.py index dfd1f224..fed1ebe3 100644 --- a/pysollib/tile/tktree.py +++ b/pysollib/tile/tktree.py @@ -23,11 +23,11 @@ # imports import os -import Tkinter +import tkinter # Toolkit imports -from tkutil import bind -from tkwidget import MfxScrolledCanvas +from .tkutil import bind +from .tkwidget import MfxScrolledCanvas # ************************************************************************ @@ -104,7 +104,7 @@ class MfxTreeBaseNode: try: # _tkinter.TclError: unknown option "-fill" ??? canvas.itemconfig(self.textrect_id, fill=bg) - except Tkinter.TclError: + except tkinter.TclError: pass elif self.selected: b = canvas.bbox(self.text_id) @@ -276,7 +276,7 @@ class MfxTreeInCanvas(MfxScrolledCanvas): # draw try: lx, ly, nx, ny = node.draw(nx, ny, None, None) - except Tkinter.TclError: + except tkinter.TclError: # FIXME: Tk bug ??? raise # set scroll region @@ -374,7 +374,7 @@ class DirectoryBrowser(MfxTreeInCanvas): return node.subnodes # dir = node.key - print "Getting %s" % dir + print("Getting %s" % dir) try: filenames = os.listdir(dir) filenames.sort() @@ -390,7 +390,7 @@ class DirectoryBrowser(MfxTreeInCanvas): node = self.findNode(event) if not node: return - print "Clicked node %s %s" % (node.text, node.key) + print("Clicked node %s %s" % (node.text, node.key)) if isinstance(node, MfxTreeLeaf): self.updateSelection(key=node.key) elif isinstance(node, MfxTreeNode): @@ -400,7 +400,7 @@ class DirectoryBrowser(MfxTreeInCanvas): if __name__ == "__main__": - tk = Tkinter.Tk() + tk = tkinter.Tk() if os.name == "nt": app = DirectoryBrowser(tk, ("c:\\", "c:\\windows")) else: diff --git a/pysollib/tile/tkutil.py b/pysollib/tile/tkutil.py index 49c2e940..6c188505 100644 --- a/pysollib/tile/tkutil.py +++ b/pysollib/tile/tkutil.py @@ -47,8 +47,8 @@ __all__ = ['wm_withdraw', # imports import re -import Tkinter -from tkFont import Font +import tkinter +from tkinter.font import Font # PySol imports from pysollib.mfxutil import Image, ImageTk, ImageOps @@ -78,8 +78,8 @@ def wm_get_geometry(window): g = window.wm_geometry() m = __wm_get_geometry_re.search(g) if not m: - raise Tkinter.TclError("invalid geometry "+str(g)) - l = map(int, m.groups()) + raise tkinter.TclError("invalid geometry "+str(g)) + l = list(map(int, m.groups())) if window.wm_state() == "zoomed": # workaround as Tk returns the "unzoomed" origin l[2] = l[3] = 0 @@ -115,7 +115,7 @@ def makeToplevel(parent, title=None): # # This is a shortcut for a Toplevel() instantiation plus calls to # set the title and icon name of the window. - window = Tkinter.Toplevel(parent) #, class_=TITLE) + window = tkinter.Toplevel(parent) #, class_=TITLE) ##window.wm_group(parent) ##window.wm_command("") if WIN_SYSTEM == "x11": @@ -129,7 +129,7 @@ def makeToplevel(parent, title=None): def make_help_toplevel(app, title=None): # Create an independent Toplevel window. from pysollib.winsystems import init_root_window - window = Tkinter.Tk(className=TITLE) + window = tkinter.Tk(className=TITLE) init_root_window(window, app) return window @@ -215,7 +215,7 @@ def unbind_destroy(widget): ##widget.deletecommand(funcid) else: widget.unbind(sequence, funcid) - except Tkinter.TclError: + except tkinter.TclError: pass del __mfx_bindings[k] ##for k in __mfx_bindings.keys(): print __mfx_bindings[k] @@ -239,7 +239,7 @@ def after_cancel(t): t[2].after_cancel(t[0]) try: t[2].deletecommand(t[1]) - except Tkinter.TclError: + except tkinter.TclError: pass @@ -287,8 +287,8 @@ def makeImage(file=None, data=None, dither=None, alpha=None): return im # fromstring(mode, size, data, decoder_name='raw', *args) else: - return Tkinter.PhotoImage(data=data) - return Tkinter.PhotoImage(**kw) + return tkinter.PhotoImage(data=data) + return tkinter.PhotoImage(**kw) loadImage = makeImage @@ -296,7 +296,7 @@ def copyImage(image, x, y, width, height): if Image: if isinstance(image, PIL_Image): return ImageTk.PhotoImage(image._pil_image.crop((x, y, x+width, y+height))) - dest = Tkinter.PhotoImage(width=width, height=height) + dest = tkinter.PhotoImage(width=width, height=height) assert dest.width() == width assert dest.height() == height dest.blank() @@ -337,7 +337,7 @@ def fillImage(image, fill, outline=None): image.put(f) def createImage(width, height, fill, outline=None): - image = Tkinter.PhotoImage(width=width, height=height) + image = tkinter.PhotoImage(width=width, height=height) assert image.width() == width assert image.height() == height image.blank() diff --git a/pysollib/tile/tkwidget.py b/pysollib/tile/tkwidget.py index 5d7fc5c9..d0db46a6 100644 --- a/pysollib/tile/tkwidget.py +++ b/pysollib/tile/tkwidget.py @@ -33,9 +33,9 @@ __all__ = ['MfxDialog', # imports import sys, os, time, locale -import Tkinter -import ttk -import tkFont +import tkinter +from . import ttk +import tkinter.font import traceback # PySol imports @@ -44,10 +44,10 @@ from pysollib.mfxutil import destruct, kwdefault, KwStruct, openURL from pysollib.settings import WIN_SYSTEM # Toolkit imports -from tkutil import after, after_cancel -from tkutil import bind, unbind_destroy -from tkutil import makeToplevel, setTransient -from tkcanvas import MfxCanvas +from .tkutil import after, after_cancel +from .tkutil import bind, unbind_destroy +from .tkutil import makeToplevel, setTransient +from .tkcanvas import MfxCanvas # ************************************************************************ @@ -83,7 +83,7 @@ class MfxDialog: # ex. _ToplevelDialog setTransient(self.top, self.parent) try: self.top.grab_set() - except Tkinter.TclError: + except tkinter.TclError: if traceback: traceback.print_exc() pass if timeout > 0: @@ -126,9 +126,9 @@ class MfxDialog: # ex. _ToplevelDialog key = event.char try: if os.name == 'nt': - key = unicode(key, locale.getpreferredencoding()) + key = str(key, locale.getpreferredencoding()) else: - key = unicode(key, 'utf-8') + key = str(key, 'utf-8') except: pass else: @@ -286,7 +286,7 @@ class MfxExceptionDialog(MfxMessageDialog): t = "[Errno %s] %s:\n%s" % (ex.errno, ex.strerror, repr(ex.filename)) else: t = str(ex) - kw.text = text + unicode(t, errors='replace') + kw.text = text + str(t, errors='replace') MfxMessageDialog.__init__(self, parent, title, **kw.getKw()) @@ -312,10 +312,10 @@ class PysolAboutDialog(MfxMessageDialog): if sys.version_info >= (2, 4): ##font_name = msg.lookup('TLabel', 'font') font_name = 'TkDefaultFont' - font = tkFont.Font(parent, name=font_name, exists=True) + font = tkinter.font.Font(parent, name=font_name, exists=True) font = font.copy() else: - font = tkFont.Font(parent, app.getFont('default')) + font = tkinter.font.Font(parent, app.getFont('default')) font.configure(underline=True) url_label = ttk.Label(frame, text=kw.url, font=font, foreground='blue', cursor='hand2') @@ -444,11 +444,11 @@ class MfxTooltip: y = self.widget.winfo_rooty() + self.widget.winfo_height() x += self.xoffset y += self.yoffset - self.tooltip = Tkinter.Toplevel() + self.tooltip = tkinter.Toplevel() self.tooltip.wm_iconify() self.tooltip.wm_overrideredirect(1) self.tooltip.wm_protocol("WM_DELETE_WINDOW", self.destroy) - self.label = Tkinter.Label(self.tooltip, text=self.text, + self.label = tkinter.Label(self.tooltip, text=self.text, relief=self.relief, justify=self.justify, fg=self.fg, bg=self.bg, bd=1, takefocus=0) self.label.pack(ipadx=1, ipady=1) @@ -554,7 +554,7 @@ class MfxScrolledCanvas: kw['bd'] = 0 relief = kw['relief'] del kw['relief'] - frame = Tkinter.Frame(self.frame, bd=bd, relief=relief) + frame = tkinter.Frame(self.frame, bd=bd, relief=relief) frame.grid(row=0, column=0, sticky="news") self.canvas = MfxCanvas(frame, **kw) self.canvas.pack(expand=True, fill='both') @@ -594,7 +594,7 @@ class MfxScrolledCanvas: #bind(w, '', self.mouse_wheel) def mouse_wheel(self, *args): - print 'MfxScrolledCanvas.mouse_wheel', args + print('MfxScrolledCanvas.mouse_wheel', args) def _setHbar(self, first, last): if self.canvas.busy: @@ -673,9 +673,9 @@ class StackDesc: text = stack.getHelp()+'\n'+stack.getBaseCard() text = text.strip() if text: - frame = Tkinter.Frame(self.canvas) + frame = tkinter.Frame(self.canvas) self.frame = frame - label = Tkinter.Message(frame, font=font, text=text, + label = tkinter.Message(frame, font=font, text=text, width=cardw-8, relief='solid', fg='#000000', bg='#ffffe0', bd=1) label.pack() @@ -798,11 +798,11 @@ class MyPysolScale: self.variable.set(v) -class TkinterScale(Tkinter.Scale): +class TkinterScale(tkinter.Scale): def __init__(self, parent, **kw): if 'value' in kw: del kw['value'] - Tkinter.Scale.__init__(self, parent, **kw) + tkinter.Scale.__init__(self, parent, **kw) PysolScale = MyPysolScale diff --git a/pysollib/tile/tkwrap.py b/pysollib/tile/tkwrap.py index d300eed1..278d7dd1 100644 --- a/pysollib/tile/tkwrap.py +++ b/pysollib/tile/tkwrap.py @@ -25,11 +25,11 @@ __all__ = ['TclError', 'MfxRoot'] # imports -import Tkinter -TclError = Tkinter.TclError +import tkinter +TclError = tkinter.TclError # PySol imports -from tkconst import EVENT_PROPAGATE +from .tkconst import EVENT_PROPAGATE # ************************************************************************ @@ -37,9 +37,9 @@ from tkconst import EVENT_PROPAGATE # * Required so that a Game will get properly destroyed. # ************************************************************************ -class MfxRoot(Tkinter.Tk): +class MfxRoot(tkinter.Tk): def __init__(self, **kw): - Tkinter.Tk.__init__(self, **kw) + tkinter.Tk.__init__(self, **kw) self.app = None self.wm_protocol('WM_DELETE_WINDOW', self.wmDeleteWindow) # for interruptible sleep @@ -77,11 +77,11 @@ class MfxRoot(Tkinter.Tk): def setCursor(self, cursor): if 0: ## FIXME: this causes ugly resizes ! - Tkinter.Tk.config(self, cursor=cursor) + tkinter.Tk.config(self, cursor=cursor) elif 0: ## and this is even worse ##print self.children - for v in self.children.values(): + for v in list(self.children.values()): v.config(cursor=cursor) else: pass @@ -94,7 +94,7 @@ class MfxRoot(Tkinter.Tk): #time.sleep(seconds) self.after(int(seconds*1000)) return - print 'sleep', seconds + print('sleep', seconds) timeout = int(seconds*1000) self.sleep_var = 0 while timeout > 0: @@ -104,7 +104,7 @@ class MfxRoot(Tkinter.Tk): break self.after(100) timeout -= 100 - print 'finish sleep' + print('finish sleep') return if self.after_id: self.after_cancel(self.after_id) @@ -115,17 +115,17 @@ class MfxRoot(Tkinter.Tk): if self.after_id: self.after_cancel(self.after_id) self.after_id = None - print 'finish sleep' + print('finish sleep') def _sleepEvent(self, *args): return - print '_sleepEvent', args + print('_sleepEvent', args) self.interruptSleep() return EVENT_PROPAGATE def interruptSleep(self): return - print 'interruptSleep' + print('interruptSleep') self.update() self.update_idletasks() self.sleep_var = 1 @@ -137,7 +137,7 @@ class MfxRoot(Tkinter.Tk): # def update(self): - Tkinter.Tk.update(self) + tkinter.Tk.update(self) def wmDeleteWindow(self): if self.app and self.app.menubar: diff --git a/pysollib/tile/toolbar.py b/pysollib/tile/toolbar.py index b21433c3..c2a5b64a 100644 --- a/pysollib/tile/toolbar.py +++ b/pysollib/tile/toolbar.py @@ -25,8 +25,8 @@ __all__ = ['PysolToolbarTk'] # imports import os -import Tkinter -import ttk +import tkinter +from . import ttk # PySol imports from pysollib.mygettext import _, n_ @@ -37,10 +37,10 @@ from pysollib.settings import TITLE, WIN_SYSTEM from pysollib.winsystems import TkSettings # Toolkit imports -from tkconst import EVENT_HANDLED -from tkwidget import MfxTooltip -from menubar import createToolbarMenu, MfxMenu -from tkutil import loadImage +from .tkconst import EVENT_HANDLED +from .tkwidget import MfxTooltip +from .menubar import createToolbarMenu, MfxMenu +from .tkutil import loadImage # ************************************************************************ @@ -122,9 +122,9 @@ class ToolbarSeparator(ttk.Separator): self.visible = False self.grid_forget() -class ToolbarLabel(Tkinter.Message): +class ToolbarLabel(tkinter.Message): def __init__(self, parent, toolbar, toolbar_name, position, **kwargs): - Tkinter.Message.__init__(self, parent, **kwargs) + tkinter.Message.__init__(self, parent, **kwargs) self.toolbar = toolbar self.toolbar_name = toolbar_name self.position = position @@ -401,7 +401,7 @@ class PysolToolbarTk: self.frame.update_idletasks() def updateText(self, **kw): - for name in kw.keys(): + for name in list(kw.keys()): label = getattr(self, name + "_label") label["text"] = kw[name] diff --git a/pysollib/tile/ttk.py b/pysollib/tile/ttk.py index 2e47f7d8..ed0b9879 100644 --- a/pysollib/tile/ttk.py +++ b/pysollib/tile/ttk.py @@ -25,13 +25,13 @@ __all__ = ["Button", "Checkbutton", "Combobox", "Entry", "Frame", "Label", # functions "tclobjs_to_py"] -import Tkinter +import tkinter from pysollib.mygettext import _, n_ -_flatten = Tkinter._flatten +_flatten = tkinter._flatten # Verify if Tk is new enough to not need Tile checking -_REQUIRE_TILE = True if Tkinter.TkVersion < 8.5 else False +_REQUIRE_TILE = True if tkinter.TkVersion < 8.5 else False def _loadttk(loadtk): # This extends the default Tkinter.Tk._loadtk method so we can be @@ -52,7 +52,7 @@ def _loadttk(loadtk): return _wrapper -Tkinter.Tk._loadtk = _loadttk(Tkinter.Tk._loadtk) +tkinter.Tk._loadtk = _loadttk(tkinter.Tk._loadtk) def _format_optdict(optdict, script=False, ignore=None): """Formats optdict to a tuple to pass it to tk.call. @@ -63,15 +63,15 @@ def _format_optdict(optdict, script=False, ignore=None): format = "%s" if not script else "{%s}" opts = [] - for opt, value in optdict.iteritems(): + for opt, value in optdict.items(): if ignore and opt in ignore: continue if isinstance(value, (list, tuple)): v = [] for val in value: - if isinstance(val, basestring): - v.append(unicode(val) if val else '{}') + if isinstance(val, str): + v.append(str(val) if val else '{}') else: v.append(str(val)) @@ -102,7 +102,7 @@ def _format_mapdict(mapdict, script=False): format = "%s" if not script else "{%s}" opts = [] - for opt, value in mapdict.iteritems(): + for opt, value in mapdict.items(): opt_val = [] # each value in mapdict is expected to be a sequence, where each item @@ -219,14 +219,14 @@ def _script_from_settings(settings): script = [] # a script will be generated according to settings passed, which # will then be evaluated by Tcl - for name, opts in settings.iteritems(): + for name, opts in settings.items(): # will format specific keys according to Tcl code if opts.get('configure'): # format 'configure' - s = ' '.join(map(unicode, _format_optdict(opts['configure'], True))) + s = ' '.join(map(str, _format_optdict(opts['configure'], True))) script.append("ttk::style configure %s %s;" % (name, s)) if opts.get('map'): # format 'map' - s = ' '.join(map(unicode, _format_mapdict(opts['map'], True))) + s = ' '.join(map(str, _format_mapdict(opts['map'], True))) script.append("ttk::style map %s %s;" % (name, s)) if 'layout' in opts: # format 'layout' which may be empty @@ -329,7 +329,7 @@ def _val_or_dict(options, func, *args): def _convert_stringval(value): """Converts a value to, hopefully, a more appropriate Python object.""" - value = unicode(value) + value = str(value) try: value = int(value) except (ValueError, TypeError): @@ -340,12 +340,12 @@ def _convert_stringval(value): def tclobjs_to_py(adict): """Returns adict with its values converted from Tcl objects to Python objects.""" - for opt, val in adict.iteritems(): - if val and hasattr(val, '__len__') and not isinstance(val, basestring): + for opt, val in adict.items(): + if val and hasattr(val, '__len__') and not isinstance(val, str): if getattr(val[0], 'typename', None) == 'StateSpec': val = _list_from_statespec(val) else: - val = map(_convert_stringval, val) + val = list(map(_convert_stringval, val)) elif hasattr(val, 'typename'): # some other (single) Tcl object val = _convert_stringval(val) @@ -362,8 +362,8 @@ class Style(object): def __init__(self, master=None): if master is None: - if Tkinter._support_default_root: - master = Tkinter._default_root or Tkinter.Tk() + if tkinter._support_default_root: + master = tkinter._default_root or tkinter.Tk() else: raise RuntimeError("No master specified and Tkinter is " "configured to not support default master") @@ -520,7 +520,7 @@ class Style(object): self.tk.call("ttk::setTheme", themename) -class Widget(Tkinter.Widget): +class Widget(tkinter.Widget): """Base class for Tk themed widgets.""" def __init__(self, master, widgetname, kw=None): @@ -543,7 +543,7 @@ class Widget(Tkinter.Widget): active, disabled, focus, pressed, selected, background, readonly, alternate, invalid """ - Tkinter.Widget.__init__(self, master, widgetname, kw=kw) + tkinter.Widget.__init__(self, master, widgetname, kw=kw) def identify(self, x, y): @@ -634,7 +634,7 @@ class Checkbutton(Widget): return self.tk.call(self._w, "invoke") -class Entry(Widget, Tkinter.Entry): +class Entry(Widget, tkinter.Entry): """Ttk Entry widget displays a one-line text string and allows that string to be edited by the user.""" @@ -939,7 +939,7 @@ class Notebook(Widget): self.tk.call("ttk::notebook::enableTraversal", self._w) -class Panedwindow(Widget, Tkinter.PanedWindow): +class Panedwindow(Widget, tkinter.PanedWindow): """Ttk Panedwindow widget displays a number of subwindows, stacked either vertically or horizontally.""" @@ -961,7 +961,7 @@ class Panedwindow(Widget, Tkinter.PanedWindow): Widget.__init__(self, master, "ttk::panedwindow", kw) - forget = Tkinter.PanedWindow.forget # overrides Pack.forget + forget = tkinter.PanedWindow.forget # overrides Pack.forget def insert(self, pos, child, **kw): @@ -1068,7 +1068,7 @@ class Radiobutton(Widget): return self.tk.call(self._w, "invoke") -class Scale(Widget, Tkinter.Scale): +class Scale(Widget, tkinter.Scale): """Ttk Scale widget is typically used to control the numeric value of a linked variable that varies uniformly over some range.""" @@ -1107,7 +1107,7 @@ class Scale(Widget, Tkinter.Scale): return self.tk.call(self._w, 'get', x, y) -class Scrollbar(Widget, Tkinter.Scrollbar): +class Scrollbar(Widget, tkinter.Scrollbar): """Ttk Scrollbar controls the viewport of a scrollable widget.""" def __init__(self, master=None, **kw): @@ -1272,7 +1272,7 @@ class Treeview(Widget): To configure the tree column heading, call this with column = "#0" """ cmd = kw.get('command') - if cmd and not isinstance(cmd, basestring): + if cmd and not isinstance(cmd, str): # callback not registered yet, do it now kw['command'] = self.master.register(cmd, self._substitute) @@ -1498,7 +1498,7 @@ class LabeledScale(Frame, object): self._label_top = kw.pop('compound', 'top') == 'top' Frame.__init__(self, master, **kw) - self._variable = variable or Tkinter.IntVar(master) + self._variable = variable or tkinter.IntVar(master) self._variable.set(from_) self._last_valid = from_ @@ -1588,13 +1588,13 @@ class OptionMenu(Menubutton): kw = {'textvariable': variable, 'style': kwargs.pop('style', None), 'direction': kwargs.pop('direction', None)} Menubutton.__init__(self, master, **kw) - self['menu'] = Tkinter.Menu(self, tearoff=False) + self['menu'] = tkinter.Menu(self, tearoff=False) self._variable = variable self._callback = kwargs.pop('command', None) if kwargs: - raise Tkinter.TclError('unknown option -%s' % ( - kwargs.iterkeys().next())) + raise tkinter.TclError('unknown option -%s' % ( + next(iter(kwargs.keys())))) self.set_menu(default, *values) @@ -1613,7 +1613,7 @@ class OptionMenu(Menubutton): menu.delete(0, 'end') for val in values: menu.add_radiobutton(label=val, - command=Tkinter._setit(self._variable, val, self._callback)) + command=tkinter._setit(self._variable, val, self._callback)) if default: self._variable.set(default) diff --git a/pysollib/tile/wizarddialog.py b/pysollib/tile/wizarddialog.py index 955a63ac..ea33934a 100644 --- a/pysollib/tile/wizarddialog.py +++ b/pysollib/tile/wizarddialog.py @@ -25,8 +25,8 @@ __all__ = ['WizardDialog'] # imports -import Tkinter -import ttk +import tkinter +from . import ttk # PySol imports from pysollib.mygettext import _, n_ @@ -35,8 +35,8 @@ from pysollib.wizardutil import WizardWidgets from pysollib.wizardpresets import presets # Toolkit imports -from tkwidget import MfxDialog -from tkwidget import PysolScale, PysolCombo +from .tkwidget import MfxDialog +from .tkwidget import PysolScale, PysolCombo # ************************************************************************ @@ -58,7 +58,7 @@ class WizardDialog(MfxDialog): notebook.pack(expand=True, fill='both') for w in WizardWidgets: - if isinstance(w, basestring): + if isinstance(w, str): frame = ttk.Frame(notebook) notebook.add(frame, text=w, sticky='nsew', padding=5) frame.columnconfigure(1, weight=1) @@ -69,7 +69,7 @@ class WizardDialog(MfxDialog): if w.widget == 'preset': if w.variable is None: - w.variable = Tkinter.StringVar() + w.variable = tkinter.StringVar() values = [_(v) for v in w.values] default = _(w.default) values.remove(default) @@ -84,12 +84,12 @@ class WizardDialog(MfxDialog): cb.grid(row=row, column=1, sticky='ew', padx=2, pady=2) elif w.widget == 'entry': if w.variable is None: - w.variable = Tkinter.StringVar() + w.variable = tkinter.StringVar() en = ttk.Entry(frame, textvariable=w.variable) en.grid(row=row, column=1, sticky='ew', padx=2, pady=2) elif w.widget == 'menu': if w.variable is None: - w.variable = Tkinter.StringVar() + w.variable = tkinter.StringVar() values = [_(v) for v in w.values] cb = PysolCombo(frame, values=tuple(values), textvariable=w.variable, @@ -98,7 +98,7 @@ class WizardDialog(MfxDialog): cb.grid(row=row, column=1, sticky='ew', padx=2, pady=2) elif w.widget == 'spin': if w.variable is None: - w.variable = Tkinter.IntVar() + w.variable = tkinter.IntVar() else: # delete all trace callbacks for mod, cbname in w.variable.trace_vinfo(): @@ -111,7 +111,7 @@ class WizardDialog(MfxDialog): s.grid(row=row, column=1, sticky='ew', padx=2, pady=2) elif w.widget == 'check': if w.variable is None: - w.variable = Tkinter.BooleanVar() + w.variable = tkinter.BooleanVar() ch = ttk.Checkbutton(frame, variable=w.variable, takefocus=False) ch.grid(row=row, column=1, sticky='ew', padx=2, pady=2) @@ -135,7 +135,7 @@ class WizardDialog(MfxDialog): n = w.translation_map[n] p = presets[n] for w in WizardWidgets: - if isinstance(w, basestring): + if isinstance(w, str): continue if w.var_name in p: v = p[w.var_name] diff --git a/pysollib/tk/card.py b/pysollib/tk/card.py index 7d135761..fe6fdcb2 100644 --- a/pysollib/tk/card.py +++ b/pysollib/tk/card.py @@ -29,7 +29,7 @@ __all__ = ['Card'] from pysollib.acard import AbstractCard # Toolkit imports -from tkcanvas import MfxCanvasGroup, MfxCanvasImage +from .tkcanvas import MfxCanvasGroup, MfxCanvasImage # ************************************************************************ diff --git a/pysollib/tk/colorsdialog.py b/pysollib/tk/colorsdialog.py index a831288c..34b2a548 100644 --- a/pysollib/tk/colorsdialog.py +++ b/pysollib/tk/colorsdialog.py @@ -24,15 +24,15 @@ __all__ = ['ColorsDialog'] # imports -import Tkinter -from tkColorChooser import askcolor +import tkinter +from tkinter.colorchooser import askcolor # PySol imports from pysollib.mygettext import _, n_ from pysollib.mfxutil import KwStruct # Toolkit imports -from tkwidget import MfxDialog +from .tkwidget import MfxDialog # ************************************************************************ # * @@ -45,25 +45,25 @@ class ColorsDialog(MfxDialog): top_frame, bottom_frame = self.createFrames(kw) self.createBitmaps(top_frame, kw) - frame = Tkinter.Frame(top_frame) + frame = tkinter.Frame(top_frame) frame.pack(expand=True, fill='both', padx=5, pady=10) frame.columnconfigure(0, weight=1) - self.text_var = Tkinter.StringVar() + self.text_var = tkinter.StringVar() self.text_var.set(app.opt.colors['text']) - self.piles_var = Tkinter.StringVar() + self.piles_var = tkinter.StringVar() self.piles_var.set(app.opt.colors['piles']) - self.cards_1_var = Tkinter.StringVar() + self.cards_1_var = tkinter.StringVar() self.cards_1_var.set(app.opt.colors['cards_1']) - self.cards_2_var = Tkinter.StringVar() + self.cards_2_var = tkinter.StringVar() self.cards_2_var.set(app.opt.colors['cards_2']) - self.samerank_1_var = Tkinter.StringVar() + self.samerank_1_var = tkinter.StringVar() self.samerank_1_var.set(app.opt.colors['samerank_1']) - self.samerank_2_var = Tkinter.StringVar() + self.samerank_2_var = tkinter.StringVar() self.samerank_2_var.set(app.opt.colors['samerank_2']) - self.hintarrow_var = Tkinter.StringVar() + self.hintarrow_var = tkinter.StringVar() self.hintarrow_var.set(app.opt.colors['hintarrow']) - self.not_matching_var = Tkinter.StringVar() + self.not_matching_var = tkinter.StringVar() self.not_matching_var.set(app.opt.colors['not_matching']) # row = 0 @@ -77,12 +77,12 @@ class ColorsDialog(MfxDialog): (_('Hint arrow:'), self.hintarrow_var), (_('Highlight not matching:'), self.not_matching_var), ): - Tkinter.Label(frame, text=title, anchor='w', + tkinter.Label(frame, text=title, anchor='w', ).grid(row=row, column=0, sticky='we') - l = Tkinter.Label(frame, width=10, height=2, + l = tkinter.Label(frame, width=10, height=2, bg=var.get(), textvariable=var) l.grid(row=row, column=1, padx=5) - b = Tkinter.Button(frame, text=_('Change...'), width=10, + b = tkinter.Button(frame, text=_('Change...'), width=10, command=lambda l=l: self.selectColor(l)) b.grid(row=row, column=2) row += 1 diff --git a/pysollib/tk/edittextdialog.py b/pysollib/tk/edittextdialog.py index 407b2c5b..d5f10880 100644 --- a/pysollib/tk/edittextdialog.py +++ b/pysollib/tk/edittextdialog.py @@ -24,14 +24,14 @@ __all__ = ['EditTextDialog'] # imports -import Tkinter +import tkinter # PySol imports from pysollib.mygettext import _, n_ from pysollib.mfxutil import KwStruct # Toolkit imports -from tkwidget import MfxDialog +from .tkwidget import MfxDialog # ************************************************************************ # * @@ -45,11 +45,11 @@ class EditTextDialog(MfxDialog): top_frame, bottom_frame = self.createFrames(kw) self.createBitmaps(top_frame, kw) # - self.text_w = Tkinter.Text(top_frame, bd=1, relief="sunken", + self.text_w = tkinter.Text(top_frame, bd=1, relief="sunken", wrap="word", width=64, height=16) self.text_w.pack(side='left', fill="both", expand=True) ###self.text_w.pack(side='top', padx=kw.padx, pady=kw.pady) - vbar = Tkinter.Scrollbar(top_frame) + vbar = tkinter.Scrollbar(top_frame) vbar.pack(side='right', fill='y') self.text_w["yscrollcommand"] = vbar.set vbar["command"] = self.text_w.yview diff --git a/pysollib/tk/findcarddialog.py b/pysollib/tk/findcarddialog.py index 3e7d3def..4e1bc905 100644 --- a/pysollib/tk/findcarddialog.py +++ b/pysollib/tk/findcarddialog.py @@ -28,16 +28,16 @@ __all__ = ['create_find_card_dialog', # imports import os -import Tkinter +import tkinter ##import traceback # PySol imports from pysollib.mygettext import _, n_ # Toolkit imports -from tkutil import after, after_cancel -from tkutil import bind, unbind_destroy, makeImage -from tkcanvas import MfxCanvas, MfxCanvasGroup, MfxCanvasImage, MfxCanvasRectangle +from .tkutil import after, after_cancel +from .tkutil import bind, unbind_destroy, makeImage +from .tkcanvas import MfxCanvas, MfxCanvasGroup, MfxCanvasImage, MfxCanvasRectangle from pysollib.settings import TITLE @@ -49,11 +49,11 @@ from pysollib.settings import TITLE LARGE_EMBLEMS_SIZE = (38, 34) SMALL_EMBLEMS_SIZE = (31, 21) -class FindCardDialog(Tkinter.Toplevel): +class FindCardDialog(tkinter.Toplevel): CARD_IMAGES = {} # key: (rank, suit) def __init__(self, parent, game, dir, size='large'): - Tkinter.Toplevel.__init__(self) + tkinter.Toplevel.__init__(self) title = TITLE + ' - ' + _('Find card') self.title(title) self.wm_resizable(False, False) @@ -197,7 +197,7 @@ class FindCardDialog(Tkinter.Toplevel): if self.highlight_items: for i in self.highlight_items: i.delete() - Tkinter.Toplevel.destroy(self) + tkinter.Toplevel.destroy(self) diff --git a/pysollib/tk/fontsdialog.py b/pysollib/tk/fontsdialog.py index 4fae3328..01a1037b 100644 --- a/pysollib/tk/fontsdialog.py +++ b/pysollib/tk/fontsdialog.py @@ -24,16 +24,16 @@ __all__ = ['FontsDialog'] # imports -import Tkinter -import tkFont +import tkinter +import tkinter.font # PySol imports from pysollib.mygettext import _, n_ from pysollib.mfxutil import KwStruct # Toolkit imports -from tkwidget import MfxDialog -from tkutil import bind +from .tkwidget import MfxDialog +from .tkutil import bind # ************************************************************************ # * @@ -72,35 +72,35 @@ class FontChooserDialog(MfxDialog): raise ValueError('invalid font style: '+init_font[3]) #self.family_var = Tkinter.StringVar() - self.weight_var = Tkinter.BooleanVar() - self.slant_var = Tkinter.BooleanVar() - self.size_var = Tkinter.IntVar() + self.weight_var = tkinter.BooleanVar() + self.slant_var = tkinter.BooleanVar() + self.size_var = tkinter.IntVar() - frame = Tkinter.Frame(top_frame) + frame = tkinter.Frame(top_frame) frame.pack(expand=True, fill='both', padx=5, pady=10) frame.columnconfigure(0, weight=1) #frame.rowconfigure(1, weight=1) - self.entry = Tkinter.Entry(frame, bg='white') + self.entry = tkinter.Entry(frame, bg='white') self.entry.grid(row=0, column=0, columnspan=2, sticky='news') self.entry.insert('end', _('abcdefghABCDEFGH')) - self.list_box = Tkinter.Listbox(frame, width=36, exportselection=False) - sb = Tkinter.Scrollbar(frame) + self.list_box = tkinter.Listbox(frame, width=36, exportselection=False) + sb = tkinter.Scrollbar(frame) self.list_box.configure(yscrollcommand=sb.set) sb.configure(command=self.list_box.yview) self.list_box.grid(row=1, column=0, sticky='news') # rowspan=4 sb.grid(row=1, column=1, sticky='ns') bind(self.list_box, '<>', self.fontupdate) ##self.list_box.focus() - cb1 = Tkinter.Checkbutton(frame, anchor='w', text=_('Bold'), + cb1 = tkinter.Checkbutton(frame, anchor='w', text=_('Bold'), command=self.fontupdate, variable=self.weight_var) cb1.grid(row=2, column=0, columnspan=2, sticky='we') - cb2 = Tkinter.Checkbutton(frame, anchor='w', text=_('Italic'), + cb2 = tkinter.Checkbutton(frame, anchor='w', text=_('Italic'), command=self.fontupdate, variable=self.slant_var) cb2.grid(row=3, column=0, columnspan=2, sticky='we') - sc = Tkinter.Scale(frame, from_=6, to=40, resolution=1, + sc = tkinter.Scale(frame, from_=6, to=40, resolution=1, #label='Size', orient='horizontal', command=self.fontupdate, variable=self.size_var) @@ -109,7 +109,7 @@ class FontChooserDialog(MfxDialog): self.size_var.set(self.font_size) self.weight_var.set(self.font_weight == 'bold') self.slant_var.set(self.font_slant == 'italic') - font_families = list(tkFont.families()) + font_families = list(tkinter.font.families()) font_families.sort() selected = -1 n = 0 @@ -158,7 +158,7 @@ class FontsDialog(MfxDialog): top_frame, bottom_frame = self.createFrames(kw) self.createBitmaps(top_frame, kw) - frame = Tkinter.Frame(top_frame) + frame = tkinter.Frame(top_frame) frame.pack(expand=True, fill='both', padx=5, pady=10) frame.columnconfigure(0, weight=1) @@ -175,15 +175,15 @@ class FontsDialog(MfxDialog): ): font = app.opt.fonts[fn] self.fonts[fn] = font - Tkinter.Label(frame, text=title, anchor='w' + tkinter.Label(frame, text=title, anchor='w' ).grid(row=row, column=0, sticky='we') if font: title = ' '.join([str(i) for i in font if i not in ('roman', 'normal')]) elif font is None: title = 'Default' - l = Tkinter.Label(frame, font=font, text=title) + l = tkinter.Label(frame, font=font, text=title) l.grid(row=row, column=1) - b = Tkinter.Button(frame, text=_('Change...'), width=10, + b = tkinter.Button(frame, text=_('Change...'), width=10, command=lambda l=l, fn=fn: self.selectFont(l, fn)) b.grid(row=row, column=2) row += 1 diff --git a/pysollib/tk/gameinfodialog.py b/pysollib/tk/gameinfodialog.py index 2731e5de..fc0b50ad 100644 --- a/pysollib/tk/gameinfodialog.py +++ b/pysollib/tk/gameinfodialog.py @@ -25,7 +25,7 @@ __all__ = ['GameInfoDialog'] # imports -import Tkinter +import tkinter # PySol imports from pysollib.mygettext import _, n_ @@ -33,7 +33,7 @@ from pysollib.mfxutil import KwStruct from pysollib.gamedb import GI # Toolkit imports -from tkwidget import MfxDialog +from .tkwidget import MfxDialog # ************************************************************************ # * @@ -46,7 +46,7 @@ class GameInfoDialog(MfxDialog): top_frame, bottom_frame = self.createFrames(kw) self.createBitmaps(top_frame, kw) - frame = Tkinter.Frame(top_frame) + frame = tkinter.Frame(top_frame) frame.pack(expand=True, fill='both', padx=5, pady=10) frame.columnconfigure(0, weight=1) @@ -110,9 +110,9 @@ class GameInfoDialog(MfxDialog): ('Hint:', hint), ): if t: - Tkinter.Label(frame, text=n, anchor='w' + tkinter.Label(frame, text=n, anchor='w' ).grid(row=row, column=0, sticky='nw') - Tkinter.Label(frame, text=t, anchor='w', justify='left' + tkinter.Label(frame, text=t, anchor='w', justify='left' ).grid(row=row, column=1, sticky='nw') row += 1 @@ -136,7 +136,7 @@ class GameInfoDialog(MfxDialog): self.mainloop(focus, kw.timeout) def showStacks(self, frame, row, title, stacks): - Tkinter.Label(frame, text=title, anchor='w' + tkinter.Label(frame, text=title, anchor='w' ).grid(row=row, column=0, sticky='nw') if isinstance(stacks, (list, tuple)): fs = {} @@ -146,10 +146,10 @@ class GameInfoDialog(MfxDialog): fs[cn] += 1 else: fs[cn] = 1 - t = '\n'.join(['%s (%d)' % (i[0], i[1]) for i in fs.items()]) + t = '\n'.join(['%s (%d)' % (i[0], i[1]) for i in list(fs.items())]) else: t = stacks.__class__.__name__ - Tkinter.Label(frame, text=t, anchor='w', justify='left' + tkinter.Label(frame, text=t, anchor='w', justify='left' ).grid(row=row, column=1, sticky='nw') def initKw(self, kw): diff --git a/pysollib/tk/menubar.py b/pysollib/tk/menubar.py index ac1b4a09..6b5b0384 100644 --- a/pysollib/tk/menubar.py +++ b/pysollib/tk/menubar.py @@ -26,7 +26,7 @@ __all__ = ['PysolMenubarTk'] # imports import math, os, sys, re import traceback -import Tkinter, tkFileDialog +import tkinter, tkinter.filedialog # PySol imports from pysollib.mygettext import _, n_ @@ -41,17 +41,17 @@ from pysollib.settings import DEBUG from pysollib.gamedb import GI # toolkit imports -from tkconst import EVENT_HANDLED, EVENT_PROPAGATE, CURSOR_WATCH, COMPOUNDS -from tkutil import bind, after_idle -from tkwidget import MfxMessageDialog -from selectgame import SelectGameDialog, SelectGameDialogWithPreview -from soundoptionsdialog import SoundOptionsDialog -from selectcardset import SelectCardsetDialogWithPreview -from selecttile import SelectTileDialogWithPreview -from findcarddialog import connect_game_find_card_dialog, destroy_find_card_dialog -from solverdialog import connect_game_solver_dialog +from .tkconst import EVENT_HANDLED, EVENT_PROPAGATE, CURSOR_WATCH, COMPOUNDS +from .tkutil import bind, after_idle +from .tkwidget import MfxMessageDialog +from .selectgame import SelectGameDialog, SelectGameDialogWithPreview +from .soundoptionsdialog import SoundOptionsDialog +from .selectcardset import SelectCardsetDialogWithPreview +from .selecttile import SelectTileDialogWithPreview +from .findcarddialog import connect_game_find_card_dialog, destroy_find_card_dialog +from .solverdialog import connect_game_solver_dialog -from tkconst import TOOLBAR_BUTTONS +from .tkconst import TOOLBAR_BUTTONS # ************************************************************************ @@ -109,14 +109,14 @@ def createToolbarMenu(menubar, menu): # * # ************************************************************************ -class MfxMenubar(Tkinter.Menu): +class MfxMenubar(tkinter.Menu): addPath = None def __init__(self, master, **kw): self.name = kw["name"] tearoff = 0 self.n = kw["tearoff"] = int(kw.get("tearoff", tearoff)) - Tkinter.Menu.__init__(self, master, **kw) + tkinter.Menu.__init__(self, master, **kw) def labeltoname(self, label): #print label, type(label) @@ -140,7 +140,7 @@ class MfxMenubar(Tkinter.Menu): if name and self.addPath: path = str(self._w) + "." + name self.addPath(path, self, self.n, cnf.get("menu")) - Tkinter.Menu.add(self, itemType, cnf) + tkinter.Menu.add(self, itemType, cnf) self.n = self.n + 1 @@ -192,53 +192,53 @@ class PysolMenubarTk: def _createTkOpt(self): # structure to convert menu-options to Toolkit variables self.tkopt = Struct( - gameid = Tkinter.IntVar(), - gameid_popular = Tkinter.IntVar(), - comment = Tkinter.BooleanVar(), - autofaceup = Tkinter.BooleanVar(), - autodrop = Tkinter.BooleanVar(), - autodeal = Tkinter.BooleanVar(), - quickplay = Tkinter.BooleanVar(), - undo = Tkinter.BooleanVar(), - bookmarks = Tkinter.BooleanVar(), - hint = Tkinter.BooleanVar(), - shuffle = Tkinter.BooleanVar(), - highlight_piles = Tkinter.BooleanVar(), - highlight_cards = Tkinter.BooleanVar(), - highlight_samerank = Tkinter.BooleanVar(), - highlight_not_matching = Tkinter.BooleanVar(), - mahjongg_show_removed = Tkinter.BooleanVar(), - shisen_show_hint = Tkinter.BooleanVar(), - sound = Tkinter.BooleanVar(), - auto_scale = Tkinter.BooleanVar(), - cardback = Tkinter.IntVar(), - tabletile = Tkinter.IntVar(), - animations = Tkinter.IntVar(), - redeal_animation = Tkinter.BooleanVar(), - win_animation = Tkinter.BooleanVar(), - shadow = Tkinter.BooleanVar(), - shade = Tkinter.BooleanVar(), - shade_filled_stacks = Tkinter.BooleanVar(), - shrink_face_down = Tkinter.BooleanVar(), - toolbar = Tkinter.IntVar(), - toolbar_style = Tkinter.StringVar(), - toolbar_relief = Tkinter.StringVar(), - toolbar_compound = Tkinter.StringVar(), - toolbar_size = Tkinter.IntVar(), - statusbar = Tkinter.BooleanVar(), - num_cards = Tkinter.BooleanVar(), - helpbar = Tkinter.BooleanVar(), - save_games_geometry = Tkinter.BooleanVar(), - splashscreen = Tkinter.BooleanVar(), - demo_logo = Tkinter.BooleanVar(), - mouse_type = Tkinter.StringVar(), - mouse_undo = Tkinter.BooleanVar(), - negative_bottom = Tkinter.BooleanVar(), - pause = Tkinter.BooleanVar(), + gameid = tkinter.IntVar(), + gameid_popular = tkinter.IntVar(), + comment = tkinter.BooleanVar(), + autofaceup = tkinter.BooleanVar(), + autodrop = tkinter.BooleanVar(), + autodeal = tkinter.BooleanVar(), + quickplay = tkinter.BooleanVar(), + undo = tkinter.BooleanVar(), + bookmarks = tkinter.BooleanVar(), + hint = tkinter.BooleanVar(), + shuffle = tkinter.BooleanVar(), + highlight_piles = tkinter.BooleanVar(), + highlight_cards = tkinter.BooleanVar(), + highlight_samerank = tkinter.BooleanVar(), + highlight_not_matching = tkinter.BooleanVar(), + mahjongg_show_removed = tkinter.BooleanVar(), + shisen_show_hint = tkinter.BooleanVar(), + sound = tkinter.BooleanVar(), + auto_scale = tkinter.BooleanVar(), + cardback = tkinter.IntVar(), + tabletile = tkinter.IntVar(), + animations = tkinter.IntVar(), + redeal_animation = tkinter.BooleanVar(), + win_animation = tkinter.BooleanVar(), + shadow = tkinter.BooleanVar(), + shade = tkinter.BooleanVar(), + shade_filled_stacks = tkinter.BooleanVar(), + shrink_face_down = tkinter.BooleanVar(), + toolbar = tkinter.IntVar(), + toolbar_style = tkinter.StringVar(), + toolbar_relief = tkinter.StringVar(), + toolbar_compound = tkinter.StringVar(), + toolbar_size = tkinter.IntVar(), + statusbar = tkinter.BooleanVar(), + num_cards = tkinter.BooleanVar(), + helpbar = tkinter.BooleanVar(), + save_games_geometry = tkinter.BooleanVar(), + splashscreen = tkinter.BooleanVar(), + demo_logo = tkinter.BooleanVar(), + mouse_type = tkinter.StringVar(), + mouse_undo = tkinter.BooleanVar(), + negative_bottom = tkinter.BooleanVar(), + pause = tkinter.BooleanVar(), toolbar_vars = {}, ) for w in TOOLBAR_BUTTONS: - self.tkopt.toolbar_vars[w] = Tkinter.BooleanVar() + self.tkopt.toolbar_vars[w] = tkinter.BooleanVar() def _setOptions(self): tkopt, opt = self.tkopt, self.app.opt @@ -635,7 +635,7 @@ class PysolMenubarTk: def _addSelectGameMenu(self, menu): #games = map(self.app.gdb.get, self.app.gdb.getGamesIdSortedByShortName()) - games = map(self.app.gdb.get, self.app.gdb.getGamesIdSortedByName()) + games = list(map(self.app.gdb.get, self.app.gdb.getGamesIdSortedByName())) ##games = tuple(games) ###menu = MfxMenu(menu, label="Select &game") m = "Ctrl-" @@ -674,7 +674,7 @@ class PysolMenubarTk: if label is None: need_sep = 1 continue - g = filter(select_func, games) + g = list(filter(select_func, games)) if not g: continue if need_sep: @@ -686,12 +686,12 @@ class PysolMenubarTk: def _getNumGames(self, games, select_data): ngames = 0 for label, select_func in select_data: - ngames += len(filter(select_func, games)) + ngames += len(list(filter(select_func, games))) return ngames def _addSelectMahjonggGameSubMenu(self, games, menu, command, variable): select_func = lambda gi: gi.si.game_type == GI.GT_MAHJONGG - mahjongg_games = filter(select_func, games) + mahjongg_games = list(filter(select_func, games)) if len(mahjongg_games) == 0: return # @@ -715,7 +715,7 @@ class PysolMenubarTk: games[c].append(gi) else: games[c] = [gi] - games = games.items() + games = list(games.items()) games.sort() g0 = [] c0 = c1 = games[0][0] @@ -731,7 +731,7 @@ class PysolMenubarTk: def _addSelectPopularGameSubMenu(self, games, menu, command, variable): select_func = lambda gi: gi.si.game_flags & GI.GT_POPULAR - if len(filter(select_func, games)) == 0: + if len(list(filter(select_func, games))) == 0: return data = (n_("&Popular games"), select_func) self._addSelectGameSubMenu(games, menu, (data, ), @@ -764,7 +764,7 @@ class PysolMenubarTk: def _addSelectCustomGameSubMenu(self, games, menu, command, variable): submenu = MfxMenu(menu, label=n_("&Custom games")) select_func = lambda gi: gi.si.game_type == GI.GT_CUSTOM - games = filter(select_func, games) + games = list(filter(select_func, games)) self.updateGamesMenu(submenu, games) def _addSelectAllGameSubMenu(self, games, menu, command, variable): @@ -992,7 +992,7 @@ class PysolMenubarTk: idir, ifile = "", "" if not idir: idir = self.app.dn.savegames - d = tkFileDialog.Open() + d = tkinter.filedialog.Open() filename = d.show(filetypes=self.FILETYPES, defaultextension=self.DEFAULTEXTENSION, initialdir=idir, initialfile=ifile) @@ -1020,7 +1020,7 @@ class PysolMenubarTk: if not idir: idir = self.app.dn.savegames ##print self.game.filename, ifile - d = tkFileDialog.SaveAs() + d = tkinter.filedialog.SaveAs() filename = d.show(filetypes=self.FILETYPES, defaultextension=self.DEFAULTEXTENSION, initialdir=idir, initialfile=ifile) @@ -1422,7 +1422,7 @@ class PysolMenubarTk: def wizardDialog(self, edit=False): from pysollib.wizardutil import write_game, reset_wizard - from wizarddialog import WizardDialog + from .wizarddialog import WizardDialog if edit: reset_wizard(self.game) @@ -1435,7 +1435,7 @@ class PysolMenubarTk: gameid = write_game(self.app, game=self.game) else: gameid = write_game(self.app) - except Exception, err: + except Exception as err: if DEBUG: traceback.print_exc() d = MfxMessageDialog(self.top, title=_('Save game error'), @@ -1449,9 +1449,9 @@ Error while saving game. if SELECT_GAME_MENU: menu = self.__menupath[".menubar.select.customgames"][2] select_func = lambda gi: gi.si.game_type == GI.GT_CUSTOM - games = map(self.app.gdb.get, - self.app.gdb.getGamesIdSortedByName()) - games = filter(select_func, games) + games = list(map(self.app.gdb.get, + self.app.gdb.getGamesIdSortedByName())) + games = list(filter(select_func, games)) self.updateGamesMenu(menu, games) self.tkopt.gameid.set(gameid) diff --git a/pysollib/tk/playeroptionsdialog.py b/pysollib/tk/playeroptionsdialog.py index c46af7e5..ce65f02c 100644 --- a/pysollib/tk/playeroptionsdialog.py +++ b/pysollib/tk/playeroptionsdialog.py @@ -24,15 +24,15 @@ __all__ = ['PlayerOptionsDialog'] # imports -import Tkinter +import tkinter # PySol imports from pysollib.mygettext import _, n_ from pysollib.mfxutil import KwStruct, Struct # Toolkit imports -from tkwidget import MfxDialog -from tkutil import bind +from .tkwidget import MfxDialog +from .tkutil import bind # ************************************************************************ @@ -46,9 +46,9 @@ class SelectUserNameDialog(MfxDialog): top_frame, bottom_frame = self.createFrames(kw) self.createBitmaps(top_frame, kw) # - listbox = Tkinter.Listbox(top_frame) + listbox = tkinter.Listbox(top_frame) listbox.pack(side='left', fill='both', expand=True) - scrollbar = Tkinter.Scrollbar(top_frame) + scrollbar = tkinter.Scrollbar(top_frame) scrollbar.pack(side='right', fill='y') listbox.configure(yscrollcommand=scrollbar.set) scrollbar.configure(command=listbox.yview) @@ -88,30 +88,30 @@ class PlayerOptionsDialog(MfxDialog): self.createBitmaps(top_frame, kw) self.app = app # - self.update_stats_var = Tkinter.BooleanVar() + self.update_stats_var = tkinter.BooleanVar() self.update_stats_var.set(app.opt.update_player_stats != 0) - self.confirm_var = Tkinter.BooleanVar() + self.confirm_var = tkinter.BooleanVar() self.confirm_var.set(app.opt.confirm != 0) - self.win_animation_var = Tkinter.BooleanVar() + self.win_animation_var = tkinter.BooleanVar() self.win_animation_var.set(app.opt.win_animation != 0) # - frame = Tkinter.Frame(top_frame) + frame = tkinter.Frame(top_frame) frame.pack(expand=True, fill='both', padx=5, pady=10) - widget = Tkinter.Label(frame, text=_("\nPlease enter your name"), + widget = tkinter.Label(frame, text=_("\nPlease enter your name"), #justify='left', anchor='w', takefocus=0) widget.grid(row=0, column=0, columnspan=2, sticky='ew', padx=0, pady=5) w = kw.get("e_width", 30) # width in characters - self.player_var = Tkinter.Entry(frame, exportselection=1, width=w) + self.player_var = tkinter.Entry(frame, exportselection=1, width=w) self.player_var.insert(0, app.opt.player) self.player_var.grid(row=1, column=0, sticky='ew', padx=0, pady=5) - widget = Tkinter.Button(frame, text=_('Choose...'), + widget = tkinter.Button(frame, text=_('Choose...'), command=self.selectUserName) widget.grid(row=1, column=1, padx=5, pady=5) - widget = Tkinter.Checkbutton(frame, variable=self.confirm_var, + widget = tkinter.Checkbutton(frame, variable=self.confirm_var, anchor='w', text=_("Confirm quit")) widget.grid(row=2, column=0, columnspan=2, sticky='ew', padx=0, pady=5) - widget = Tkinter.Checkbutton(frame, variable=self.update_stats_var, + widget = tkinter.Checkbutton(frame, variable=self.update_stats_var, anchor='w', text=_("Update statistics and logs")) widget.grid(row=3, column=0, columnspan=2, sticky='ew', padx=0, pady=5) @@ -157,14 +157,14 @@ class PlayerOptionsDialog(MfxDialog): def playeroptionsdialog_main(args): - from tkutil import wm_withdraw + from .tkutil import wm_withdraw opt = Struct(player="Test", update_player_stats=1) app = Struct(opt=opt) - tk = Tkinter.Tk() + tk = tkinter.Tk() wm_withdraw(tk) tk.update() d = PlayerOptionsDialog(tk, "Player options", app) - print d.status, d.button, ":", d.player, d.update_stats + print(d.status, d.button, ":", d.player, d.update_stats) return 0 if __name__ == "__main__": diff --git a/pysollib/tk/progressbar.py b/pysollib/tk/progressbar.py index d984402f..79950591 100644 --- a/pysollib/tk/progressbar.py +++ b/pysollib/tk/progressbar.py @@ -24,11 +24,11 @@ __all__ = ['PysolProgressBar'] # imports -import Tkinter +import tkinter # Toolkit imports -from tkconst import EVENT_HANDLED -from tkutil import makeToplevel, setTransient +from .tkconst import EVENT_HANDLED +from .tkutil import makeToplevel, setTransient # ************************************************************************ @@ -44,23 +44,23 @@ class PysolProgressBar: self.top.wm_protocol("WM_DELETE_WINDOW", self.wmDeleteWindow) self.top.wm_group(parent) self.top.wm_resizable(False, False) - self.frame = Tkinter.Frame(self.top, relief='flat', bd=0, + self.frame = tkinter.Frame(self.top, relief='flat', bd=0, takefocus=0) - self.cframe = Tkinter.Frame(self.frame, relief='sunken', bd=1, + self.cframe = tkinter.Frame(self.frame, relief='sunken', bd=1, takefocus=0) - self.canvas = Tkinter.Canvas(self.cframe, width=width, height=height, + self.canvas = tkinter.Canvas(self.cframe, width=width, height=height, takefocus=0, bd=0, highlightthickness=0) self.scale = self.canvas.create_rectangle(-10, -10, 0, height, outline=color, fill=color) self.text = -1 if show_text: - self.text = self.canvas.create_text(0, 0, anchor=Tkinter.CENTER) + self.text = self.canvas.create_text(0, 0, anchor=tkinter.CENTER) self.cframe.grid_configure(column=0, row=0, sticky="ew") if images: - self.f1 = Tkinter.Label(self.frame, image=images[0]) + self.f1 = tkinter.Label(self.frame, image=images[0]) self.f1.grid_configure(column=0, row=0, sticky="ew", ipadx=8, ipady=4) self.cframe.grid_configure(column=1, row=0, sticky="ew", padx=8) - self.f2 = Tkinter.Label(self.frame, image=images[1]) + self.f2 = tkinter.Label(self.frame, image=images[1]) self.f2.grid_configure(column=2, row=0, sticky="ew", ipadx=8, ipady=4) self.top.config(cursor="watch") self.pack() @@ -83,7 +83,7 @@ class PysolProgressBar: self.top = None def pack(self, **kw): - self.canvas.pack(fill=Tkinter.X, expand=False) + self.canvas.pack(fill=tkinter.X, expand=False) self.frame.pack(**kw) def reset(self, percent=0): @@ -132,8 +132,8 @@ class TestProgressBar: self.progress.frame.after(30, self.update) def progressbar_main(args): - from tkutil import wm_withdraw - tk = Tkinter.Tk() + from .tkutil import wm_withdraw + tk = tkinter.Tk() wm_withdraw(tk) pb = TestProgressBar(tk) tk.mainloop() diff --git a/pysollib/tk/selectcardset.py b/pysollib/tk/selectcardset.py index e7ecf1ec..6fa8eb8c 100644 --- a/pysollib/tk/selectcardset.py +++ b/pysollib/tk/selectcardset.py @@ -25,7 +25,7 @@ __all__ = ['SelectCardsetDialogWithPreview'] # imports import os -import Tkinter +import tkinter # PySol imports from pysollib.mygettext import _, n_ @@ -34,11 +34,11 @@ from pysollib.util import CARDSET from pysollib.resource import CSI # Toolkit imports -from tkutil import loadImage -from tkwidget import MfxDialog, MfxScrolledCanvas -from tkcanvas import MfxCanvasImage -from selecttree import SelectDialogTreeLeaf, SelectDialogTreeNode -from selecttree import SelectDialogTreeData, SelectDialogTreeCanvas +from .tkutil import loadImage +from .tkwidget import MfxDialog, MfxScrolledCanvas +from .tkcanvas import MfxCanvasImage +from .selecttree import SelectDialogTreeLeaf, SelectDialogTreeNode +from .selecttree import SelectDialogTreeData, SelectDialogTreeCanvas # ************************************************************************ @@ -71,7 +71,7 @@ class SelectCardsetData(SelectDialogTreeData): self.no_contents = [ SelectCardsetLeaf(None, None, _("(no cardsets)"), key=None), ] # select_by_type = None - items = CSI.TYPE.items() + items = list(CSI.TYPE.items()) items.sort(lambda a, b: cmp(a[1], b[1])) nodes = [] for key, name in items: @@ -81,7 +81,7 @@ class SelectCardsetData(SelectDialogTreeData): select_by_type = SelectCardsetNode(None, _("by Type"), tuple(nodes), expanded=1) # select_by_style = None - items = CSI.STYLE.items() + items = list(CSI.STYLE.items()) items.sort(lambda a, b: cmp(a[1], b[1])) nodes = [] for key, name in items: @@ -92,7 +92,7 @@ class SelectCardsetData(SelectDialogTreeData): select_by_style = SelectCardsetNode(None, _("by Style"), tuple(nodes)) # select_by_nationality = None - items = CSI.NATIONALITY.items() + items = list(CSI.NATIONALITY.items()) items.sort(lambda a, b: cmp(a[1], b[1])) nodes = [] for key, name in items: @@ -103,7 +103,7 @@ class SelectCardsetData(SelectDialogTreeData): select_by_nationality = SelectCardsetNode(None, _("by Nationality"), tuple(nodes)) # select_by_date = None - items = CSI.DATE.items() + items = list(CSI.DATE.items()) items.sort(lambda a, b: cmp(a[1], b[1])) nodes = [] for key, name in items: @@ -113,7 +113,7 @@ class SelectCardsetData(SelectDialogTreeData): nodes.append(SelectCardsetNode(None, _("Uncategorized"), lambda cs: not cs.si.dates)) select_by_date = SelectCardsetNode(None, _("by Date"), tuple(nodes)) # - self.rootnodes = filter(None, ( + self.rootnodes = [_f for _f in ( SelectCardsetNode(None, _("All Cardsets"), lambda cs: 1, expanded=len(self.all_objects)<=12), SelectCardsetNode(None, _("by Size"), ( SelectCardsetNode(None, _("Tiny cardsets"), lambda cs: cs.si.size == CSI.SIZE_TINY), @@ -126,7 +126,7 @@ class SelectCardsetData(SelectDialogTreeData): select_by_style, select_by_date, select_by_nationality, - )) + ) if _f] class SelectCardsetByTypeData(SelectDialogTreeData): @@ -135,7 +135,7 @@ class SelectCardsetByTypeData(SelectDialogTreeData): self.all_objects = manager.getAllSortedByName() self.no_contents = [ SelectCardsetLeaf(None, None, _("(no cardsets)"), key=None), ] # - items = CSI.TYPE.items() + items = list(CSI.TYPE.items()) items.sort(lambda a, b: cmp(a[1], b[1])) nodes = [] for key, name in items: @@ -143,9 +143,9 @@ class SelectCardsetByTypeData(SelectDialogTreeData): nodes.append(SelectCardsetNode(None, name, lambda cs, key=key: key == cs.si.type)) select_by_type = SelectCardsetNode(None, _("by Type"), tuple(nodes), expanded=1) # - self.rootnodes = filter(None, ( + self.rootnodes = [_f for _f in ( select_by_type, - )) + ) if _f] # ************************************************************************ @@ -190,10 +190,10 @@ class SelectCardsetDialogWithPreview(MfxDialog): w1, w2 = 240, 400 else: w1, w2 = 200, 300 - paned_window = Tkinter.PanedWindow(top_frame) + paned_window = tkinter.PanedWindow(top_frame) paned_window.pack(expand=True, fill='both') - left_frame = Tkinter.Frame(paned_window) - right_frame = Tkinter.Frame(paned_window) + left_frame = tkinter.Frame(paned_window) + right_frame = tkinter.Frame(paned_window) paned_window.add(left_frame) paned_window.add(right_frame) @@ -205,9 +205,9 @@ class SelectCardsetDialogWithPreview(MfxDialog): padx=padx, pady=pady) if USE_PIL: # - var = Tkinter.DoubleVar() + var = tkinter.DoubleVar() var.set(app.opt.scale_x) - self.scale_x = Tkinter.Scale( + self.scale_x = tkinter.Scale( left_frame, label=_('Scale X:'), from_=0.5, to=4.0, resolution=0.1, orient='horizontal', variable=var, @@ -215,9 +215,9 @@ class SelectCardsetDialogWithPreview(MfxDialog): command=self._updateScale) self.scale_x.grid(row=1, column=0, sticky='ew', padx=padx, pady=pady) # - var = Tkinter.DoubleVar() + var = tkinter.DoubleVar() var.set(app.opt.scale_y) - self.scale_y = Tkinter.Scale( + self.scale_y = tkinter.Scale( left_frame, label=_('Scale Y:'), from_=0.5, to=4.0, resolution=0.1, orient='horizontal', variable=var, @@ -225,9 +225,9 @@ class SelectCardsetDialogWithPreview(MfxDialog): command=self._updateScale) self.scale_y.grid(row=2, column=0, sticky='ew', padx=padx, pady=pady) # - self.auto_scale = Tkinter.BooleanVar() + self.auto_scale = tkinter.BooleanVar() self.auto_scale.set(app.opt.auto_scale) - check = Tkinter.Checkbutton( + check = tkinter.Checkbutton( left_frame, text=_('Auto scaling'), variable=self.auto_scale, takefocus=False, @@ -236,9 +236,9 @@ class SelectCardsetDialogWithPreview(MfxDialog): check.grid(row=3, column=0, columnspan=2, sticky='w', padx=padx, pady=pady) # - self.preserve_aspect = Tkinter.BooleanVar() + self.preserve_aspect = tkinter.BooleanVar() self.preserve_aspect.set(app.opt.preserve_aspect_ratio) - self.aspect_check = Tkinter.Checkbutton( + self.aspect_check = tkinter.Checkbutton( left_frame, text=_('Preserve aspect ratio'), variable=self.preserve_aspect, takefocus=False, @@ -386,11 +386,11 @@ class CardsetInfoDialog(MfxDialog): MfxDialog.__init__(self, parent, title, kw.resizable, kw.default) top_frame, bottom_frame = self.createFrames(kw) self.createBitmaps(top_frame, kw) - frame = Tkinter.Frame(top_frame) + frame = tkinter.Frame(top_frame) frame.pack(fill="both", expand=True, padx=5, pady=10) # # - info_frame = Tkinter.LabelFrame(frame, text=_('About cardset')) + info_frame = tkinter.LabelFrame(frame, text=_('About cardset')) info_frame.grid(row=0, column=0, columnspan=2, sticky='ew', padx=0, pady=5, ipadx=5, ipady=5) styles = nationalities = year = None @@ -412,10 +412,10 @@ class CardsetInfoDialog(MfxDialog): (_('Size:'), '%d x %d' % (cardset.CARDW, cardset.CARDH)), ): if t is not None: - l = Tkinter.Label(info_frame, text=n, + l = tkinter.Label(info_frame, text=n, anchor='w', justify='left') l.grid(row=row, column=0, sticky='nw') - l = Tkinter.Label(info_frame, text=t, + l = tkinter.Label(info_frame, text=t, anchor='w', justify='left') l.grid(row=row, column=1, sticky='nw') row += 1 @@ -425,7 +425,7 @@ class CardsetInfoDialog(MfxDialog): im = choice(images) f = os.path.join(cardset.dir, cardset.backname) self.back_image = loadImage(file=f) - canvas = Tkinter.Canvas(info_frame, + canvas = tkinter.Canvas(info_frame, width=2*im.width()+30, height=im.height()+2) canvas.create_image(10, 1, image=im, anchor='nw') @@ -438,10 +438,10 @@ class CardsetInfoDialog(MfxDialog): pass ##bg = top_frame["bg"] bg = 'white' - text_w = Tkinter.Text(frame, bd=1, relief="sunken", wrap="word", + text_w = tkinter.Text(frame, bd=1, relief="sunken", wrap="word", padx=4, width=64, height=16, bg=bg) text_w.grid(row=1, column=0, sticky='nsew') - sb = Tkinter.Scrollbar(frame) + sb = tkinter.Scrollbar(frame) sb.grid(row=1, column=1, sticky='ns') text_w.configure(yscrollcommand=sb.set) sb.configure(command=text_w.yview) diff --git a/pysollib/tk/selectgame.py b/pysollib/tk/selectgame.py index 7846d0b1..620a2910 100644 --- a/pysollib/tk/selectgame.py +++ b/pysollib/tk/selectgame.py @@ -24,8 +24,8 @@ # imports import os -import Tkinter -from UserList import UserList +import tkinter +from collections import UserList # PySol imports from pysollib.mygettext import _, n_ @@ -36,10 +36,10 @@ from pysollib.help import help_html from pysollib.resource import CSI # Toolkit imports -from tkutil import unbind_destroy -from tkwidget import MfxDialog, MfxScrolledCanvas -from selecttree import SelectDialogTreeLeaf, SelectDialogTreeNode -from selecttree import SelectDialogTreeData, SelectDialogTreeCanvas +from .tkutil import unbind_destroy +from .tkwidget import MfxDialog, MfxScrolledCanvas +from .selecttree import SelectDialogTreeLeaf, SelectDialogTreeNode +from .selecttree import SelectDialogTreeData, SelectDialogTreeCanvas # ************************************************************************ @@ -81,7 +81,7 @@ class SelectGameNode(SelectDialogTreeNode): class SelectGameData(SelectDialogTreeData): def __init__(self, app): SelectDialogTreeData.__init__(self) - self.all_games_gi = map(app.gdb.get, app.gdb.getGamesIdSortedByName()) + self.all_games_gi = list(map(app.gdb.get, app.gdb.getGamesIdSortedByName())) self.no_games = [ SelectGameLeaf(None, None, _("(no games)"), None), ] # s_by_type = s_oriental = s_special = s_original = s_contrib = s_mahjongg = None @@ -94,13 +94,13 @@ class SelectGameData(SelectDialogTreeData): ): gg = [] for name, select_func in data: - if name is None or not filter(select_func, self.all_games_gi): + if name is None or not list(filter(select_func, self.all_games_gi)): continue gg.append(SelectGameNode(None, _(name), select_func)) g.append(gg) select_mahjongg_game = lambda gi: gi.si.game_type == GI.GT_MAHJONGG gg = None - if filter(select_mahjongg_game, self.all_games_gi): + if list(filter(select_mahjongg_game, self.all_games_gi)): gg = SelectGameNode(None, _("Mahjongg Games"), select_mahjongg_game) g.append(gg) @@ -124,7 +124,7 @@ class SelectGameData(SelectDialogTreeData): s_by_compatibility, gg = None, [] for name, games in GI.GAMES_BY_COMPATIBILITY: select_func = lambda gi, games=games: gi.id in games - if name is None or not filter(select_func, self.all_games_gi): + if name is None or not list(filter(select_func, self.all_games_gi)): continue gg.append(SelectGameNode(None, name, select_func)) if 1 and gg: @@ -135,7 +135,7 @@ class SelectGameData(SelectDialogTreeData): s_by_pysol_version, gg = None, [] for name, games in GI.GAMES_BY_PYSOL_VERSION: select_func = lambda gi, games=games: gi.id in games - if name is None or not filter(select_func, self.all_games_gi): + if name is None or not list(filter(select_func, self.all_games_gi)): continue name = _("New games in v. ") + name gg.append(SelectGameNode(None, name, select_func)) @@ -145,7 +145,7 @@ class SelectGameData(SelectDialogTreeData): s_by_inventors, gg = None, [] for name, games in GI.GAMES_BY_INVENTORS: select_func = lambda gi, games=games: gi.id in games - if name is None or not filter(select_func, self.all_games_gi): + if name is None or not list(filter(select_func, self.all_games_gi)): continue gg.append(SelectGameNode(None, name, select_func)) if 1 and gg: @@ -154,7 +154,7 @@ class SelectGameData(SelectDialogTreeData): # ul_alternate_names = UserList(list(app.gdb.getGamesTuplesSortedByAlternateName())) # - self.rootnodes = filter(None, ( + self.rootnodes = [_f for _f in ( SelectGameNode(None, _("All Games"), None), SelectGameNode(None, _("Alternate Names"), ul_alternate_names), SelectGameNode(None, _("Popular Games"), @@ -240,7 +240,7 @@ class SelectGameData(SelectDialogTreeData): )), s_original, s_contrib, - )) + ) if _f] # ************************************************************************ @@ -354,10 +354,10 @@ class SelectGameDialogWithPreview(SelectGameDialog): ##padx, pady = kw.padx, kw.pady padx, pady = kw.padx/2, kw.pady/2 # PanedWindow - paned_window = Tkinter.PanedWindow(top_frame) + paned_window = tkinter.PanedWindow(top_frame) paned_window.pack(expand=True, fill='both') - left_frame = Tkinter.Frame(paned_window) - right_frame = Tkinter.Frame(paned_window) + left_frame = tkinter.Frame(paned_window) + right_frame = tkinter.Frame(paned_window) paned_window.add(left_frame) paned_window.add(right_frame) # Tree @@ -366,8 +366,8 @@ class SelectGameDialogWithPreview(SelectGameDialog): default=kw.default, font=font, width=w1) self.tree.frame.pack(padx=padx, pady=pady, expand=True, fill='both') # LabelFrame - info_frame = Tkinter.LabelFrame(right_frame, text=_('About game')) - stats_frame = Tkinter.LabelFrame(right_frame, text=_('Statistics')) + info_frame = tkinter.LabelFrame(right_frame, text=_('About game')) + stats_frame = tkinter.LabelFrame(right_frame, text=_('Statistics')) info_frame.grid(row=0, column=0, padx=padx, pady=pady, ipadx=padx, ipady=pady, sticky='nws') stats_frame.grid(row=0, column=1, padx=padx, pady=pady, @@ -391,9 +391,9 @@ class SelectGameDialogWithPreview(SelectGameDialog): ('moves', _('Moves:'), stats_frame, 4), ('percent', _('% won:'), stats_frame, 5), ): - title_label = Tkinter.Label(f, text=t, justify='left', anchor='w') + title_label = tkinter.Label(f, text=t, justify='left', anchor='w') title_label.grid(row=row, column=0, sticky='nw') - text_label = Tkinter.Label(f, justify='left', anchor='w') + text_label = tkinter.Label(f, justify='left', anchor='w') text_label.grid(row=row, column=1, sticky='nw') self.info_labels[n] = (title_label, text_label) ##info_frame.columnconfigure(1, weight=1) diff --git a/pysollib/tk/selecttile.py b/pysollib/tk/selecttile.py index d0528a98..84e3925c 100644 --- a/pysollib/tk/selecttile.py +++ b/pysollib/tk/selecttile.py @@ -23,16 +23,16 @@ # imports -import Tkinter, tkColorChooser +import tkinter, tkinter.colorchooser # PySol imports from pysollib.mygettext import _, n_ from pysollib.mfxutil import KwStruct # Toolkit imports -from tkwidget import MfxDialog, MfxScrolledCanvas -from selecttree import SelectDialogTreeLeaf, SelectDialogTreeNode -from selecttree import SelectDialogTreeData, SelectDialogTreeCanvas +from .tkwidget import MfxDialog, MfxScrolledCanvas +from .selecttree import SelectDialogTreeLeaf, SelectDialogTreeNode +from .selecttree import SelectDialogTreeData, SelectDialogTreeCanvas # ************************************************************************ @@ -118,7 +118,7 @@ class SelectTileDialogWithPreview(MfxDialog): w1, w2 = 200, 300 font = app.getFont("default") padx, pady = 4, 4 - frame = Tkinter.Frame(top_frame) + frame = tkinter.Frame(top_frame) frame.pack(fill='both', expand=True, padx=kw.padx-padx, pady=kw.pady-pady) self.tree = self.Tree_Class(self, frame, key=key, @@ -157,17 +157,17 @@ class SelectTileDialogWithPreview(MfxDialog): def mDone(self, button): if button == 0: # "OK" or double click - if isinstance(self.tree.selection_key, basestring): + if isinstance(self.tree.selection_key, str): self.key = str(self.tree.selection_key) else: self.key = self.tree.selection_key self.tree.n_expansions = 1 # save xyview in any case if button == 1: # "Solid color..." try: - c = tkColorChooser.askcolor(master=self.top, + c = tkinter.colorchooser.askcolor(master=self.top, initialcolor=self.table_color, title=_("Select table color")) - except Tkinter.TclError: + except tkinter.TclError: pass else: if c and c[1]: @@ -185,7 +185,7 @@ class SelectTileDialogWithPreview(MfxDialog): return canvas = self.preview.canvas canvas.deleteAllItems() - if isinstance(key, basestring): + if isinstance(key, str): # solid color canvas.config(bg=key) canvas.setTile(None) diff --git a/pysollib/tk/selecttree.py b/pysollib/tk/selecttree.py index 0ce9dd9b..47aeafaf 100644 --- a/pysollib/tk/selecttree.py +++ b/pysollib/tk/selecttree.py @@ -24,10 +24,10 @@ __all__ = ['SelectDialogTreeData'] # imports -import tkFont +import tkinter.font # Toolkit imports -from tktree import MfxTreeLeaf, MfxTreeNode, MfxTreeInCanvas +from .tktree import MfxTreeLeaf, MfxTreeNode, MfxTreeInCanvas # ************************************************************************ @@ -110,7 +110,7 @@ class SelectDialogTreeCanvas(MfxTreeInCanvas): self.style.height = 14 # height of symbol if font: self.style.font = font - f = tkFont.Font(parent, font) + f = tkinter.font.Font(parent, font) h = f.metrics()["linespace"] self.style.disty = max(self.style.width, h) diff --git a/pysollib/tk/solverdialog.py b/pysollib/tk/solverdialog.py index 1cd5bd4a..887cfc86 100644 --- a/pysollib/tk/solverdialog.py +++ b/pysollib/tk/solverdialog.py @@ -30,7 +30,7 @@ __all__ = [ ] # imports -import Tkinter +import tkinter ##import traceback # PySol imports @@ -39,8 +39,8 @@ from pysollib.mfxutil import KwStruct from pysollib.settings import TITLE # Toolkit imports -from tkconst import EVENT_HANDLED -from tkwidget import MfxDialog +from .tkconst import EVENT_HANDLED +from .tkwidget import MfxDialog # ************************************************************************ @@ -68,13 +68,13 @@ class SolverDialog(MfxDialog): self.games = {} # key: gamename; value: gameid # - frame = Tkinter.Frame(top_frame) + frame = tkinter.Frame(top_frame) frame.pack(expand=True, fill='both', padx=4, pady=4) frame.columnconfigure(1, weight=1) # row = 0 - Tkinter.Label(frame, text=_('Game:'), anchor='w' + tkinter.Label(frame, text=_('Game:'), anchor='w' ).grid(row=row, column=0, sticky='ew', padx=2, pady=2) games = app.getGamesForSolver() gamenames = [''] @@ -84,83 +84,83 @@ class SolverDialog(MfxDialog): self.games[name] = id gamenames.sort() self.gamenames = gamenames - self.games_var = var = Tkinter.StringVar() - om = Tkinter.OptionMenu(frame, var, command=self.gameSelected, + self.games_var = var = tkinter.StringVar() + om = tkinter.OptionMenu(frame, var, command=self.gameSelected, *gamenames) om.grid(row=row, column=1, sticky='ew', padx=2, pady=2) n = len(gamenames) cb_max = int(self.top.winfo_screenheight()/23) cb_max = n / (n/cb_max+1) - for i in xrange(cb_max, n, cb_max): + for i in range(cb_max, n, cb_max): om['menu'].entryconfig(i, columnbreak=True) # row += 1 - Tkinter.Label(frame, text=_('Preset:'), anchor='w' + tkinter.Label(frame, text=_('Preset:'), anchor='w' ).grid(row=row, column=0, sticky='ew', padx=2, pady=2) presets = app.opt.solver_presets self.presets = presets - self.preset_var = var = Tkinter.StringVar() + self.preset_var = var = tkinter.StringVar() var.set('none') - om = Tkinter.OptionMenu(frame, var, *presets) + om = tkinter.OptionMenu(frame, var, *presets) om.grid(row=row, column=1, sticky='ew', padx=2, pady=2) # row += 1 - self.max_iters_var = Tkinter.IntVar() + self.max_iters_var = tkinter.IntVar() self.max_iters_var.set(10e4) - Tkinter.Label(frame, text=_('Max iterations:'), anchor='w' + tkinter.Label(frame, text=_('Max iterations:'), anchor='w' ).grid(row=row, column=0, sticky='ew', padx=2, pady=2) - spin = Tkinter.Spinbox(frame, bg='white', from_=1000, to=10e6, + spin = tkinter.Spinbox(frame, bg='white', from_=1000, to=10e6, increment=1000, textvariable=self.max_iters_var) spin.grid(row=row, column=1, sticky='w', padx=2, pady=2) # row += 1 - self.max_depth_var = Tkinter.IntVar() + self.max_depth_var = tkinter.IntVar() self.max_depth_var.set(1000) - Tkinter.Label(frame, text=_('Max depth:'), anchor='w' + tkinter.Label(frame, text=_('Max depth:'), anchor='w' ).grid(row=row, column=0, sticky='ew', padx=2, pady=2) - spin = Tkinter.Spinbox(frame, bg='white', from_=100, to=10000, + spin = tkinter.Spinbox(frame, bg='white', from_=100, to=10000, increment=100, textvariable=self.max_depth_var) spin.grid(row=row, column=1, sticky='w', padx=2, pady=2) # row += 1 - self.progress_var = Tkinter.BooleanVar() + self.progress_var = tkinter.BooleanVar() self.progress_var.set(True) - w = Tkinter.Checkbutton(frame, variable=self.progress_var, + w = tkinter.Checkbutton(frame, variable=self.progress_var, text=_('Show progress'), anchor='w') w.grid(row=row, column=0, columnspan=2, sticky='ew', padx=2, pady=2) # - label_frame = Tkinter.LabelFrame(top_frame, text=_('Progress')) + label_frame = tkinter.LabelFrame(top_frame, text=_('Progress')) label_frame.pack(expand=True, fill='both', padx=6, pady=2) #label_frame.columnconfigure(0, weight=1) label_frame.columnconfigure(1, weight=1) # frow = 0 - Tkinter.Label(label_frame, text=_('Iteration:'), anchor='w' + tkinter.Label(label_frame, text=_('Iteration:'), anchor='w' ).grid(row=frow, column=0, sticky='ew', padx=4, pady=2) - lb = Tkinter.Label(label_frame, anchor='w') + lb = tkinter.Label(label_frame, anchor='w') lb.grid(row=frow, column=1, sticky='ew', padx=4, pady=2) self.iter_label = lb frow += 1 - Tkinter.Label(label_frame, text=_('Depth:'), anchor='w' + tkinter.Label(label_frame, text=_('Depth:'), anchor='w' ).grid(row=frow, column=0, sticky='ew', padx=4, pady=2) - lb = Tkinter.Label(label_frame, anchor='w') + lb = tkinter.Label(label_frame, anchor='w') lb.grid(row=frow, column=1, sticky='ew', padx=4, pady=2) self.depth_label = lb frow += 1 - Tkinter.Label(label_frame, text=_('Stored-States:'), anchor='w' + tkinter.Label(label_frame, text=_('Stored-States:'), anchor='w' ).grid(row=frow, column=0, sticky='ew', padx=4, pady=2) - lb = Tkinter.Label(label_frame, anchor='w') + lb = tkinter.Label(label_frame, anchor='w') lb.grid(row=frow, column=1, sticky='ew', padx=4, pady=2) self.states_label = lb # - lb = Tkinter.Label(top_frame, anchor='w') + lb = tkinter.Label(top_frame, anchor='w') lb.pack(expand=True, fill='x', padx=6, pady=4) self.result_label = lb diff --git a/pysollib/tk/soundoptionsdialog.py b/pysollib/tk/soundoptionsdialog.py index f66011ac..48004de0 100644 --- a/pysollib/tk/soundoptionsdialog.py +++ b/pysollib/tk/soundoptionsdialog.py @@ -25,7 +25,7 @@ __all__ = ['SoundOptionsDialog'] # imports import os -import Tkinter +import tkinter # PySol imports from pysollib.mygettext import _, n_ @@ -34,8 +34,8 @@ from pysollib.settings import TITLE from pysollib.pysolaudio import pysolsoundserver # Toolkit imports -from tkconst import EVENT_HANDLED -from tkwidget import MfxDialog, MfxMessageDialog +from .tkconst import EVENT_HANDLED +from .tkwidget import MfxDialog, MfxMessageDialog # ************************************************************************ # * @@ -51,74 +51,74 @@ class SoundOptionsDialog(MfxDialog): self.createBitmaps(top_frame, kw) # self.saved_opt = app.opt.copy() - self.sound = Tkinter.BooleanVar() + self.sound = tkinter.BooleanVar() self.sound.set(app.opt.sound != 0) - self.sound_mode = Tkinter.BooleanVar() + self.sound_mode = tkinter.BooleanVar() self.sound_mode.set(app.opt.sound_mode != 0) - self.sample_volume = Tkinter.IntVar() + self.sample_volume = tkinter.IntVar() self.sample_volume.set(app.opt.sound_sample_volume) - self.music_volume = Tkinter.IntVar() + self.music_volume = tkinter.IntVar() self.music_volume.set(app.opt.sound_music_volume) self.samples = [ - ('areyousure', _('Are You Sure'), Tkinter.BooleanVar()), + ('areyousure', _('Are You Sure'), tkinter.BooleanVar()), - ('deal', _('Deal'), Tkinter.BooleanVar()), - ('dealwaste', _('Deal waste'), Tkinter.BooleanVar()), + ('deal', _('Deal'), tkinter.BooleanVar()), + ('dealwaste', _('Deal waste'), tkinter.BooleanVar()), - ('turnwaste', _('Turn waste'), Tkinter.BooleanVar()), - ('startdrag', _('Start drag'), Tkinter.BooleanVar()), + ('turnwaste', _('Turn waste'), tkinter.BooleanVar()), + ('startdrag', _('Start drag'), tkinter.BooleanVar()), - ('drop', _('Drop'), Tkinter.BooleanVar()), - ('droppair', _('Drop pair'), Tkinter.BooleanVar()), - ('autodrop', _('Auto drop'), Tkinter.BooleanVar()), + ('drop', _('Drop'), tkinter.BooleanVar()), + ('droppair', _('Drop pair'), tkinter.BooleanVar()), + ('autodrop', _('Auto drop'), tkinter.BooleanVar()), - ('flip', _('Flip'), Tkinter.BooleanVar()), - ('autoflip', _('Auto flip'), Tkinter.BooleanVar()), - ('move', _('Move'), Tkinter.BooleanVar()), - ('nomove', _('No move'), Tkinter.BooleanVar()), + ('flip', _('Flip'), tkinter.BooleanVar()), + ('autoflip', _('Auto flip'), tkinter.BooleanVar()), + ('move', _('Move'), tkinter.BooleanVar()), + ('nomove', _('No move'), tkinter.BooleanVar()), - ('undo', _('Undo'), Tkinter.BooleanVar()), - ('redo', _('Redo'), Tkinter.BooleanVar()), + ('undo', _('Undo'), tkinter.BooleanVar()), + ('redo', _('Redo'), tkinter.BooleanVar()), - ('autopilotlost', _('Autopilot lost'), Tkinter.BooleanVar()), - ('autopilotwon', _('Autopilot won'), Tkinter.BooleanVar()), + ('autopilotlost', _('Autopilot lost'), tkinter.BooleanVar()), + ('autopilotwon', _('Autopilot won'), tkinter.BooleanVar()), - ('gamefinished', _('Game finished'), Tkinter.BooleanVar()), - ('gamelost', _('Game lost'), Tkinter.BooleanVar()), - ('gamewon', _('Game won'), Tkinter.BooleanVar()), - ('gameperfect', _('Perfect game'), Tkinter.BooleanVar()), + ('gamefinished', _('Game finished'), tkinter.BooleanVar()), + ('gamelost', _('Game lost'), tkinter.BooleanVar()), + ('gamewon', _('Game won'), tkinter.BooleanVar()), + ('gameperfect', _('Perfect game'), tkinter.BooleanVar()), ] # - frame = Tkinter.Frame(top_frame) + frame = tkinter.Frame(top_frame) frame.pack(expand=True, fill='both', padx=5, pady=5) frame.columnconfigure(1, weight=1) # row = 0 - w = Tkinter.Checkbutton(frame, variable=self.sound, + w = tkinter.Checkbutton(frame, variable=self.sound, text=_("Sound enabled"), anchor='w') w.grid(row=row, column=0, columnspan=2, sticky='ew') # if os.name == "nt" and pysolsoundserver: row += 1 - w = Tkinter.Checkbutton(frame, variable=self.sound_mode, + w = tkinter.Checkbutton(frame, variable=self.sound_mode, text=_("Use DirectX for sound playing"), command=self.mOptSoundDirectX, anchor='w') w.grid(row=row, column=0, columnspan=2, sticky='ew') # if app.audio.CAN_PLAY_MUSIC: # and app.startup_opt.sound_mode > 0: row += 1 - w = Tkinter.Label(frame, text=_('Sample volume:')) + w = tkinter.Label(frame, text=_('Sample volume:')) w.grid(row=row, column=0, sticky='w', padx=5) - w = Tkinter.Scale(frame, from_=0, to=128, resolution=1, + w = tkinter.Scale(frame, from_=0, to=128, resolution=1, orient='horizontal', takefocus=0, length="3i", #label=_('Sample volume'), variable=self.sample_volume) w.grid(row=row, column=1, sticky='ew', padx=5) row += 1 - w = Tkinter.Label(frame, text=_('Music volume:')) + w = tkinter.Label(frame, text=_('Music volume:')) w.grid(row=row, column=0, sticky='w', padx=5) - w = Tkinter.Scale(frame, from_=0, to=128, resolution=1, + w = tkinter.Scale(frame, from_=0, to=128, resolution=1, orient='horizontal', takefocus=0, length="3i", #label=_('Music volume'), variable=self.music_volume) @@ -128,7 +128,7 @@ class SoundOptionsDialog(MfxDialog): # remove "Apply" button kw.strings[1] = None # - frame = Tkinter.LabelFrame(top_frame, text=_('Enable samles'), + frame = tkinter.LabelFrame(top_frame, text=_('Enable samles'), padx=5, pady=5) frame.pack(expand=True, fill='both', padx=5, pady=5) frame.columnconfigure(0, weight=1) @@ -138,7 +138,7 @@ class SoundOptionsDialog(MfxDialog): col = 0 for n, t, v in self.samples: v.set(app.opt.sound_samples[n]) - w = Tkinter.Checkbutton(frame, text=t, anchor='w', variable=v) + w = tkinter.Checkbutton(frame, text=t, anchor='w', variable=v) w.grid(row=row, column=col, sticky='ew') if col == 1: col = 0 diff --git a/pysollib/tk/statusbar.py b/pysollib/tk/statusbar.py index c433022b..26adfef5 100644 --- a/pysollib/tk/statusbar.py +++ b/pysollib/tk/statusbar.py @@ -25,19 +25,19 @@ __all__ = ['PysolStatusbar', 'HelpStatusbar'] # imports -import os, sys, Tkinter +import os, sys, tkinter if __name__ == '__main__': d = os.path.abspath(os.path.join(sys.path[0], os.pardir, os.pardir)) sys.path.append(d) import gettext - gettext.install('pysol', d, unicode=True) + gettext.install('pysol', d, str=True) # PySol imports from pysollib.mygettext import _, n_ # Toolkit imports -from tkwidget import MfxTooltip +from .tkwidget import MfxTooltip from pysollib.settings import WIN_SYSTEM @@ -59,7 +59,7 @@ class MfxStatusbar: # self.padx = 1 self.label_relief = 'sunken' - self.frame = Tkinter.Frame(self.top, bd=1) + self.frame = tkinter.Frame(self.top, bd=1) self.frame.grid(row=self._row, column=self._column, columnspan=self._columnspan, sticky='ew', padx=1, pady=1) @@ -73,7 +73,7 @@ class MfxStatusbar: # util def _createLabel(self, name, expand=False, width=0, tooltip=None): - label = Tkinter.Label(self.frame, width=width, + label = tkinter.Label(self.frame, width=width, relief=self.label_relief, bd=1, highlightbackground='black' ) @@ -97,9 +97,9 @@ class MfxStatusbar: # def updateText(self, **kw): - for k, v in kw.items(): + for k, v in list(kw.items()): label = getattr(self, k + '_label') - text = unicode(v) + text = str(v) width = label['width'] if width and len(text) > width: label['width'] = len(text) @@ -188,7 +188,7 @@ class TestStatusbar(PysolStatusbar): self.updateText(info='Some info text.') def statusbar_main(args): - tk = Tkinter.Tk() + tk = tkinter.Tk() statusbar = TestStatusbar(tk, args) tk.mainloop() return 0 diff --git a/pysollib/tk/tabpage.py b/pysollib/tk/tabpage.py index 09ec1e0b..e9aa7834 100644 --- a/pysollib/tk/tabpage.py +++ b/pysollib/tk/tabpage.py @@ -24,7 +24,7 @@ a couple of classes for implementing partial tabbed-page like behaviour """ -from Tkinter import * +from tkinter import * MYRIDGE, MYRAISED = RAISED, RIDGE #MYRIDGE, MYRAISED = RIDGE, RAISED @@ -68,12 +68,12 @@ class TabPageSet(Frame): def ChangePage(self,pageName=None): if pageName: - if pageName in self.pages.keys(): + if pageName in list(self.pages.keys()): self.activePage.set(pageName) else: - raise InvalidTabPage, 'Invalid TabPage Name' + raise InvalidTabPage('Invalid TabPage Name') ## pop up the active 'tab' only - for page in self.pages.keys(): + for page in list(self.pages.keys()): self.pages[page]['tab'].config(relief=MYRIDGE) self.pages[self.GetActivePage()]['tab'].config(relief=MYRAISED) ## switch page @@ -83,8 +83,8 @@ class TabPageSet(Frame): return self.activePage.get() def AddPage(self,pageName): - if pageName in self.pages.keys(): - raise AlreadyExists, 'TabPage Name Already Exists' + if pageName in list(self.pages.keys()): + raise AlreadyExists('TabPage Name Already Exists') self.pages[pageName]={ 'tab': PageTab(self.tabBar), 'page': Frame(self,borderwidth=2,relief=RAISED) @@ -103,8 +103,8 @@ class TabPageSet(Frame): self.ChangePage() def RemovePage(self,pageName): - if not pageName in self.pages.keys(): - raise InvalidTabPage, 'Invalid TabPage Name' + if not pageName in list(self.pages.keys()): + raise InvalidTabPage('Invalid TabPage Name') self.pages[pageName]['tab'].pack_forget() self.pages[pageName]['page'].grid_forget() self.pages[pageName]['tab'].destroy() diff --git a/pysollib/tk/timeoutsdialog.py b/pysollib/tk/timeoutsdialog.py index b9833830..7f352b9b 100644 --- a/pysollib/tk/timeoutsdialog.py +++ b/pysollib/tk/timeoutsdialog.py @@ -24,14 +24,14 @@ __all__ = ['TimeoutsDialog'] # imports -import Tkinter +import tkinter # PySol imports from pysollib.mygettext import _, n_ from pysollib.mfxutil import KwStruct # Toolkit imports -from tkwidget import MfxDialog +from .tkwidget import MfxDialog # ************************************************************************ # * @@ -44,21 +44,21 @@ class TimeoutsDialog(MfxDialog): top_frame, bottom_frame = self.createFrames(kw) #self.createBitmaps(top_frame, kw) - frame = Tkinter.Frame(top_frame) + frame = tkinter.Frame(top_frame) frame.pack(expand=True, fill='both', padx=5, pady=10) frame.columnconfigure(0, weight=1) - self.demo_sleep_var = Tkinter.DoubleVar() + self.demo_sleep_var = tkinter.DoubleVar() self.demo_sleep_var.set(app.opt.timeouts['demo']) - self.hint_sleep_var = Tkinter.DoubleVar() + self.hint_sleep_var = tkinter.DoubleVar() self.hint_sleep_var.set(app.opt.timeouts['hint']) - self.raise_card_sleep_var = Tkinter.DoubleVar() + self.raise_card_sleep_var = tkinter.DoubleVar() self.raise_card_sleep_var.set(app.opt.timeouts['raise_card']) - self.highlight_piles_sleep_var = Tkinter.DoubleVar() + self.highlight_piles_sleep_var = tkinter.DoubleVar() self.highlight_piles_sleep_var.set(app.opt.timeouts['highlight_piles']) - self.highlight_cards_sleep_var = Tkinter.DoubleVar() + self.highlight_cards_sleep_var = tkinter.DoubleVar() self.highlight_cards_sleep_var.set(app.opt.timeouts['highlight_cards']) - self.highlight_samerank_sleep_var = Tkinter.DoubleVar() + self.highlight_samerank_sleep_var = tkinter.DoubleVar() self.highlight_samerank_sleep_var.set(app.opt.timeouts['highlight_samerank']) # #Tkinter.Label(frame, text='Set delays in seconds').grid(row=0, column=0, columnspan=2) @@ -70,9 +70,9 @@ class TimeoutsDialog(MfxDialog): (_('Highlight cards:'), self.highlight_cards_sleep_var), (_('Highlight same rank:'), self.highlight_samerank_sleep_var), ): - Tkinter.Label(frame, text=title, anchor='w' + tkinter.Label(frame, text=title, anchor='w' ).grid(row=row, column=0, sticky='we') - widget = Tkinter.Scale(frame, from_=0.2, to=9.9, + widget = tkinter.Scale(frame, from_=0.2, to=9.9, resolution=0.1, orient='horizontal', length="3i", variable=var, takefocus=0) widget.grid(row=row, column=1) diff --git a/pysollib/tk/tkcanvas.py b/pysollib/tk/tkcanvas.py index 9ce6e599..ae1ca306 100644 --- a/pysollib/tk/tkcanvas.py +++ b/pysollib/tk/tkcanvas.py @@ -29,13 +29,15 @@ __all__ = ['MfxCanvasGroup', 'MfxCanvas'] # imports -import Tkinter, Canvas +import tkinter + +import pysollib.Py2Canvas as Canvas # PySol imports from pysollib.mfxutil import Image, ImageTk # Toolkit imports -from tkutil import bind, unbind_destroy, loadImage +from .tkutil import bind, unbind_destroy, loadImage # ************************************************************************ @@ -117,9 +119,9 @@ class MfxCanvasText(Canvas.CanvasText): # * canvas # ************************************************************************ -class MfxCanvas(Tkinter.Canvas): +class MfxCanvas(tkinter.Canvas): def __init__(self, *args, **kw): - Tkinter.Canvas.__init__(self, *args, **kw) + tkinter.Canvas.__init__(self, *args, **kw) self.preview = 0 self.busy = False # this is also used by lib-tk/Canvas.py @@ -207,11 +209,11 @@ class MfxCanvas(Tkinter.Canvas): # def _x_create(self, itemType, *args, **kw): - return Tkinter.Canvas._create(self, itemType, args, kw) + return tkinter.Canvas._create(self, itemType, args, kw) def _create(self, itemType, args, kw): ##print "_create:", itemType, args, kw - id = Tkinter.Canvas._create(self, itemType, args, kw) + id = tkinter.Canvas._create(self, itemType, args, kw) if self.__tops: self.tk.call(self._w, "lower", id, self.__tops[0]) return id @@ -262,7 +264,7 @@ class MfxCanvas(Tkinter.Canvas): # delete all CanvasItems, but keep the background and top tiles def deleteAllItems(self): self._text_items = [] - for id in self.items.keys(): + for id in list(self.items.keys()): assert id not in self.__tiles # because the tile is created by id unbind_destroy(self.items[id]) self.items[id].delete() @@ -337,7 +339,7 @@ class MfxCanvas(Tkinter.Canvas): try: if image and isinstance(image, str): image = loadImage(file=image) - except Tkinter.TclError: + except tkinter.TclError: return 0 if len(self.__tops) == 1 and image is self.__tops[0]: return 1 @@ -369,11 +371,11 @@ class MfxCanvas(Tkinter.Canvas): # def hideAllItems(self): - for item in self.items.values(): + for item in list(self.items.values()): item.config(state='hidden') def showAllItems(self): - for item in self.items.values(): + for item in list(self.items.values()): item.config(state='normal') @@ -389,7 +391,7 @@ class MfxCanvas(Tkinter.Canvas): return funcid def _substitute(self, *args): - e = Tkinter.Event() + e = tkinter.Event() try: # Tk changed behavior in 8.4.2, returning "??" rather more often. e.x = int(args[0]) diff --git a/pysollib/tk/tkconst.py b/pysollib/tk/tkconst.py index e844ccee..feffb597 100644 --- a/pysollib/tk/tkconst.py +++ b/pysollib/tk/tkconst.py @@ -39,7 +39,7 @@ __all__ = ['EVENT_HANDLED', ] # imports -import Tkinter +import tkinter from pysollib.mygettext import _, n_ @@ -54,23 +54,23 @@ CURSOR_DRAG = "hand1" CURSOR_WATCH = "watch" CURSOR_DOWN_ARROW = 'sb_down_arrow' -ANCHOR_CENTER = Tkinter.CENTER -ANCHOR_N = Tkinter.N -ANCHOR_NW = Tkinter.NW -ANCHOR_NE = Tkinter.NE -ANCHOR_S = Tkinter.S -ANCHOR_SW = Tkinter.SW -ANCHOR_SE = Tkinter.SE -ANCHOR_W = Tkinter.W -ANCHOR_E = Tkinter.E +ANCHOR_CENTER = tkinter.CENTER +ANCHOR_N = tkinter.N +ANCHOR_NW = tkinter.NW +ANCHOR_NE = tkinter.NE +ANCHOR_S = tkinter.S +ANCHOR_SW = tkinter.SW +ANCHOR_SE = tkinter.SE +ANCHOR_W = tkinter.W +ANCHOR_E = tkinter.E COMPOUNDS = ( ##(Tkinter.BOTTOM, 'bottom'), ##(Tkinter.CENTER, 'center'), ##(Tkinter.RIGHT, 'right'), - (Tkinter.NONE, n_('Icons only')), - (Tkinter.TOP, n_('Text below icons')), - (Tkinter.LEFT, n_('Text beside icons')), + (tkinter.NONE, n_('Icons only')), + (tkinter.TOP, n_('Text below icons')), + (tkinter.LEFT, n_('Text beside icons')), ('text', n_('Text only')), ) diff --git a/pysollib/tk/tkhtml.py b/pysollib/tk/tkhtml.py index f0b36553..fce7e115 100644 --- a/pysollib/tk/tkhtml.py +++ b/pysollib/tk/tkhtml.py @@ -26,13 +26,13 @@ __all__ = ['HTMLViewer'] # imports import os, sys import htmllib, formatter -import Tkinter +import tkinter if __name__ == '__main__': d = os.path.abspath(os.path.join(sys.path[0], '..', '..')) sys.path.append(d) import gettext - gettext.install('pysol', d, unicode=True) + gettext.install('pysol', d, str=True) # PySol imports from pysollib.mygettext import _, n_ @@ -40,9 +40,9 @@ from pysollib.mfxutil import Struct, openURL from pysollib.settings import TITLE # Toolkit imports -from tkutil import bind, unbind_destroy -from tkwidget import MfxMessageDialog -from statusbar import HtmlStatusbar +from .tkutil import bind, unbind_destroy +from .tkwidget import MfxMessageDialog +from .statusbar import HtmlStatusbar REMOTE_PROTOCOLS = ("ftp:", "gopher:", "http:", "mailto:", "news:", "telnet:") @@ -82,7 +82,7 @@ class tkHTMLWriter(formatter.NullWriter): } self.text.config(cursor=self.viewer.defcursor, font=font) - for f in self.fontmap.keys(): + for f in list(self.fontmap.keys()): self.text.tag_config(f, font=self.fontmap[f]) self.anchor = None @@ -238,30 +238,30 @@ class HTMLViewer: # create buttons button_width = 8 - self.homeButton = Tkinter.Button(parent, text=_("Index"), + self.homeButton = tkinter.Button(parent, text=_("Index"), width=button_width, command=self.goHome) self.homeButton.grid(row=0, column=0, sticky='w') - self.backButton = Tkinter.Button(parent, text=_("Back"), + self.backButton = tkinter.Button(parent, text=_("Back"), width=button_width, command=self.goBack) self.backButton.grid(row=0, column=1, sticky='w') - self.forwardButton = Tkinter.Button(parent, text=_("Forward"), + self.forwardButton = tkinter.Button(parent, text=_("Forward"), width=button_width, command=self.goForward) self.forwardButton.grid(row=0, column=2, sticky='w') - self.closeButton = Tkinter.Button(parent, text=_("Close"), + self.closeButton = tkinter.Button(parent, text=_("Close"), width=button_width, command=self.destroy) self.closeButton.grid(row=0, column=3, sticky='e') # create text widget - text_frame = Tkinter.Frame(parent) + text_frame = tkinter.Frame(parent) text_frame.grid(row=1, column=0, columnspan=4, sticky='nsew') text_frame.grid_propagate(False) - vbar = Tkinter.Scrollbar(text_frame) + vbar = tkinter.Scrollbar(text_frame) vbar.pack(side='right', fill='y') - self.text = Tkinter.Text(text_frame, + self.text = tkinter.Text(text_frame, fg='black', bg='white', bd=1, relief='sunken', cursor=self.defcursor, @@ -277,7 +277,7 @@ class HTMLViewer: parent.rowconfigure(1, weight=1) # load images - for name, fn in self.symbols_fn.items(): + for name, fn in list(self.symbols_fn.items()): self.symbols_img[name] = self.getImage(fn) self.initBindings() @@ -327,8 +327,8 @@ class HTMLViewer: if baseurl is None: baseurl = self.url if 0: - import urllib - url = urllib.pathname2url(url) + import urllib.request, urllib.parse, urllib.error + url = urllib.request.pathname2url(url) if relpath and self.url: url = urllib.basejoin(baseurl, url) else: @@ -388,14 +388,14 @@ to open the following URL: try: file = None if 0: - import urllib - file = urllib.urlopen(url) + import urllib.request, urllib.parse, urllib.error + file = urllib.request.urlopen(url) else: file, url = self.openfile(url) data = file.read() file.close() file = None - except Exception, ex: + except Exception as ex: if file: file.close() self.errorDialog(_("Unable to service request:\n") + url + "\n\n" + str(ex)) return @@ -493,7 +493,7 @@ to open the following URL: if fn in self.images: return self.images[fn] try: - img = Tkinter.PhotoImage(master=self.parent, file=fn) + img = tkinter.PhotoImage(master=self.parent, file=fn) except: img = None self.images[fn] = img @@ -517,7 +517,7 @@ def tkhtml_main(args): url = args[1] except: url = os.path.join(os.pardir, os.pardir, "data", "html", "index.html") - top = Tkinter.Tk() + top = tkinter.Tk() top.wm_minsize(400, 200) viewer = HTMLViewer(top) viewer.app = None diff --git a/pysollib/tk/tkstats.py b/pysollib/tk/tkstats.py index 6ab0f6f4..fc713bdd 100644 --- a/pysollib/tk/tkstats.py +++ b/pysollib/tk/tkstats.py @@ -33,7 +33,7 @@ __all__ = ['SingleGame_StatsDialog', # imports import os import time -import Tkinter, tkFont +import tkinter, tkinter.font # PySol imports from pysollib.mygettext import _, n_ @@ -44,9 +44,9 @@ from pysollib.stats import PysolStatsFormatter, ProgressionFormatter from pysollib.settings import TOP_TITLE # Toolkit imports -from tkutil import bind, unbind_destroy, loadImage -from tkwidget import MfxDialog, MfxMessageDialog -from tkwidget import MfxScrolledCanvas +from .tkutil import bind, unbind_destroy, loadImage +from .tkwidget import MfxDialog, MfxMessageDialog +from .tkwidget import MfxScrolledCanvas # FIXME - this file a quick hack and needs a rewrite @@ -77,7 +77,7 @@ class SingleGame_StatsDialog(MfxDialog): ## createChart = self.createSimpleChart # self.font = self.app.getFont("default") - self.tk_font = tkFont.Font(self.top, self.font) + self.tk_font = tkinter.font.Font(self.top, self.font) self.font_metrics = self.tk_font.metrics() self._calc_tabs() # @@ -131,14 +131,14 @@ class SingleGame_StatsDialog(MfxDialog): def _createChartInit(self, text): w, h = self.tab_x[-1]+20, self.tab_y[-1]+20 - c = Tkinter.Canvas(self.top_frame, width=w, height=h) + c = tkinter.Canvas(self.top_frame, width=w, height=h) c.pack(side='top', fill='both', expand=False, padx=20, pady=10) self.canvas = c ##self.fg = c.cget("insertbackground") self.fg = c.option_get('foreground', '') or c.cget("insertbackground") # c.create_rectangle(2, 7, w, h, fill="", outline="#7f7f7f") - l = Tkinter.Label(c, text=text, font=self.font, bd=0, padx=3, pady=1) + l = tkinter.Label(c, text=text, font=self.font, bd=0, padx=3, pady=1) dy = int(self.font_metrics['ascent']) - 10 dy = dy/2 c.create_window(20, -dy, window=l, anchor="nw") @@ -312,7 +312,7 @@ class CanvasFormatter(PysolStatsFormatter): tw = 15*self.w ##tw = 160 self._tabs = [tw] - font = tkFont.Font(self.canvas, self.font) + font = tkinter.font.Font(self.canvas, self.font) for t in arg[1:]: tw = font.measure(t)+20 self._tabs.append(tw) @@ -454,7 +454,7 @@ class AllGames_StatsDialog(MfxDialog): # lines = 20 # self.font = app.getFont(self.FONT_TYPE) - font = tkFont.Font(parent, self.font) + font = tkinter.font.Font(parent, self.font) self.font_metrics = font.metrics() self.CHAR_H = self.font_metrics['linespace'] self.CHAR_W = font.measure('M') @@ -532,9 +532,9 @@ class AllGames_StatsDialog(MfxDialog): ## FIXME / TODO return if gameid and gamenumber: - print gameid, gamenumber + print(gameid, gamenumber) elif gameid: - print gameid + print(gameid) # # @@ -643,37 +643,37 @@ class _TopDialog(MfxDialog): 'highlightthickness': 1, 'highlightbackground': 'black', } - frame = Tkinter.Frame(**cnf) + frame = tkinter.Frame(**cnf) frame.pack(expand=True, fill='both', padx=10, pady=10) frame.columnconfigure(0, weight=1) cnf['master'] = frame cnf['text'] = _('N') - l = Tkinter.Label(**cnf) + l = tkinter.Label(**cnf) l.grid(row=0, column=0, sticky='ew') cnf['text'] = _('Game number') - l = Tkinter.Label(**cnf) + l = tkinter.Label(**cnf) l.grid(row=0, column=1, sticky='ew') cnf['text'] = _('Started at') - l = Tkinter.Label(**cnf) + l = tkinter.Label(**cnf) l.grid(row=0, column=2, sticky='ew') cnf['text'] = _('Result') - l = Tkinter.Label(**cnf) + l = tkinter.Label(**cnf) l.grid(row=0, column=3, sticky='ew') row = 1 for i in top: # N cnf['text'] = str(row) - l = Tkinter.Label(**cnf) + l = tkinter.Label(**cnf) l.grid(row=row, column=0, sticky='ew') # Game number cnf['text'] = '#'+str(i.game_number) - l = Tkinter.Label(**cnf) + l = tkinter.Label(**cnf) l.grid(row=row, column=1, sticky='ew') # Start time t = time.strftime('%Y-%m-%d %H:%M', time.localtime(i.game_start_time)) cnf['text'] = t - l = Tkinter.Label(**cnf) + l = tkinter.Label(**cnf) l.grid(row=row, column=2, sticky='ew') # Result if isinstance(i.value, float): @@ -683,7 +683,7 @@ class _TopDialog(MfxDialog): # moves s = str(i.value) cnf['text'] = s - l = Tkinter.Label(**cnf) + l = tkinter.Label(**cnf) l.grid(row=row, column=3, sticky='ew') row += 1 @@ -704,7 +704,7 @@ class Top_StatsDialog(MfxDialog): top_frame, bottom_frame = self.createFrames(kw) self.createBitmaps(top_frame, kw) - frame = Tkinter.Frame(top_frame) + frame = tkinter.Frame(top_frame) frame.pack(expand=True, fill='both', padx=10, pady=10) frame.columnconfigure(0, weight=1) @@ -712,9 +712,9 @@ class Top_StatsDialog(MfxDialog): gameid in app.stats.games_stats[player] and app.stats.games_stats[player][gameid].time_result.top): - Tkinter.Label(frame, text=_('Minimum')).grid(row=0, column=1) - Tkinter.Label(frame, text=_('Maximum')).grid(row=0, column=2) - Tkinter.Label(frame, text=_('Average')).grid(row=0, column=3) + tkinter.Label(frame, text=_('Minimum')).grid(row=0, column=1) + tkinter.Label(frame, text=_('Maximum')).grid(row=0, column=2) + tkinter.Label(frame, text=_('Average')).grid(row=0, column=3) ##Tkinter.Label(frame, text=_('Total')).grid(row=0, column=4) s = app.stats.games_stats[player][gameid] @@ -755,17 +755,17 @@ class Top_StatsDialog(MfxDialog): ## s.score_casino_result.max, ## round(s.score_casino_result.average, 2), )) for l, min, max, avr, tot, top in ll: - Tkinter.Label(frame, text=l).grid(row=row, column=0) - Tkinter.Label(frame, text=str(min)).grid(row=row, column=1) - Tkinter.Label(frame, text=str(max)).grid(row=row, column=2) - Tkinter.Label(frame, text=str(avr)).grid(row=row, column=3) + tkinter.Label(frame, text=l).grid(row=row, column=0) + tkinter.Label(frame, text=str(min)).grid(row=row, column=1) + tkinter.Label(frame, text=str(max)).grid(row=row, column=2) + tkinter.Label(frame, text=str(avr)).grid(row=row, column=3) ##Tkinter.Label(frame, text=str(tot)).grid(row=row, column=4) - b = Tkinter.Button(frame, text=TOP_TITLE+' ...', width=10, + b = tkinter.Button(frame, text=TOP_TITLE+' ...', width=10, command=lambda top=top: self.showTop(top)) b.grid(row=row, column=5) row += 1 else: - Tkinter.Label(frame, text=_('No TOP for this game')).pack() + tkinter.Label(frame, text=_('No TOP for this game')).pack() focus = self.createButtons(bottom_frame, kw) self.mainloop(focus, kw.timeout) @@ -792,8 +792,8 @@ class ProgressionDialog(MfxDialog): def __init__(self, parent, title, app, player, gameid, **kw): font_name = app.getFont('default') - font = tkFont.Font(parent, font_name) - tkfont = tkFont.Font(parent, font) + font = tkinter.font.Font(parent, font_name) + tkfont = tkinter.font.Font(parent, font) font_metrics = font.metrics() measure = tkfont.measure self.text_height = font_metrics['linespace'] @@ -807,7 +807,7 @@ class ProgressionDialog(MfxDialog): top_frame, bottom_frame = self.createFrames(kw) self.createBitmaps(top_frame, kw) - frame = Tkinter.Frame(top_frame) + frame = tkinter.Frame(top_frame) frame.pack(expand=True, fill='both', padx=5, pady=10) frame.columnconfigure(0, weight=1) @@ -822,7 +822,7 @@ class ProgressionDialog(MfxDialog): self.won_color = '#00dc28' self.percent_color = 'blue' # create canvas - self.canvas = canvas = Tkinter.Canvas(frame, bg='#dfe8ff', + self.canvas = canvas = tkinter.Canvas(frame, bg='#dfe8ff', highlightthickness=1, highlightbackground='black', width=self.canvas_width, @@ -879,25 +879,25 @@ class ProgressionDialog(MfxDialog): canvas.create_text(x, y, anchor='sw', text=_('% won')) # right frame - right_frame = Tkinter.Frame(frame) + right_frame = tkinter.Frame(frame) right_frame.pack(side='left', fill='x', padx=5) - self.all_games_variable = var = Tkinter.StringVar() + self.all_games_variable = var = tkinter.StringVar() var.set('all') - b = Tkinter.Radiobutton(right_frame, text=_('All games'), + b = tkinter.Radiobutton(right_frame, text=_('All games'), variable=var, value='all', command=self.updateGraph, justify='left', anchor='w' ) b.pack(fill='x', expand=True, padx=3, pady=1) - b = Tkinter.Radiobutton(right_frame, text=_('Current game'), + b = tkinter.Radiobutton(right_frame, text=_('Current game'), variable=var, value='current', command=self.updateGraph, justify='left', anchor='w' ) b.pack(fill='x', expand=True, padx=3, pady=1) - label_frame = Tkinter.LabelFrame(right_frame, text=_('Statistics for')) + label_frame = tkinter.LabelFrame(right_frame, text=_('Statistics for')) label_frame.pack(side='top', fill='x', pady=10) - self.variable = var = Tkinter.StringVar() + self.variable = var = tkinter.StringVar() var.set('week') for v, t in ( ('week', _('Last 7 days')), @@ -905,32 +905,32 @@ class ProgressionDialog(MfxDialog): ('year', _('Last year')), ('all', _('All time')), ): - b = Tkinter.Radiobutton(label_frame, text=t, variable=var, value=v, + b = tkinter.Radiobutton(label_frame, text=t, variable=var, value=v, command=self.updateGraph, justify='left', anchor='w' ) b.pack(fill='x', expand=True, padx=3, pady=1) - label_frame = Tkinter.LabelFrame(right_frame, text=_('Show graphs')) + label_frame = tkinter.LabelFrame(right_frame, text=_('Show graphs')) label_frame.pack(side='top', fill='x') - self.played_graph_var = Tkinter.BooleanVar() + self.played_graph_var = tkinter.BooleanVar() self.played_graph_var.set(True) - b = Tkinter.Checkbutton(label_frame, text=_('Played'), + b = tkinter.Checkbutton(label_frame, text=_('Played'), command=self.updateGraph, variable=self.played_graph_var, justify='left', anchor='w' ) b.pack(fill='x', expand=True, padx=3, pady=1) - self.won_graph_var = Tkinter.BooleanVar() + self.won_graph_var = tkinter.BooleanVar() self.won_graph_var.set(True) - b = Tkinter.Checkbutton(label_frame, text=_('Won'), + b = tkinter.Checkbutton(label_frame, text=_('Won'), command=self.updateGraph, variable=self.won_graph_var, justify='left', anchor='w' ) b.pack(fill='x', expand=True, padx=3, pady=1) - self.percent_graph_var = Tkinter.BooleanVar() + self.percent_graph_var = tkinter.BooleanVar() self.percent_graph_var.set(True) - b = Tkinter.Checkbutton(label_frame, text=_('% won'), + b = tkinter.Checkbutton(label_frame, text=_('% won'), command=self.updateGraph, variable=self.percent_graph_var, justify='left', anchor='w' diff --git a/pysollib/tk/tktree.py b/pysollib/tk/tktree.py index 74c2b0eb..1099e6df 100644 --- a/pysollib/tk/tktree.py +++ b/pysollib/tk/tktree.py @@ -23,11 +23,11 @@ # imports import os -import Tkinter +import tkinter # Toolkit imports -from tkutil import bind -from tkwidget import MfxScrolledCanvas +from .tkutil import bind +from .tkwidget import MfxScrolledCanvas # ************************************************************************ @@ -104,7 +104,7 @@ class MfxTreeBaseNode: try: # _tkinter.TclError: unknown option "-fill" ??? canvas.itemconfig(self.textrect_id, fill=bg) - except Tkinter.TclError: + except tkinter.TclError: pass elif self.selected: b = canvas.bbox(self.text_id) @@ -276,7 +276,7 @@ class MfxTreeInCanvas(MfxScrolledCanvas): # draw try: lx, ly, nx, ny = node.draw(nx, ny, None, None) - except Tkinter.TclError: + except tkinter.TclError: # FIXME: Tk bug ??? raise # set scroll region @@ -372,7 +372,7 @@ class DirectoryBrowser(MfxTreeInCanvas): return node.subnodes # dir = node.key - print "Getting %s" % dir + print("Getting %s" % dir) try: filenames = os.listdir(dir) filenames.sort() @@ -388,7 +388,7 @@ class DirectoryBrowser(MfxTreeInCanvas): node = self.findNode(event) if not node: return - print "Clicked node %s %s" % (node.text, node.key) + print("Clicked node %s %s" % (node.text, node.key)) if isinstance(node, MfxTreeLeaf): self.updateSelection(key=node.key) elif isinstance(node, MfxTreeNode): @@ -398,7 +398,7 @@ class DirectoryBrowser(MfxTreeInCanvas): if __name__ == "__main__": - tk = Tkinter.Tk() + tk = tkinter.Tk() if os.name == "nt": app = DirectoryBrowser(tk, ("c:\\", "c:\\windows")) else: diff --git a/pysollib/tk/tkutil.py b/pysollib/tk/tkutil.py index 49c2e940..6c188505 100644 --- a/pysollib/tk/tkutil.py +++ b/pysollib/tk/tkutil.py @@ -47,8 +47,8 @@ __all__ = ['wm_withdraw', # imports import re -import Tkinter -from tkFont import Font +import tkinter +from tkinter.font import Font # PySol imports from pysollib.mfxutil import Image, ImageTk, ImageOps @@ -78,8 +78,8 @@ def wm_get_geometry(window): g = window.wm_geometry() m = __wm_get_geometry_re.search(g) if not m: - raise Tkinter.TclError("invalid geometry "+str(g)) - l = map(int, m.groups()) + raise tkinter.TclError("invalid geometry "+str(g)) + l = list(map(int, m.groups())) if window.wm_state() == "zoomed": # workaround as Tk returns the "unzoomed" origin l[2] = l[3] = 0 @@ -115,7 +115,7 @@ def makeToplevel(parent, title=None): # # This is a shortcut for a Toplevel() instantiation plus calls to # set the title and icon name of the window. - window = Tkinter.Toplevel(parent) #, class_=TITLE) + window = tkinter.Toplevel(parent) #, class_=TITLE) ##window.wm_group(parent) ##window.wm_command("") if WIN_SYSTEM == "x11": @@ -129,7 +129,7 @@ def makeToplevel(parent, title=None): def make_help_toplevel(app, title=None): # Create an independent Toplevel window. from pysollib.winsystems import init_root_window - window = Tkinter.Tk(className=TITLE) + window = tkinter.Tk(className=TITLE) init_root_window(window, app) return window @@ -215,7 +215,7 @@ def unbind_destroy(widget): ##widget.deletecommand(funcid) else: widget.unbind(sequence, funcid) - except Tkinter.TclError: + except tkinter.TclError: pass del __mfx_bindings[k] ##for k in __mfx_bindings.keys(): print __mfx_bindings[k] @@ -239,7 +239,7 @@ def after_cancel(t): t[2].after_cancel(t[0]) try: t[2].deletecommand(t[1]) - except Tkinter.TclError: + except tkinter.TclError: pass @@ -287,8 +287,8 @@ def makeImage(file=None, data=None, dither=None, alpha=None): return im # fromstring(mode, size, data, decoder_name='raw', *args) else: - return Tkinter.PhotoImage(data=data) - return Tkinter.PhotoImage(**kw) + return tkinter.PhotoImage(data=data) + return tkinter.PhotoImage(**kw) loadImage = makeImage @@ -296,7 +296,7 @@ def copyImage(image, x, y, width, height): if Image: if isinstance(image, PIL_Image): return ImageTk.PhotoImage(image._pil_image.crop((x, y, x+width, y+height))) - dest = Tkinter.PhotoImage(width=width, height=height) + dest = tkinter.PhotoImage(width=width, height=height) assert dest.width() == width assert dest.height() == height dest.blank() @@ -337,7 +337,7 @@ def fillImage(image, fill, outline=None): image.put(f) def createImage(width, height, fill, outline=None): - image = Tkinter.PhotoImage(width=width, height=height) + image = tkinter.PhotoImage(width=width, height=height) assert image.width() == width assert image.height() == height image.blank() diff --git a/pysollib/tk/tkwidget.py b/pysollib/tk/tkwidget.py index f41637da..ed616457 100644 --- a/pysollib/tk/tkwidget.py +++ b/pysollib/tk/tkwidget.py @@ -33,8 +33,8 @@ __all__ = ['MfxDialog', # imports import time -import Tkinter -import tkFont +import tkinter +import tkinter.font import traceback # PySol imports @@ -43,10 +43,10 @@ from pysollib.mfxutil import destruct, kwdefault, KwStruct, openURL from pysollib.settings import WIN_SYSTEM # Toolkit imports -from tkutil import after, after_cancel -from tkutil import bind, unbind_destroy -from tkutil import makeToplevel, setTransient -from tkcanvas import MfxCanvas +from .tkutil import after, after_cancel +from .tkutil import bind, unbind_destroy +from .tkutil import makeToplevel, setTransient +from .tkcanvas import MfxCanvas # ************************************************************************ @@ -79,7 +79,7 @@ class MfxDialog: # ex. _ToplevelDialog setTransient(self.top, self.parent) try: self.top.grab_set() - except Tkinter.TclError: + except tkinter.TclError: if traceback: traceback.print_exc() pass if timeout > 0: @@ -136,7 +136,7 @@ class MfxDialog: # ex. _ToplevelDialog def altKeyEvent(self, event): key = event.char - key = unicode(key, 'utf-8') + key = str(key, 'utf-8') key = key.lower() button = self.accel_keys.get(key) if button is not None: @@ -162,24 +162,24 @@ class MfxDialog: # ex. _ToplevelDialog return kw def createFrames(self, kw): - bottom_frame = Tkinter.Frame(self.top) + bottom_frame = tkinter.Frame(self.top) bottom_frame.pack(side='bottom', fill='both', expand=False, ipadx=3, ipady=3) if kw.separator: - separator = Tkinter.Frame(self.top, relief="sunken", + separator = tkinter.Frame(self.top, relief="sunken", height=2, width=2, borderwidth=1) separator.pack(side='bottom', fill='x') - top_frame = Tkinter.Frame(self.top) + top_frame = tkinter.Frame(self.top) top_frame.pack(side='top', fill='both', expand=True) return top_frame, bottom_frame def createBitmaps(self, frame, kw): if kw.bitmap: ## in ("error", "info", "question", "warning") img = self.img.get(kw.bitmap) - b = Tkinter.Label(frame, image=img) + b = tkinter.Label(frame, image=img) b.pack(side=kw.bitmap_side, padx=kw.bitmap_padx, pady=kw.bitmap_pady) elif kw.image: - b = Tkinter.Label(frame, image=kw.image) + b = tkinter.Label(frame, image=kw.image) b.pack(side=kw.image_side, padx=kw.image_padx, pady=kw.image_pady) def createButtons(self, frame, kw): @@ -215,10 +215,10 @@ class MfxDialog: # ex. _ToplevelDialog accel_indx = s.find('&') s = s.replace('&', '') if button < 0: - b = Tkinter.Button(frame, text=s, state="disabled") + b = tkinter.Button(frame, text=s, state="disabled") button = xbutton else: - b = Tkinter.Button(frame, text=s, default="normal", + b = tkinter.Button(frame, text=s, default="normal", command=(lambda self=self, button=button: self.mDone(button))) if button == kw.default: focus = b @@ -259,7 +259,7 @@ class MfxMessageDialog(MfxDialog): self.createBitmaps(top_frame, kw) # self.button = kw.default - msg = Tkinter.Label(top_frame, text=kw.text, justify=kw.justify, + msg = tkinter.Label(top_frame, text=kw.text, justify=kw.justify, width=kw.width) msg.pack(fill='both', expand=True, padx=kw.padx, pady=kw.pady) # @@ -282,7 +282,7 @@ class MfxExceptionDialog(MfxMessageDialog): t = "[Errno %s] %s:\n%s" % (ex.errno, ex.strerror, repr(ex.filename)) else: t = str(ex) - kw.text = text + unicode(t, errors='replace') + kw.text = text + str(t, errors='replace') MfxMessageDialog.__init__(self, parent, title, **kw.getKw()) @@ -299,15 +299,15 @@ class PysolAboutDialog(MfxMessageDialog): self.createBitmaps(top_frame, kw) # self.button = kw.default - frame = Tkinter.Frame(top_frame) + frame = tkinter.Frame(top_frame) frame.pack(fill='both', expand=True, padx=kw.padx, pady=kw.pady) - msg = Tkinter.Label(frame, text=kw.text, justify=kw.justify, + msg = tkinter.Label(frame, text=kw.text, justify=kw.justify, width=kw.width) msg.pack(fill='both', expand=True) - font = tkFont.Font(parent, app.getFont('default')) + font = tkinter.font.Font(parent, app.getFont('default')) font.configure(underline=True) - url_label = Tkinter.Label(frame, text=kw.url, font=font, + url_label = tkinter.Label(frame, text=kw.url, font=font, foreground='blue', cursor='hand2') url_label.pack() url_label.bind('<1>', self._urlClicked) @@ -332,10 +332,10 @@ class MfxSimpleEntry(MfxDialog): # self.value = value if label: - label = Tkinter.Label(top_frame, text=label, takefocus=0) + label = tkinter.Label(top_frame, text=label, takefocus=0) label.pack(pady=5) w = kw.get("e_width", 0) # width in characters - self.var = Tkinter.Entry(top_frame, exportselection=1, width=w) + self.var = tkinter.Entry(top_frame, exportselection=1, width=w) self.var.insert(0, value) self.var.pack(side='top', padx=kw.padx, pady=kw.pady) # @@ -434,11 +434,11 @@ class MfxTooltip: y = self.widget.winfo_rooty() + self.widget.winfo_height() x += self.xoffset y += self.yoffset - self.tooltip = Tkinter.Toplevel() + self.tooltip = tkinter.Toplevel() self.tooltip.wm_iconify() self.tooltip.wm_overrideredirect(1) self.tooltip.wm_protocol("WM_DELETE_WINDOW", self.destroy) - self.label = Tkinter.Label(self.tooltip, text=self.text, + self.label = tkinter.Label(self.tooltip, text=self.text, relief=self.relief, justify=self.justify, fg=self.fg, bg=self.bg, bd=1, takefocus=0) self.label.pack(ipadx=1, ipady=1) @@ -538,25 +538,25 @@ class MfxScrolledCanvas: def createFrame(self, kw): width = kw.get("width") height = kw.get("height") - self.frame = Tkinter.Frame(self.parent, width=width, height=height) + self.frame = tkinter.Frame(self.parent, width=width, height=height) def createCanvas(self, kw): bd = kw['bd'] kw['bd'] = 0 relief = kw['relief'] del kw['relief'] - frame = Tkinter.Frame(self.frame, bd=bd, relief=relief) + frame = tkinter.Frame(self.frame, bd=bd, relief=relief) frame.grid(row=0, column=0, sticky="news") self.canvas = MfxCanvas(frame, **kw) self.canvas.pack(expand=True, fill='both') def createHbar(self): - self.hbar = Tkinter.Scrollbar(self.frame, takefocus=0, + self.hbar = tkinter.Scrollbar(self.frame, takefocus=0, orient="horizontal") self.canvas["xscrollcommand"] = self._setHbar self.hbar["command"] = self.canvas.xview self.hbar.grid(row=1, column=0, sticky="we") self.hbar.grid_remove() def createVbar(self): - self.vbar = Tkinter.Scrollbar(self.frame, takefocus=0) + self.vbar = tkinter.Scrollbar(self.frame, takefocus=0) self.canvas["yscrollcommand"] = self._setVbar self.vbar["command"] = self.canvas.yview self.vbar.grid(row=0, column=1, sticky="ns") @@ -584,7 +584,7 @@ class MfxScrolledCanvas: #bind(w, '', self.mouse_wheel) def mouse_wheel(self, *args): - print 'MfxScrolledCanvas.mouse_wheel', args + print('MfxScrolledCanvas.mouse_wheel', args) def _setHbar(self, first, last): if self.canvas.busy: @@ -663,9 +663,9 @@ class StackDesc: text = stack.getHelp()+'\n'+stack.getBaseCard() text = text.strip() if text: - frame = Tkinter.Frame(self.canvas) + frame = tkinter.Frame(self.canvas) self.frame = frame - label = Tkinter.Message(frame, font=font, text=text, + label = tkinter.Message(frame, font=font, text=text, width=cardw-8, relief='solid', fg='#000000', bg='#ffffe0', bd=1) label.pack() diff --git a/pysollib/tk/tkwrap.py b/pysollib/tk/tkwrap.py index d300eed1..278d7dd1 100644 --- a/pysollib/tk/tkwrap.py +++ b/pysollib/tk/tkwrap.py @@ -25,11 +25,11 @@ __all__ = ['TclError', 'MfxRoot'] # imports -import Tkinter -TclError = Tkinter.TclError +import tkinter +TclError = tkinter.TclError # PySol imports -from tkconst import EVENT_PROPAGATE +from .tkconst import EVENT_PROPAGATE # ************************************************************************ @@ -37,9 +37,9 @@ from tkconst import EVENT_PROPAGATE # * Required so that a Game will get properly destroyed. # ************************************************************************ -class MfxRoot(Tkinter.Tk): +class MfxRoot(tkinter.Tk): def __init__(self, **kw): - Tkinter.Tk.__init__(self, **kw) + tkinter.Tk.__init__(self, **kw) self.app = None self.wm_protocol('WM_DELETE_WINDOW', self.wmDeleteWindow) # for interruptible sleep @@ -77,11 +77,11 @@ class MfxRoot(Tkinter.Tk): def setCursor(self, cursor): if 0: ## FIXME: this causes ugly resizes ! - Tkinter.Tk.config(self, cursor=cursor) + tkinter.Tk.config(self, cursor=cursor) elif 0: ## and this is even worse ##print self.children - for v in self.children.values(): + for v in list(self.children.values()): v.config(cursor=cursor) else: pass @@ -94,7 +94,7 @@ class MfxRoot(Tkinter.Tk): #time.sleep(seconds) self.after(int(seconds*1000)) return - print 'sleep', seconds + print('sleep', seconds) timeout = int(seconds*1000) self.sleep_var = 0 while timeout > 0: @@ -104,7 +104,7 @@ class MfxRoot(Tkinter.Tk): break self.after(100) timeout -= 100 - print 'finish sleep' + print('finish sleep') return if self.after_id: self.after_cancel(self.after_id) @@ -115,17 +115,17 @@ class MfxRoot(Tkinter.Tk): if self.after_id: self.after_cancel(self.after_id) self.after_id = None - print 'finish sleep' + print('finish sleep') def _sleepEvent(self, *args): return - print '_sleepEvent', args + print('_sleepEvent', args) self.interruptSleep() return EVENT_PROPAGATE def interruptSleep(self): return - print 'interruptSleep' + print('interruptSleep') self.update() self.update_idletasks() self.sleep_var = 1 @@ -137,7 +137,7 @@ class MfxRoot(Tkinter.Tk): # def update(self): - Tkinter.Tk.update(self) + tkinter.Tk.update(self) def wmDeleteWindow(self): if self.app and self.app.menubar: diff --git a/pysollib/tk/toolbar.py b/pysollib/tk/toolbar.py index 62bc98b5..7e7a2ab4 100644 --- a/pysollib/tk/toolbar.py +++ b/pysollib/tk/toolbar.py @@ -25,7 +25,7 @@ __all__ = ['PysolToolbarTk'] # imports import os -import Tkinter +import tkinter # PySol imports from pysollib.mygettext import _, n_ @@ -36,9 +36,9 @@ from pysollib.settings import TITLE from pysollib.winsystems import TkSettings # Toolkit imports -from tkconst import EVENT_HANDLED -from tkwidget import MfxTooltip -from menubar import createToolbarMenu, MfxMenu +from .tkconst import EVENT_HANDLED +from .tkwidget import MfxTooltip +from .menubar import createToolbarMenu, MfxMenu # ************************************************************************ @@ -74,21 +74,21 @@ class AbstractToolbarButton: self.grid_forget() -class ToolbarCheckbutton(AbstractToolbarButton, Tkinter.Checkbutton): +class ToolbarCheckbutton(AbstractToolbarButton, tkinter.Checkbutton): def __init__(self, parent, toolbar, toolbar_name, position, **kwargs): - Tkinter.Checkbutton.__init__(self, parent, kwargs) + tkinter.Checkbutton.__init__(self, parent, kwargs) AbstractToolbarButton.__init__(self, parent, toolbar, toolbar_name, position) -class ToolbarButton(AbstractToolbarButton, Tkinter.Button): +class ToolbarButton(AbstractToolbarButton, tkinter.Button): def __init__(self, parent, toolbar, toolbar_name, position, **kwargs): - Tkinter.Button.__init__(self, parent, kwargs) + tkinter.Button.__init__(self, parent, kwargs) AbstractToolbarButton.__init__(self, parent, toolbar, toolbar_name, position) -class ToolbarSeparator(Tkinter.Frame): +class ToolbarSeparator(tkinter.Frame): def __init__(self, parent, toolbar, position, **kwargs): - Tkinter.Frame.__init__(self, parent, kwargs) + tkinter.Frame.__init__(self, parent, kwargs) self.toolbar = toolbar self.position = position self.visible = False @@ -120,9 +120,9 @@ class ToolbarSeparator(Tkinter.Frame): class ToolbarFlatSeparator(ToolbarSeparator): pass -class ToolbarLabel(Tkinter.Message): +class ToolbarLabel(tkinter.Message): def __init__(self, parent, toolbar, toolbar_name, position, **kwargs): - Tkinter.Message.__init__(self, parent, kwargs) + tkinter.Message.__init__(self, parent, kwargs) self.toolbar = toolbar self.toolbar_name = toolbar_name self.position = position @@ -168,7 +168,7 @@ class PysolToolbarTk: self.orient = 'horizontal' self.button_pad = 2 # - self.frame = Tkinter.Frame(top, relief=TkSettings.toolbar_relief, + self.frame = tkinter.Frame(top, relief=TkSettings.toolbar_relief, bd=TkSettings.toolbar_borderwidth) # for l, f, t in ( @@ -258,7 +258,7 @@ class PysolToolbarTk: if Image: image = ImageTk.PhotoImage(Image.open(file)) else: - image = Tkinter.PhotoImage(file=file) + image = tkinter.PhotoImage(file=file) break return image @@ -409,7 +409,7 @@ class PysolToolbarTk: self.frame.update_idletasks() def updateText(self, **kw): - for name in kw.keys(): + for name in list(kw.keys()): label = getattr(self, name + "_label") label["text"] = kw[name] diff --git a/pysollib/tk/wizarddialog.py b/pysollib/tk/wizarddialog.py index 3294b652..028e4726 100644 --- a/pysollib/tk/wizarddialog.py +++ b/pysollib/tk/wizarddialog.py @@ -25,8 +25,8 @@ __all__ = ['WizardDialog'] # imports -import Tkinter -from tabpage import TabPageSet +import tkinter +from .tabpage import TabPageSet # PySol imports from pysollib.mygettext import _, n_ @@ -35,7 +35,7 @@ from pysollib.wizardutil import WizardWidgets from pysollib.wizardpresets import presets # Toolkit imports -from tkwidget import MfxDialog +from .tkwidget import MfxDialog # ************************************************************************ @@ -49,7 +49,7 @@ class WizardDialog(MfxDialog): top_frame, bottom_frame = self.createFrames(kw) self.createBitmaps(top_frame, kw) - frame = Tkinter.Frame(top_frame) + frame = tkinter.Frame(top_frame) frame.pack(expand=True, fill='both', padx=10, pady=10) frame.columnconfigure(0, weight=1) @@ -57,51 +57,51 @@ class WizardDialog(MfxDialog): notebook.pack(expand=True, fill='both') for w in WizardWidgets: - if isinstance(w, basestring): + if isinstance(w, str): p = notebook.AddPage(w) - frame = Tkinter.Frame(notebook.pages[w]['page']) + frame = tkinter.Frame(notebook.pages[w]['page']) frame.pack(expand=True, fill='both', padx=2, pady=4) frame.columnconfigure(1, weight=1) row = 0 continue - Tkinter.Label(frame, text=w.label).grid(row=row, column=0, padx=2) + tkinter.Label(frame, text=w.label).grid(row=row, column=0, padx=2) if w.widget == 'preset': if w.variable is None: - w.variable = Tkinter.StringVar() + w.variable = tkinter.StringVar() values = [_(v) for v in w.values] default = _(w.default) values.remove(default) values.sort() values.insert(0, default) callback = lambda v, w=w: self.presetSelected(v, w) - om = Tkinter.OptionMenu(frame, w.variable, + om = tkinter.OptionMenu(frame, w.variable, command=callback, *values) om.grid(row=row, column=1, sticky='ew', padx=2) elif w.widget == 'entry': if w.variable is None: - w.variable = Tkinter.StringVar() - en = Tkinter.Entry(frame, textvariable=w.variable) + w.variable = tkinter.StringVar() + en = tkinter.Entry(frame, textvariable=w.variable) en.grid(row=row, column=1, sticky='ew', padx=2) elif w.widget == 'menu': if w.variable is None: - w.variable = Tkinter.StringVar() + w.variable = tkinter.StringVar() values = [_(v) for v in w.values] - om = Tkinter.OptionMenu(frame, w.variable, *values) + om = tkinter.OptionMenu(frame, w.variable, *values) om.grid(row=row, column=1, sticky='ew', padx=2) elif w.widget == 'spin': if w.variable is None: - w.variable = Tkinter.IntVar() + w.variable = tkinter.IntVar() from_, to = w.values - s = Tkinter.Scale(frame, from_=from_, to=to, resolution=1, + s = tkinter.Scale(frame, from_=from_, to=to, resolution=1, orient='horizontal', length=200, variable=w.variable) s.grid(row=row, column=1, sticky='ew', padx=2) elif w.widget == 'check': if w.variable is None: - w.variable = Tkinter.BooleanVar() - ch = Tkinter.Checkbutton(frame, variable=w.variable, + w.variable = tkinter.BooleanVar() + ch = tkinter.Checkbutton(frame, variable=w.variable, takefocus=False, anchor='w') ch.grid(row=row, column=1, sticky='ew', padx=2, pady=2) @@ -125,7 +125,7 @@ class WizardDialog(MfxDialog): n = w.translation_map[v] p = presets[n] for w in WizardWidgets: - if isinstance(w, basestring): + if isinstance(w, str): continue if w.var_name in p: v = p[w.var_name] diff --git a/pysollib/winsystems/__init__.py b/pysollib/winsystems/__init__.py index 0847533c..666c7355 100644 --- a/pysollib/winsystems/__init__.py +++ b/pysollib/winsystems/__init__.py @@ -24,11 +24,11 @@ from pysollib.settings import WIN_SYSTEM if WIN_SYSTEM == 'win32': - import win32 as gui + from . import win32 as gui elif WIN_SYSTEM == 'aqua': - import aqua as gui + from . import aqua as gui else: # 'x11' - import x11 as gui + from . import x11 as gui init_root_window = gui.init_root_window TkSettings = gui.TkSettings diff --git a/pysollib/winsystems/aqua.py b/pysollib/winsystems/aqua.py index 8a4596d0..00dfa714 100644 --- a/pysollib/winsystems/aqua.py +++ b/pysollib/winsystems/aqua.py @@ -22,14 +22,14 @@ ##---------------------------------------------------------------------------## import sys, os -import Tkinter +import tkinter from pysollib.settings import TOOLKIT, USE_TILE if USE_TILE: from pysollib.tile import ttk from pysollib.macosx.appSupport import hideTkConsole -from common import base_init_root_window, BaseTkSettings +from .common import base_init_root_window, BaseTkSettings def init_root_window(root, app): @@ -46,7 +46,7 @@ def init_root_window(root, app): if app.opt.tile_theme == 'aqua': # standard Tk scrollbars work on OS X, but ttk ones look weird - ttk.Scrollbar = Tkinter.Scrollbar + ttk.Scrollbar = tkinter.Scrollbar else: # pure Tk #root.option_add(...) diff --git a/pysollib/winsystems/common.py b/pysollib/winsystems/common.py index 7987b935..bb16fbfa 100644 --- a/pysollib/winsystems/common.py +++ b/pysollib/winsystems/common.py @@ -61,7 +61,7 @@ def set_theme(app, top, theme): def get_font_name(font): # create font name # i.e. "helvetica 12" -> ("helvetica", 12, "roman", "normal") - from tkFont import Font + from tkinter.font import Font font_name = None try: f = Font(font=font) diff --git a/pysollib/winsystems/win32.py b/pysollib/winsystems/win32.py index cbbb3978..5875793c 100644 --- a/pysollib/winsystems/win32.py +++ b/pysollib/winsystems/win32.py @@ -27,7 +27,7 @@ from pysollib.settings import TOOLKIT, USE_TILE if USE_TILE: from pysollib.tile import ttk -from common import base_init_root_window, BaseTkSettings +from .common import base_init_root_window, BaseTkSettings def init_root_window(root, app): diff --git a/pysollib/winsystems/x11.py b/pysollib/winsystems/x11.py index 9faa49f5..388b7d1c 100644 --- a/pysollib/winsystems/x11.py +++ b/pysollib/winsystems/x11.py @@ -23,15 +23,15 @@ import sys, os, traceback -import Tkinter -import tkFont +import tkinter +import tkinter.font from pysollib.settings import TITLE from pysollib.settings import TOOLKIT, USE_TILE if USE_TILE: from pysollib.tile import ttk -from common import base_init_root_window, BaseTkSettings, get_font_name +from .common import base_init_root_window, BaseTkSettings, get_font_name # ************************************************************************ @@ -71,10 +71,10 @@ def init_root_window(root, app): except: traceback.print_exc() else: - import tkFileDialog - tkFileDialog.Open.command = 'ttk::getOpenFile' - tkFileDialog.SaveAs.command = 'ttk::getSaveFile' - tkFileDialog.Directory.command = 'ttk::chooseDirectory' + import tkinter.filedialog + tkinter.filedialog.Open.command = 'ttk::getOpenFile' + tkinter.filedialog.SaveAs.command = 'ttk::getSaveFile' + tkinter.filedialog.Directory.command = 'ttk::chooseDirectory' style = ttk.Style(root) color = style.lookup('.', 'background') diff --git a/pysollib/wizardutil.py b/pysollib/wizardutil.py index 3352d170..acd82e4b 100644 --- a/pysollib/wizardutil.py +++ b/pysollib/wizardutil.py @@ -27,7 +27,7 @@ from pysollib.gamedb import GI, loadGame from pysollib.util import * from pysollib.stack import * from pysollib.layout import Layout -from wizardpresets import presets +from .wizardpresets import presets from pysollib.mygettext import _, n_ @@ -64,7 +64,7 @@ class WizSetting: WizardPresets = WizSetting( - values_map = presets.keys(), + values_map = list(presets.keys()), default = 'None', widget = 'preset', label = _('Initial setting:'), @@ -387,7 +387,7 @@ class MyCustomGame(CustomGame): ''') for w in WizardWidgets: - if isinstance(w, basestring): + if isinstance(w, str): continue v = w.variable.get() if w.widget in ('menu', 'preset'): @@ -402,7 +402,7 @@ class MyCustomGame(CustomGame): # escape v = v.replace('\\', '\\\\') v = v.replace("'", "\\'") - if isinstance(v, unicode): + if isinstance(v, str): v = v.encode('utf-8') if not v: v = 'Invalid Game Name' @@ -422,7 +422,7 @@ registerCustomGame(MyCustomGame) def reset_wizard(game): for w in WizardWidgets: - if isinstance(w, basestring): + if isinstance(w, str): continue if game is None: # set to default