我无法让 tkinter 更新一对简单的“应用程序全局”布尔变量以匹配相关复选框的变量。布尔值被初始化、更新并存储在一个文件中,并被另一个文件引用(只读)。无论复选框状态如何,布尔值都不会改变其默认值。(需要注意的一点:False/True 的初始值变为 0/1,可能是由于 tkinter impelements 布尔值的方式存在问题)。奇怪的是,对应于 tkinter 复选框表的类似“应用程序全局”布尔值表没有问题。该表是由第三个文件定义的类的实例。该表与简单布尔值位于相同的文件中(并以相同的方式处理)。
所有布尔值都在一个文件 (File1.py) 中使用(只读),并且仅由另一个文件 (File2.py) 修改。显式返回问题布尔值(从 File2.py 到 File1.py)不起作用。
使用的环境是带有 Pydev 2.7.32013031601 插件的 Eclipse Juno(4.2.2,构建 M20130204-1200)上的 Windows 7、Python 3.2.2。该应用程序正在从 Eclipse 控制台运行。
根据 LEGB 范围规则,一切似乎都正常(包含和全局语句存在,并且点分名称形式用于外部定义的“应用程序级别”全局变量)。正如我所看到的,要么所有布尔更新都应该工作,要么都不应该工作。那么为什么布尔表可以正常工作而简单的布尔值不能正常工作 - 以及需要什么才能让简单的布尔值正常工作?
推测,这是否与 python 将具有基本值(例如 0、1、2、3、True?False?)的变量实现为“共享值”而不是单独变量的方式有关 - 这会导致引用时出现问题这些来自其他模块的简单值?
示例应用程序由 3 个文件组成;每个都已尽可能减少,同时仍能显示问题。在 Windows 7 上运行时,您应该看到:
File1.py - 主线,包含回调函数“Get_User_Selections”:
from tkinter import *
from tkinter import ttk
import File2
#==========================================================================
def Get_User_Selections( ):
print( "\nDoAllReports=", File2.DoAllReports, "DoNoReports=", File2.DoNoReports )
if ( not File2.DoNoReports ) :
for row in range( len( File2.ChosenReports ) ):
for column in range( len( File2.ChosenReports[ 0 ] ) ) :
if ( File2.ChosenReports[ row ][ column ].get() or
File2.DoAllReports ) :
print( "Do report (", row, ',', column, ')' )
return
#==========================================================================
def CreateTheReports( *args ):
Get_User_Selections( )
return
#==========================================================================
''' *********** MAIN PROCEDURE ***************** '''
root = Tk()
root.title( 'tkinter Boolean problem' )
mainframe = ttk.Frame( root )
mainframe.grid( )
File2.ChooseReports( mainframe )
DoItButton = Button( mainframe, text = 'DO IT!', command = CreateTheReports )
DoItButton.grid()
root.mainloop()
#==========================================================================
File2.py - 定义 GUI,更新所有“应用程序级全局”布尔值:
from tkinter import *
# import the custom "GUI table" widgit class (which works as expected)
from TkinterCheckBoxTableClass import TkinterCheckBoxTableClass
# Determine the table "shape" (in the original application the strings become
# the row and column headers, these headers NOT shown by this example code).
RowTitles = [ "A", "B" ]
ColumnTitles = [ "1", "2", "3", "4" ]
DefaultReports = [ ]
for i in RowTitles :
for j in ColumnTitles :
DefaultReports = DefaultReports + [ False ]
# Initialize the three "APPLICATION LEVEL" global variables that preserve the
# user choices across invocations of the routine. Each invocation is caused
# by the user pressing the "DO IT!" button on the GUI.
ChosenReports = DefaultReports # table of user choices (works properly)
# These two "application" globals override the table (above) of individual
# choices. "DoNoReports" overrides "DoAllReports"; both override the table.
DoAllReports = False # does not work, value never changes
DoNoReports = False # does not work, value never changes
#==========================================================================
def ChooseReports( ParentFrame ):
# Purpose : Interface between the "application globals" and what appears
# on the GUI. Called from File1.py whenever user presses
# the "DO IT" button
global ChosenReports # "application" global, resides in this file
global DoAllReports # "application" global, resides in this file
global DoNoReports # "application" global, resides in this file
GuiTable = [ [ IntVar() for j in range( len( ColumnTitles ) ) ]
for i in range( len( RowTitles ) ) ]
ThisFrame = LabelFrame( ParentFrame, text = " Select Reports " )
ThisFrame.grid( row = 1, column = 0 )
DoAll = IntVar( value = DoAllReports )
DoNone = IntVar( value = DoNoReports )
SelectAll = Checkbutton( ThisFrame, variable = DoAll, text = "All",
onvalue = True, offvalue = False)
SelectAll.grid( row = 0, column = 1 )
SelectNone = Checkbutton( ThisFrame, variable = DoNone, text ='None',
onvalue = True, offvalue = False )
SelectNone.grid( row = 0, column = 2 )
TableFrame = LabelFrame( ThisFrame, background = 'grey',
borderwidth = 1, relief = FLAT )
TableFrame.grid( row = 1, column = 0, columnspan = 3, rowspan = 2 )
# Create the custom Checkbox Table, works without any problems.
ChooseTheReports = TkinterCheckBoxTableClass( FrameID = TableFrame,
UserSelections = GuiTable )
# Update the "application level" globals
DoAllReports = DoAll.get( )
DoNoReports = DoNone.get( )
ChosenReports = ChooseTheReports.getTable( )
# Passing back the above variables in the return statement did NOT work.
# Returning them shouldn't even be needed since a) they have "application"
# level scope, b) they reside in THIS file and c) are ONLY modified by THIS
# file (with the new values being accessible from other files).
return
#==========================================================================
TkinterCheckBoxTableClass.py - 实现布尔表:
'''
Implements a 2-D matrix (table) of tkinter checkboxes (for Python 3.x).
'''
from tkinter import *
from tkinter import ttk
class TkinterCheckBoxTableClass( object ):
'''
Python 3.x interface to a matrix (2-D table) of tkinter checkboxes.
Must pass a tkinter frame and the matrix to the constructor.
Class constructor parameters:
FrameID - tkinter parent frame that displays the table
UserSelections - matrix of True/False values passed to/from to GUI
Entire Table Methods:
getTable() - extracts 2-D array of UserSelections from tkinter
'''
'''----------------------------------------------------------------------'''
'''
Constructor
'''
def __init__( self , FrameID, UserSelections ) :
self.frameID = FrameID
self.userSelections = UserSelections
self.rowCount = max( 1, len( self.userSelections ) )
self.columnCount = max( 1, len( self.userSelections[ 0 ] ) )
self.checkBoxTable = [ [ IntVar() for j in range( self.columnCount ) ]
for i in range( self.rowCount ) ]
# Construct and display the table of tkinter checkboxes
for i in range( self.rowCount ) :
for j in range( self.columnCount ) :
self.checkBoxTable[i][j] = Checkbutton( self.frameID,
variable = self.userSelections[ i ][ j ],
onvalue = True, offvalue = False )
self.checkBoxTable[i][j].grid( row = i + 1, column = j + 1,
sticky = W )
'''----------------------------------------------------------------------'''
'''Methods:'''
def getTable( self ) :
for i in range( self.rowCount ) :
for j in range( self.columnCount ) :
self.checkBoxTable[i][j] = Checkbutton( self.frameID,
variable = self.userSelections[ i ][ j ],
onvalue = True,offvalue = False )
self.checkBoxTable[i][j].grid( row = i + 1, column = j + 1,
sticky = W )
return self.userSelections
''' END CLASS '''
顺便说一句,关于 PEP8:请参阅 PEP8 介绍之后的部分。;>) 我也很清楚“应用程序全局变量”和“创建通用包含文件并在任何地方导入”方法的优缺点;除非绝对没有其他简单的方法可以解决我的问题,否则我不希望使用它。(我更喜欢只在需要的地方导入模块。)