1

25 個のボタンがあり、それぞれが同じフォルダー内の一意のファイルにアクセスする GUI プログラムを作成しています。各ファイルに移動するようにそれぞれを個別にプログラムできることはわかっていますが、必要以上のコードのように思えます。これを行うためのより効率的な方法はありますか?コードは次のとおりです。

box1 = 'C:/Users/Geekman2/Documents/Tests/box1.txt
cupcake = Button(donut,text = "Box #1", command = open(box1))

このようにすると、すべてのファイルに対して変数を作成する必要があり、あまり効率的ではありません

PS混乱している場合は、ペストリーにちなんですべての変数に名前を付けます

4

1 に答える 1

1

次のようなコード スニペットを試してみます。

directory = 'C:/Users/Geekman2/Documents/Tests/'
...
def AddDirTo(filename)
     return directory + filename

次に、投稿したコードは次のようになります。

box1 = AddDirTo('box1.txt') #note: you did close box1's quote on your question
cupcake = Button(donut,text = "Box #1", command = open(box1))

質問のテイズから示されているように、持っているすべてのファイルがテキストファイルである場合は、次のようにすることもできます。

directory = 'C:/Users/Geekman2/Documents/Tests/'
extension = '.txt'
...
def AddDirTo(filename):
     return directory + filename + extension
...
box1 = AddDirTo('box1') #note: you did close box1's quote on your question
cupcake = Button(donut,text = "Box #1", command = open(box1))

directory一番上にあるand変数に反対票を投じようとしている人はextension、新しい関数を作成することなく、コードを他のディレクトリや拡張機能で再利用できるようになります。

于 2012-10-16T20:40:40.317 に答える