Skip to content

Instantly share code, notes, and snippets.

@umyuu
Last active August 23, 2018 17:47
Show Gist options
  • Save umyuu/edf91e3f540e0ce0c8027d8a93a9be62 to your computer and use it in GitHub Desktop.
Save umyuu/edf91e3f540e0ce0c8027d8a93a9be62 to your computer and use it in GitHub Desktop.

pythonで1つの変数をボタンで切り返したい。の回答 プログラミング初心者に対して、複数の議題を提示すると 初心者が混乱して話の流れが発散してしまうのでGistに回答内容を記載

◆ポイント Buttonウィジットではなく、Radiobuttonウィジットを使う。 変数:xtkinter.IntVarを使う。

以下は未テストコード。

A142673.py

import tkinter
from pathlib import Path

~
#ボタン123設定
~

x = tkinter.IntVar(1)
button1 = tkinter.Radiobutton(~, variable=x, value=1)
button2 = tkinter.Radiobutton(~, variable=x, value=2)
dir_test = ['Downloads','Documents']


def Test():
    # 再代入を伴わないのでglobal文を削除。
    directory = Path.home() / dir_test[x.get()]
    # file_typeではなくPathLibに合わせて変数名をsuffixに
    # https://docs.python.jp/3/library/pathlib.html#pathlib.PurePath.suffix
    suffixs = ('png',)
    for suffix in suffixs:
        (directory / suffix).mkdir(parents=True, exist_ok=True)
        for f in directory.glob('*.' + suffix):
            # Path#renameはwindows環境だとアトミック操作にならないためreplaceを使う。
            # https://github.com/python/cpython/blob/3.6/Lib/pathlib.py#L420
            # https://docs.python.jp/3/library/os.html#os.rename
            # >対象の上書きがクロスプラットフォームになる場合は replace() を使用してください。
            f.replace(directory / suffix / f.name)

            
button3['command'] = Test
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment