2011-08-22 137 views
1

這很難解釋,但我會盡我所能。如何使用if設置true/false變量?

我有我的代碼

def hideConsole(): 
    hideConsole = win32console.GetConsoleWindow() 
    win32gui.ShowWindow(hideConsole, 0) 

其中隱藏控制檯這一部分,我有這個部分,使其能夠

def onKeyboardEvent(event): 
    if event.KeyID == 192 and event.Alt == 32: 
     hideConsole() 
    return True 

我怎樣才能做一個「系統」裏,當我按一次組合鍵,控制檯隱藏,下一次,控制檯會顯示出來? (改hideConsole,值爲1)

+1

下面的答案是好的,但也要記住,如果其他東西可以顯示/隱藏控制檯,您需要選擇與該程序的其他玩家合作的最佳解決方案。 –

+0

儘管這裏不應該引起問題,但在風格上使用與包含函數具有相同名稱的本地變量是一個壞主意。畢竟這不是語法上的:'hideConsole'建議一個動作,而該變量不包含動作,而是一個事物。 'consoleToHide'可能是一個更好的變量名稱。 *不是你真的需要一個*;只需編寫'win32gui.ShowWindow(win32console.GetConsoleWindow(),0)''是完全正確的。 –

回答

1

您可以使用您在每次調用真假之間切換的功能屬性:

def toggleConsole(): 
    toggleConsole.show = not getattr(toggleConsole, "show", True) 
    console = win32console.GetConsoleWindow() 
    win32gui.ShowWindow(console, int(toggleConsole.show)) 

下面是一個簡單的例子這是如何工作的:

>>> def test(): 
...  test.show = not getattr(test, "show", True) 
...  print int(test.show) 
... 
>>> test() 
0 
>>> test() 
1 
>>> test() 
0 
+0

有一種感覺,這是Perl-ish相比做一個適當的類,但我喜歡它。簡單勝於複雜。 –

+0

美麗,以前從未想過這個。 –

0

可以使用的狀態變量hideValue使用初始值0,並且對於每個鍵盤事件做:

hideValue = 1 - hideValue 

這將切換hideValue 0和1之間

然後你可以撥打win32gui.ShowWindow(hideConsole, hideValue)

+0

這樣的技巧應該伴隨解釋性評論。使用布爾標誌和'not'會佔用更多線條,但更簡單。 – delnan

+0

使用布爾值更好(更易讀)。像這樣:'hidevalue = False',然後'hidevalue = not hidevalue' –

+0

@delnan,@Denilson我剛剛注意到使用名稱'showValue'而不是'hideValue'可讀性更強。關於切換布爾值或整數,我認爲它幾乎在同一層次上,但也許你是對的。 –

0

你需要以某種方式保持狀態:

hidden = False 

def toggleConsoleVisibility(): 
    global hidden 

    hideConsole = win32console.GetConsoleWindow() 
    win32gui.ShowWindow(hideConsole, 1 if hidden else 0) 
    hidden = not hidden 

def onKeyboardEvent(event): 
    if event.KeyID == 192 and event.Alt == 32: 
     toggleConsoleVisibility() 
    return True 

如果可能的話,寫爲類的一部分。然後,您可以保留由該類封裝的hidden變量,而不是在您的全局名稱空間中進行浮動。

+0

Python的三元'if'被寫爲' if else ',而不是'?:'。 –

+0

啊,是的,我使用多種語言,並將它們混合在一起。 :(感謝您的糾正 – cdhowie

+0

有幾個語法問題,但我喜歡這種方法 –

0
con_visible = True 

def setVisibility(visible): 
    global con_visible 
    hideConsole = win32console.GetConsoleWindow() 
    win32gui.ShowWindow(hideConsole, int(visible)) 
    con_visible = bool(visible) 

def onKeyboardEvent(event): 
    if event.KeyID == 192 and event.Alt == 32: 
     if con_visible: 
      setVisibility(False) 
     else: 
      setVisibility(True) 
    return True 

如果控制檯保持其可見性狀態在內部,你可以最好用這個來代替全局變量。

1

用布爾變量,像這樣:

class Console(object): 
    def __init__(self): 
     self.is_hidden = False 
     self.handle = win32console.GetConsoleWindow() 

    def toggle(self): 
     win32gui.ShowWindow(self.handle, 1 if self.is_hidden else 0) 
     self.is_hidden = not self.is_hidden 
+0

飛,遇見大錘,我喜歡它 –

+0

@Gringo Suave:對象方向很好正好兩件事:通過(多態)消息封裝狀態和通信,ASKA方法OO可以通過類或原型來實現,或者如果你很窮,通過閉包,或者如果你很差,通過函數指針。沒關係。在Python中你會使用一個類。 Cat的解決方案是明智而正確的方式,因爲它只是通過方法調用來封裝狀態並進行更改。 – pillmuncher

+0

是的,它的優雅,我喜歡它,並沒有說我沒有。只是覺得2或3行代碼很重。 –